content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_config_from_json(json_file):
"""
Get the config from a json file
:param json_file:
:return: config(namespace) or config(dictionary)
"""
# parse the configurations from the config json file provided
with open(json_file, 'r') as config_file:
config_dict = json.load(config_file)... | 38,900 |
def create_polarimetric_layers(import_file, out_dir, burst_prefix, config_dict):
"""Pipeline for Dual-polarimetric decomposition
:param import_file:
:param out_dir:
:param burst_prefix:
:param config_dict:
:return:
"""
# temp dir for intermediate files
with TemporaryDirectory(prefi... | 38,901 |
def parse_args():
"""Parse argument values from command-line"""
parser = argparse.ArgumentParser(description='Arguments required for script.')
parser.add_argument('-t', '--job-type', required=True, choices=['process', 'analyze'], help='process or analysis')
args = parser.parse_args()
return args | 38,902 |
def test_send_mail():
"""should fail on incorrect email address"""
rv = send_mail('', 'hello, this is testing!')
rv_obj = json.loads(rv)
assert rv_obj['message'] == "'to' parameter is not a valid address. please check documentation"
# change email
rv = send_mail('testingmportertesting@gmail.... | 38,903 |
def Builtin_FLOOR(expr, ctx):
"""
http://www.w3.org/TR/sparql11-query/#func-floor
"""
l_ = expr.arg
return Literal(int(math.floor(numeric(l_))), datatype=l_.datatype) | 38,904 |
def upgrade():
"""Add snapshots table"""
op.create_table(
"snapshots",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("parent_id", sa.Integer(), nullable=False),
sa.Column("parent_type", sa.String(length=250), nullable=False),
sa.Column("child_id", sa.Integer(), nullable=Fa... | 38,905 |
def _compute_fwd_sol(raw_fname, trans_fname, src, bem, fwd_filename):
"""Compute leadfield matrix by BEM."""
mindist = 5. # ignore sources <= 0mm from inner skull
fwd = mne.make_forward_solution(raw_fname, trans_fname, src, bem,
mindist=mindist, meg=True, eeg=False,
... | 38,906 |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
## Initial call to print 0% progress
#printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
#for i, item in enumerate(items):
# # Do stuff...
# t... | 38,907 |
def get(target: str) -> tuple:
"""Fetches a document via HTTP/HTTPS and returns a tuple containing a boolean indicating the result of the request,
the URL we attempted to contact and the request HTML content in bytes and text format, if successful.
Otherwise, returns a tuple containing a boolean indicati... | 38,908 |
def init_logging() -> None:
"""Initialize logging system."""
args = parse_args()
dictConfig(CONFIG.LOGGING_CONFIG)
root = logging.getLogger()
root.setLevel(args["log"]) | 38,909 |
def create_info(tasks,input_chunk_name: str, output_layer_path: str, channel_num: int,
layer_type: str, data_type: str, encoding: str, voxel_size: tuple,
voxel_offset: tuple, volume_size: tuple, block_size: tuple, factor: tuple, max_mip: int):
"""Create metadata for Neuroglancer Pr... | 38,910 |
def DOM2ET(domelem):
"""Converts a DOM node object of type element to an ElementTree Element.
domelem: DOM node object of type element (domelem.nodeType == domelem.ELEMENT_NODE)
returns an 'equivalent' ElementTree Element
"""
# make some local variables for fast processing
tyCDATA = domelem.CD... | 38,911 |
def test_no_package_json():
"""Tests that there are errors when there is not an install.rdf or a
package.json"""
assert _do_config_test(
packagelayout.test_layout_all,
has_install_rdf=False,
has_package_json=False), (
'no errors and no install.rdf and package.json') | 38,912 |
def write_objective(n, terms):
"""
Writer function for writing out one or multiple objective terms.
Parameters
----------
n : pypsa.Network
terms : str/numpy.array/pandas.Series/pandas.DataFrame
String or array of strings which represent new objective terms, built
with :func:`li... | 38,913 |
async def on_ready():
"""起動時に通知してくれる処理"""
print('ログインしました')
print(client.user.name) # ボットの名前
print(client.user.id) # ボットのID
print(discord.__version__) # discord.pyのバージョン
print('------') | 38,914 |
def f_score(pr, gt, beta=1, eps=1e-7, threshold=.5):
"""dice score(also referred to as F1-score)"""
if threshold is not None:
pr = (pr > threshold).float()
tp = torch.sum(gt * pr)
fp = torch.sum(pr) - tp
fn = torch.sum(gt) - tp
score = ((1 + beta ** 2) * tp + eps) \
/ ((1 +... | 38,915 |
def makeSatelliteDir(metainfo):
"""
Make the directory name for the 'satellite' level.
"""
satDir = "Sentinel-" + metainfo.satId[1]
return satDir | 38,916 |
def parse_requirements(file_name):
"""Taken from http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy"""
requirements = []
for line in open(os.path.join(os.path.dirname(__file__), "config", file_name), "r"):
line = line.strip()
# comments and blank lines
if re.match(r"(^#)|(^$)", line):
continue
... | 38,917 |
def resolve_tagged_field(field):
"""
Fields tagged with `swagger_field` shoudl respect user definitions.
"""
field_type = getattr(field, SWAGGER_TYPE)
field_format = getattr(field, SWAGGER_FORMAT, None)
if isinstance(field_type, list):
# Ideally we'd use oneOf here, but OpenAPI 2.0 use... | 38,918 |
def grid_id_from_string(grid_id_str):
"""Convert
Parameters
----------
grid_id_str : str
The string grid ID representation
Returns
-------
ret : tuple of ints
A 4-length tuple representation of the dihedral id
"""
return tuple(int(i) for i in grid_id_str.split(',')) | 38,919 |
def adj_to_edge_index(adj):
"""
Convert an adjacency matrix to an edge index
:param adj: Original adjacency matrix
:return: Edge index representation of the graphs
"""
converted = []
for d in adj:
edge_index = np.argwhere(d > 0.).T
converted.append(edge_index)
return con... | 38,920 |
def determine_all_layers_for_elev(std_atmos, layers, values, elevation):
"""Determine all of the layers to use for the elevation
Args:
std_atmos [StdAtmosInfo]: The standard atmosphere
layers [<str>]: All the pressure layers
values [<LayerInfo>]: All the interpolated layers information
... | 38,921 |
def remove_redundant(
text: str,
list_redundant_words: List[str] = S_GRAM_REDUNDANT,
) -> str:
"""To remove phrases that appear frequently and that can not be used to infere skills.
Parameters
----------
text : str
The text to clean.
list_redundant_words : List[str], optional
... | 38,922 |
def main():
"""
ARGS:
None.
DESCRIPTION:
Driver function. Does all the analysis
RETURN:
DEBUG:
FUTURE:
1. Check suffixes for correct file types
"""
###### Check python version ######
if(sys.version_info[0] != 3):
exit_with_error("ERROR!!! Wrong python... | 38,923 |
def position_controller_mock():
"""
Position controller mock.
"""
mock = MagicMock(spec=PositionController)
future = asyncio.Future()
future.set_result(None)
mock.update_odometry = MagicMock(return_value=future)
return mock | 38,924 |
def create_report(mlflow_folder):
"""
# Creates a pandas dataframe from the mlflow logs of the input folder
# Parameters:
# mlflow_folder: path of the folder containing the mlflow logs
# Effects:
# It creates a Pandas dataframe for each experiment of the specified folder
"""
exp_n ... | 38,925 |
def trim(docstring):
"""PEP257 docstring indentation trim function."""
if not docstring:
return ""
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn'... | 38,926 |
def save_model(model, optimizer, output_dir, epoch_i, debug=False):
"""Save model and upload it to GCS."""
if debug:
return
save_dict = {
"model": model.state_dict(),
"optimizer": optimizer.state_dict(),
}
ckpt_dir = os.path.join(output_dir, "ckpts")
if not os.path.exists(ckpt_dir):
os... | 38,927 |
def forest_overview():
"""
The remove forest URL handler.
:return: The remove_forest.html page
"""
all_sensors = mysql_manager.get_all_sensors()
for sensor_module in all_sensors:
sensor_module['latest_measurements'] = mysql_manager.get_latest_measurements_from_sensor(sensor_m... | 38,928 |
def task_dev():
"""Run the main task for the project"""
return {
'actions': ["docker run --volume %s/:/app %s" % (CONFIG["project_root"], IMAGE)]
} | 38,929 |
def header_parse(header, ts_resolution):
"""
parses the header of a TOB3 frame.
Parameters
----------
header: string
of binary encoded dat with length of 12-Bytes
ts_resolution:
frame time resolution. multiplier for sub-second part of frame
timestamp to
acheive ... | 38,930 |
def testWebContainerProps(cfg):
"""Tests the setting of Web Container Properties."""
m = "testWebContainerProps:"
sop(m,"Entry.")
propName1 = "wsadminlib.test.foo"
propName2 = "wsadminlib.test.bar"
nodeName = cfg["nodeName"]
serverName = cfg["serverName"]
wc = getWebcontainer(nodeName,... | 38,931 |
def shuff_par_str(shuffle=True, str_type="file"):
"""
shuff_par_str()
Returns string from shuffle parameter to print or for a filename.
Optional args:
- shuffle (bool): default: True
- str_type (str): "print" for a printable string and "file" for a
string usab... | 38,932 |
def fft_imaginary(x: np.ndarray) -> np.ndarray:
""" Imaginary values of FFT transform
:param x: a numeric sequence
:return: a numeric sequence
"""
x_fft = np.fft.fft(x)
xt = np.imag(x_fft)
return xt | 38,933 |
def main(argv=None):
"""Entry point for the CLI interface
"""
parser = argparse.ArgumentParser()
parser.add_argument("darshanlogs", nargs="+", type=str, help="Darshan logs to process")
parser.add_argument('-t', '--threads', default=1, type=int,
help="Number of concurrent proc... | 38,934 |
def prodtype_to_platform(prods):
"""
Converts one or more prodtypes into a string with one or more <platform>
elements.
"""
if isinstance(prods, str):
return name_to_platform(prodtype_to_name(prods))
return "\n".join(map(prodtype_to_platform, prods)) | 38,935 |
def train_config_setting(config, dataset):
"""
Configuring parameter for training process
:param config: type dict: config parameter
:param dataset: type str: dataset name
:return: config: type dict: config parameter
"""
# Load max shape & channels of images and labels.
if config['read_... | 38,936 |
def parse_bool(value):
"""Parses a boolean value from a string."""
return _parse_value(value, BooleanField()) | 38,937 |
def load_dataset_X_y(dirname, opt):
"""
load training data
:param : dirname : str, loading target directory
:param : opt : str, option data format "pandas" or "numpy"
:return : data_X : numpy, training data
:return : data_y : numpy, true data
"""
# X
input_filename = di... | 38,938 |
def test_routing_policy_order(api_client, private_base_url):
"""
Test if APIAP implicit routing policy has a correct place in the chain.
"""
client = api_client()
response = client.get("/httpbin/get")
assert response.status_code == 200
echoed_request = EchoedRequest.create(response)
ass... | 38,939 |
def useDarwinButtons():
"""Use darwin styled buttons everywhere in app"""
qrainbowstyle.USE_DARWIN_BUTTONS = True
_logger.info("Darwin buttons style has been enabled") | 38,940 |
def connect_to_es(host, port, use_auth=False):
"""
Return client that's connected to an Elasticsearch cluster.
Unless running from authorized IP, set use_auth to True so that credentials are based on role.
"""
if use_auth:
http_auth = _aws_auth()
else:
http_auth = None
es = ... | 38,941 |
def task_5():
"""Задание 5"""
s = select([
student.c.name,
student.c.surname,
cast((student.c.stipend * 100), Integer)
])
print(str(s))
rp = connection.execute(s)
return rp.fetchall() | 38,942 |
def linked_tmp_dir(
suffix: Optional[str] = None,
prefix: Optional[str] = None,
dir: Optional[str] = None,
mkdirs: Optional[List[str]] = None,
lndirs: Optional[List[Tuple[str, str]]] = None,
lnfiles: Optional[List[Tuple[str, str]]] = None,
) -> Any:
"""
:param suffix:
:param prefix:... | 38,943 |
def sentinelCloudScore(img):
"""
Compute a custom cloud likelihood score for Sentinel-2 imagery
Parameters:
img (ee.Image): Sentinel-2 image
Returns:
ee.Image: original image with added ['cloudScore'] band
"""
im = sentinel2toa(img)
# Compute several indicators of cloudyness ... | 38,944 |
def safe_filename(name: str, file_ending: str = ".json") -> str:
"""Return a safe version of name + file_type."""
filename = re.sub(r"\s+", "_", name)
filename = re.sub(r"\W+", "-", filename)
return filename.lower().strip() + file_ending | 38,945 |
def group():
""" RESTful CRUD controller """
if auth.is_logged_in() or auth.basic():
pass
else:
redirect(URL(c="default", f="user", args="login",
vars={"_next":URL(c="msg", f="group")}))
module = "pr"
tablename = "%s_%s" % (module, resourcename)
table = s3db[tablename]... | 38,946 |
def gen_function():
"""Generate the next number in the sequence of iterations if the specified
conditions are met.
"""
global carry_on
a = 0
while (a < frame_num) & (carry_on):
yield a # Returns control and waits next call.
a = a + 1 | 38,947 |
def test_logconfig():
"""Config logger for test."""
global test_logger_inited
if test_logger_inited:
return
test_logger_inited = True
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
ch = query_stream_log_handler(logger)
ch.setLevel(logging.DEBUG)
ch.setFormatter... | 38,948 |
def _tracking_cost(time: int = 0, state: np.ndarray = None) -> float:
"""Tracking cost function.
The goal is to minimize the distance of the x/y position of the vehicle to the
'state' of the target trajectory at each time step.
Args:
time : Time of the simulation. Used for time-dependent cost ... | 38,949 |
def test_basic_meta(namespaceable, namespace):
"""Test the basic interactions between Namespaceable and metaclasses."""
class Meta(namespaceable, type(namespaceable)):
"""A throwaway test metaclass."""
with namespace() as namespace_:
meta_var = 1
class Test(namespaceable, metacl... | 38,950 |
def configure_logging(args, **kwargs):
"""run logging.basicConfig based on common verbosity command line arguments
"""
if args.debug:
logging.basicConfig(level=logging.DEBUG, **kwargs)
elif args.verbose:
logging.basicConfig(level=logging.INFO, **kwargs)
else:
logging.basicCon... | 38,951 |
def get_health_check(HealthCheckId=None):
"""
Gets information about a specified health check.
See also: AWS API Documentation
:example: response = client.get_health_check(
HealthCheckId='string'
)
:type HealthCheckId: string
:param HealthCheckId: [REQUIRED]
... | 38,952 |
def fixture_repo(repo_owner: str, repo_name: str) -> Repository:
"""Return a GitHub repository."""
return Repository(repo_owner, repo_name) | 38,953 |
def new_task(user, data: []):
"""
Create a new task and save it.
"""
Task(user=user, description=data[0], due_time=data[1]).save() | 38,954 |
def get_clean(source_file):
"""Generate a clean data frame from source file"""
print('Reading from source...')
df = pd.read_csv(source_file)
print('Cleaning up source csv...')
# Drop rows with too much NA data
df.drop(['Meter Id', 'Marked Time', 'VIN'], axis=1, inplace=True)
# Drop rows miss... | 38,955 |
def populate_db():
"""Populate the db with the common pop/rock songs file"""
songs = dm.parse_file('static/common_songs.txt')
freq_matrix = dm.get_frequency_matrix(songs)
model, clusters = clustering.clusterize(freq_matrix)
clustering.save(model, MODEL_FILENAME)
clusters_for_db = {}
try:
... | 38,956 |
def magenta_on_red(string, *funcs, **additional):
"""Text color - magenta on background color - red. (see sgr_combiner())."""
return sgr_combiner(string, ansi.MAGENTA, *funcs, attributes=(ansi.BG_RED,)) | 38,957 |
def test_list_ncname_max_length_nistxml_sv_iv_list_ncname_max_length_1_4(mode, save_output, output_format):
"""
Type list/NCName is restricted by facet maxLength with value 5.
"""
assert_bindings(
schema="nistData/list/NCName/Schema+Instance/NISTSchema-SV-IV-list-NCName-maxLength-1.xsd",
... | 38,958 |
def enabled(flag: str) -> bool:
"""
Returns whether an environment flag is enabled.
"""
return os.getenv(flag, "").lower() in ENABLED_SYMBOLS | 38,959 |
def create_entry(entry: Entry) -> int:
"""
Create an entry in the database and return an int of it's ID
"""
return create_entry(entry.title, entry.text) | 38,960 |
def process_document_bytes(
project_id: str,
location: str,
processor_id: str,
file_content: bytes,
mime_type: str = DEFAULT_MIME_TYPE,
) -> documentai.Document:
"""
Processes a document using the Document AI API.
Takes in bytes from file reading, instead of a file path
"""
# Th... | 38,961 |
def merge_imgs(imgs, cols=6, rows=6, is_h=True):
"""
合并图像
:param imgs: 图像序列
:param cols: 行数
:param rows: 列数
:param is_h: 是否水平排列
:param sk: 间隔,当sk=2时,即0, 2, 4, 6
:return: 大图
"""
import numpy as np
if not imgs:
raise Exception('[Exception] 合并图像的输入为空!')
img_shape =... | 38,962 |
def eval_model(model: transformer.Transformer, input_seq: torch.LongTensor, target_seq: torch.LongTensor) -> None:
"""Evaluates the the provided model on the given data, and prints the probabilities of the desired translations.
Args:
model (:class:`transformer.Transformer`): The model to evaluate.
... | 38,963 |
def get_nose_runner(report_folder, parallel=True, process_timeout=600, process_restart=True):
"""Create a nose execution method"""
def _run_nose(test_folders):
import nose
import os.path
if not report_folder or not os.path.exists(report_folder) or not os.path.isdir(report_folder):
... | 38,964 |
def text_editor():
"""Solution to exercise R-2.3.
Describe a component from a text-editor GUI and the methods that it
encapsulates.
--------------------------------------------------------------------------
Solution:
--------------------------------------------------------------------------
... | 38,965 |
def generate_imm5(value):
"""Returns the 5-bit two's complement representation of the number."""
if value < 0:
# the sign bit needs to be bit number 5.
return 0x1 << 4 | (0b1111 & value)
else:
return value | 38,966 |
def test_scope_invalid(app: Flask, indieauthfix: IndieAuthActions, client: FlaskClient):
"""Requests usint a key not scoped for them should fail"""
with app.app_context():
z2btd = indieauthfix.zero_to_bearer_with_test_data(scopes=["create"])
actest_value = "an testing value,,,"
headers =... | 38,967 |
def SetNodeThumbnailEnabled():
""" None """
pass | 38,968 |
def CalculateChiv6p(mol):
"""
#################################################################
Calculation of valence molecular connectivity chi index for
path order 6
---->Chiv6
Usage:
result=CalculateChiv6p(mol)
Input: mol is a molecule object.... | 38,969 |
def _cart2sph(x,y,z):
"""A function that should operate equally well on floats and arrays,
and involves trignometry...a good test function for the types of
functions in geospacepy-lite"""
r = x**2+y**2+z**2
th = np.arctan2(y,x)
ph = np.arctan2(x**2+y**2,z)
return r,th,ph | 38,970 |
def get_existing_key_pair(ec2: EC2Client, keypair_name: str) -> Optional[KeyPairInfo]:
"""Get existing keypair."""
resp = ec2.describe_key_pairs()
keypair = next(
(kp for kp in resp.get("KeyPairs", {}) if kp.get("KeyName") == keypair_name),
None,
)
if keypair:
LOGGER.info(
... | 38,971 |
def render_template(template: str, context: dict,
trim_blocks=True, lstrip_blocks=True,
**env_kwargs):
"""
One-time-use jinja environment + template rendering helper.
"""
env = jinja2.Environment(
loader=jinja2.DictLoader({'template': template}),
t... | 38,972 |
def _func_to_user(uid, func):
"""
Internal function for doing actions against a user. Gets the user from
the database, calls the provided function, and then updates the user
back in the database.
Args:
uid (string) -- The user's key
func (function) -- activity to perform on the use... | 38,973 |
def exp():
"""An experiment to compute the relative error.
Arguments:
c -- a coordinate represented as a (lat, lon) tuple
"""
#olney transportation center
p1 = (40.040042, -75.144772)
#att station
p2 = (39.907473, -75.173907)
#the distance, taking into account curvature of the... | 38,974 |
def execute(work_db, dist=True):
"""Execute any pending work in `work_db`, recording the results.
This looks for any work in `work_db` which has no results, schedules to be
executed, and records any results that arrive.
If `dist` is `True` then this uses Celery to distribute tasks to remote
worker... | 38,975 |
def breg_sim_divergence(K, p, q, symmetric=False):
# NOTE: if you make changes in this function, do them in *_stable function under this as well.
"""
Compute similarity sensitive Bregman divergence of between a pair of (batches of)
distribution(s) p and q over an alphabet of n elements. Inputs:
... | 38,976 |
def manage_pages(request):
"""Dispatches to the first page or to the form to add a page (if there is no
page yet).
"""
try:
page = Page.objects.all()[0]
url = reverse("lfs_manage_page", kwargs={"id": page.id})
except IndexError:
url = reverse("lfs_add_page")
return HttpR... | 38,977 |
def get_network_info():
"""
Sends a NETWORK_INTERFACES_INFO command to the server.
Returns a dict with:
- boolean status
- list of str ifs (network interfaces detected by RaSCSI)
"""
command = proto.PbCommand()
command.operation = proto.PbOperation.NETWORK_INTERFACES_INFO
data = sen... | 38,978 |
def setFigStyle(): # fancyPlots=False): # TODO: Merge this with setFigOutput
"""Set figure style"""
global fancyPlots
global colours
if fancyPlots:
try:
import seaborn as sns
#cp = sns.color_palette()
colours = sns.color_palette()
except ImportError:
... | 38,979 |
def basis(asset: Asset, termination_tenor: str, *, source: str = None, real_time: bool = False,
request_id: Optional[str] = None) -> Series:
"""
GS end-of-day cross-currency basis swap spread.
:param asset: asset object loaded from security master
:param termination_tenor: relative date repre... | 38,980 |
def env_path_contains(path_to_look_for, env_path=None):
"""Check if the specified path is listed in OS environment path.
:param path_to_look_for: The path the search for.
:param env_path: The environment path str.
:return: True if the find_path exists in the env_path.
:rtype: bool
"""
if no... | 38,981 |
def jp_clean_year(string, format):
"""Parse the date and return the year."""
return getYearFromISODate(iso8601date(string,format)) | 38,982 |
def _epsilon(e_nr, atomic_number_z):
"""For lindhard factor"""
return 11.5 * e_nr * (atomic_number_z ** (-7 / 3)) | 38,983 |
def compute_heatmap(cnn_model, image, pred_index, last_conv_layer):
"""
construct our gradient model by supplying (1) the inputs
to our pre-trained model, (2) the output of the (presumably)
final 4D layer in the network, and (3) the output of the
softmax activations from the model
"""
gradM... | 38,984 |
def did_git_push_succeed(push_info: git.remote.PushInfo) -> bool:
"""Check whether a git push succeeded
A git push succeeded if it was not "rejected" or "remote rejected",
and if there was not a "remote failure" or an "error".
Args:
push_info: push info
"""
return push_info.flags & GIT... | 38,985 |
def end_h_nl_constraint(ocp: AcadosOcp, nl_expr, lower_upper: Union[float, tuple],
sq_penalty: Union[float, tuple] = 0, lin_penalty: Union[float, tuple] = 0):
"""
Add a terminal non-linear constraints with lower and upper bound.
Generates the lower, upper and slack variables, and opt... | 38,986 |
def find_only(element, tag):
"""Return the only subelement with tag(s)."""
if isinstance(tag, six.string_types):
tag = [tag]
found = []
for t in tag:
found.extend(element.findall(t))
assert len(found) == 1, 'expected one <%s>, got %d' % (tag, len(found))
return found[0] | 38,987 |
async def mongoengine_invalid_document_exception_handler(request, exc):
"""
Error handler for InvalidDocumentError.
Logs the InvalidDocumentError detected and returns the
appropriate message and details of the error.
"""
logger.exception(exc)
return JSONResponse(
Response(succes... | 38,988 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up Daikin climate based on config_entry."""
entities = []
config = entry.data
for controller in hass.data[DOMAIN][CONTROLLERS].values():
try:
entity = DaikinMadokaClimate(controller)
entities.append(en... | 38,989 |
def gen_2Dsersic(size,parameters,normalize=False,show2Dsersic=False,savefits=False,verbose=True):
"""
Generating a 2D sersic with specified parameters using astropy's generator
--- INPUT ---
size The dimensions of the array to return. Expects [ysize,xsize].
The 2D gauss will ... | 38,990 |
def test_staking(testerchain, token, escrow_contract):
"""
Tests for staking methods: deposit, lock and stake division
"""
escrow = escrow_contract(1500)
creator = testerchain.interface.w3.eth.accounts[0]
ursula1 = testerchain.interface.w3.eth.accounts[1]
ursula2 = testerchain.interface.w3.... | 38,991 |
async def basic_tests():
"""Run Basic tests."""
es = ElasticSearchClient()
await es.get_all_indices()
await es.create_index(0)
await es.clear_index(0)
await es.close() | 38,992 |
def dqn(agent, env, brain_name, n_episodes=2500, max_t=1000, eps_start=1.0,
eps_end=0.01, eps_decay=0.999, train=True):
"""Deep Q-Learning.
Params
======
n_episodes (int): maximum number of training episodes
max_t (int): maximum number of timesteps per episode
eps_start (flo... | 38,993 |
def get_activity_stats_subprocess(
data_full: list[ActivitiesUsers], data_cp: list[ActivitiesUsers]
) -> DestinyActivityOutputModel:
"""Run in anyio subprocess on another thread since this might be slow"""
result = DestinyActivityOutputModel(
full_completions=0,
cp_completions=0,
ki... | 38,994 |
def execute(db_name):
"""Execute any pending work in the database stored in `db_name`,
recording the results.
This looks for any work in `db_name` which has no results, schedules it to
be executed, and records any results that arrive.
"""
try:
with use_db(db_name, mode=WorkDB.Mode.open)... | 38,995 |
def ma_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Array2d]:
"""Caching function for `vectorbt.indicators.basic.MA`."""
cache_dict = dict()
for i in range(len(windows)):
h = hash((windows[i], ewms[i]))
if h not in c... | 38,996 |
def get_AllVolumes(controller, secondary=None):
"""Run smcli command 'show AllVolumes' on the controller, the output is
returned to the calling function.
The primary controller (a) is mandatory, but the secondary controller
(b) is optional."""
# Check which controller is reachable.
... | 38,997 |
def sync(
path: Path = PROJECT_PATH_ARGUMENT,
prompt: bool = typer.Option(
False,
"--prompt",
"-p",
help="Pass to enable answering template prompts",
show_default=False,
),
quiet: bool = QUIET_OPTION,
):
"""
Syncs manual changes to the flexlate branches, a... | 38,998 |
def fetch_slot_freq_num(timestamp, slot, freq_nums):
"""Find GLONASS frequency number in glo_freq_nums and return it.
Parameters
----------
timestamp : datetime.datetime
slot : int
GLONASS satellite number
freq_nums : dict
{ slot_1: { datetime_1: freq-num, ... } }
Returns
... | 38,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.