content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def exchange_ecYeast(s1, subystem):
"""
this function is used to define the exchange reaction
s1=['a --> b','a <=> c', 'H+ [extracellular] + L-citrulline [extracellular] <=> H+ [cytoplasm] L-citrulline [cytoplasm]', ' a--> ']
subsystem = ['a','a','b','']
"""
for i, x in enumerate(s1):
p... | 0f8eb84b3270c910acd673491238d52b2744f68c | 3,603,800 |
import traceback
def search(user: User, start_time, end_time, date, room_id):
"""
返回座位列表
:param user:
:param start_time:
:param end_time:
:param date:
:param room_id:
:return:
"""
try:
search_json = user.search_seat(start_time, end_time, date, room_id)
if search... | 643c4cd79a47a03c7427f5b1d78e09f2642634cf | 3,603,801 |
import functools
def _check_length(func):
"""Wrapper which checks the length of inputs to set_X
Eg:
@_check_length
def set_X(self, group, values):
Will check the length of *values* compared to *group* before proceeding with
anything in the *set_X* method.
Pseudo code for the check:
... | 8d6f6e0a082472f4eb58c3246717266508a95e3c | 3,603,802 |
from typing import Optional
def get_in_reply_to(event: nio.Event) -> Optional[str]:
"""
Pulls an in reply to event ID from an event, if any.
"""
return event.source.get("content", {}).get("m.relates_to", {}).get("m.in_reply_to", {}).get("event_id") | 2331b2b8eff59c1f9c36af2ad5f3ce3def571e10 | 3,603,803 |
def readResults(file_name, _start_time, _end_time):
"""Read micro-data from file_name, structured on a separate line per year. In particular, read from start_year until
end_year, both inclusive"""
# Read list of float values, one per household
data_float = []
with open(file_name, "r") as _f:
... | 4ca6bb102b0605d3472430725a8349fa891dd247 | 3,603,804 |
def move_and_check_if_over(game: GameBoard, current_player: Player,
move: Move) -> Player:
"""
This method is invoked from the main Game Runner utility to perform
a move selected by the Current player and check if this move opted by
the user gave him a winning board.
In o... | 84fc7bd05caab51d456dff61e4d61ebf57dd57fc | 3,603,805 |
async def get_research_by_player(keys, context):
"""Get researches."""
where, values = compound_where(keys, ('match_id', 'player_number'))
query = """
select name, started::interval(0), finished::interval(0), player_number, match_id,
extract(epoch from started)::integer as started_secs, extr... | 0468786e1d08e46bcbcbf59e471e5117454049cd | 3,603,806 |
import subprocess
import os
def run_nodejs(js_filename):
""" Run given file in nodejs and capture output """
proc = subprocess.Popen(
['node', js_filename], stdout=subprocess.PIPE)
outs, _ = proc.communicate(timeout=10)
outs = outs.decode('ascii', errors='ignore')
outs = outs.replace(os.... | 623c4201638272dfb40a35d7ce1ddb6949eed39a | 3,603,807 |
import requests
def create_client(hostname, port, reauth=False, logins=[]):
"""Create Docker client
Args:
-----
reauth: (boolean) Forces reauthentication e.g. Docker login
"""
base_url = "tcp://{0}:{1}".format(hostname, port)
try:
client = docker.APIClient(base_url=base_url)
... | a17e4672f0bc58d2512cc5c8d82d2be5cdf2b9c3 | 3,603,808 |
def pendulum_duration_from_isodate_duration(dur: IsodateDuration) -> Duration:
"""
Converts a :class:`isodate.isoduration.Duration` into a
:class:`pendulum.Duration`.
Both :class:`isodate.isoduration.Duration` and :class:`pendulum.Duration`
incorporate an internal representation of a :class:`dateti... | 9ed2ab0ce6dcddafdd3b7bb1933209eed85bd8f1 | 3,603,809 |
import time
def compute_perplexity(model, sess, name, eval_handle):
"""Compute perplexity of the output of the model based on loss function."""
def aggregate_all_summaries(original, updates):
for key in updates:
if key not in original:
original[key] = 0.0
original[key] += updates[key]
... | 126b6e87b9c700289438eccec3301f9416d3ae1d | 3,603,810 |
def array_pack(img):
"""
img: numpy array. I primarily use this for OpenCV images
"""
d = img.tobytes()
s = img.shape
t = img.dtype
return (s, t, d) | e01398caf1018000d0dabd776945a223e39b130b | 3,603,811 |
def new_gauge(name):
"""
Build a new "gauge" metric
"""
return new_metric(name, simple_metrics.Gauge) | 7452fe823a7b72beb8cf877012c1849558b03ca7 | 3,603,812 |
def create_cons_seq(seq: str, df_vcf: pd.DataFrame) -> str:
"""Create consensus sequence given a reference sequence and a table of a Snippy vcf_to_tab
Args:
seq: Reference sequence
df_vcf: VCF file DataFrame
Returns:
Consensus sequence
"""
segments = []
prev_position = ... | 7db0116574ea7965f064d030a6d00ce580da66a6 | 3,603,813 |
from typing import Dict
from typing import List
def get_notice_tokens() -> Dict[str, List[str]]:
"""Tokenised Covid notices."""
run_id = sg_covid_impact.config["flows"]["notice_tokens"]["run_id"]
return flow_getter("NoticeTokeniseFlow", run_id=run_id).docs | 645e460488d9fdc03048fabaa2d0baf1ea0d94fc | 3,603,814 |
import torch
def run_test_adversarial(net, loader, epsilon):
"""
This function is responsible to evaluate the model robustness against an FGSM attack on the given data loader.
Args:
net: a CNN model.
loader: a pytorch data loader that load either validation or test set samples
epsi... | 0ba78d792a5a0322095b76dae476f91243fb2fb9 | 3,603,815 |
def _build_rotation_dataset(imfiles, imshape=(256,256), batch_size=256,
num_parallel_calls=None, norm=255,
num_channels=3, augment=False,
single_channel=False):
"""
"""
ds = _image_file_dataset(imfiles, shuffle=True, augment=augment,
... | 87a748829578b7c44979554f4b329765906640b8 | 3,603,816 |
def get_taxes(tu):
""" Calculates taxes by running taxcalc on a tax unit DataFrame.
Args:
tu: Tax unit DataFrame.
Returns:
Series with tax liability for each tax unit.
"""
return mdf.calc_df(records=tc.Records(tu, weights=None, gfactors=None),
# year doesn't ... | 6ece3d327c18b00f8470c8e4b8e09444327ae80e | 3,603,817 |
def getref():
"""Current default values for graph and component tables, primary area,
and wavelength set.
.. note::
Also see :func:`setref`.
Returns
-------
ans : dict
Mapping of parameter names to their current values.
"""
ans=dict(graphtable=GRAPHTABLE,
... | 91671bde04c8e60f1d2af2da1a28cc35adb96a49 | 3,603,818 |
def _normalize_type(the_type):
"""
A single entry point for parsing the type.
This assumes that enums and optional properties have been
taken care of.
Parameters
----------
the_type : str
The type string extracted from the docs
Returns
-------
norm_type : str
T... | 3a6ac79bb655fc3aa2751f1c1a179d8a95082229 | 3,603,819 |
import yaml
def kv_string2dict(s):
"""Convert a key-value string: k=v,k2=v2,... into a dictionary
"""
return yaml.load(s.replace(",", "\n").replace("=", ": ")) | 78380d6735dc139afe5879aee7d25e5adf7d7e0d | 3,603,820 |
def auto_histogram(x, **histogram_opts):
"""Auto version of :func:`~xyzpy.histogram` that accepts array arguments
by converting them to a ``Dataset`` first.
"""
return AutoHistogram(x, **histogram_opts)() | 8a1e4e52669bed58f0603fca7f00e729bd1d25f1 | 3,603,821 |
def test_idempotent_persistence_exception_getting(
persistence_store,
lambda_apigw_event,
timestamp_future,
lambda_response,
hashed_idempotency_key,
expected_params_put_item,
):
"""
Test idempotent decorator when lambda is executed with an event with a previously unknown event key, but
... | 0d82bd10d2560096b907e54316863ca3dc6384f7 | 3,603,822 |
def select_number(list_of_numbers):
"""The player select *one* number of a list of numbers"""
answer = ""
while ((not answer.isdecimal()) or int(answer) not in list_of_numbers):
answer = input("Please type selected number and press ENTER: ")
return int(answer) | af91b18508ff361b0524a551949aac7d93f9afc6 | 3,603,823 |
def compose_context_fst(ifst1, ifst2, connect=True, compose_filter="auto"):
"""Composes context FST with an FST over the tropical semiring.
Args:
ifst1 (StdContextFst): The input context FST over the tropical semiring.
ifst2 (StdFst): The input FST over the tropical semiring.
connect (b... | 8dfc0f1ba01d42ca10ab1965dd5e2f491182396d | 3,603,824 |
def welcome():
"""最简单的接口
"""
return 'Hello World' | 5ae25fb699343bb48cdf113dc783a37290b3c38a | 3,603,825 |
def create_mel_filterbank(sample_rate, frame_len, num_bands, min_freq,
max_freq, crop=False):
"""
Creates a mel filterbank of `num_bands` triangular filters, with the first
filter starting at `min_freq` and the last one stopping at `max_freq`.
Returns the filterbank as a matrix... | c7c1b46e2d092128db42dce1a58e80b1be735e9d | 3,603,826 |
import numpy
def _time_zone_string_to_utc_offset(time_zone_string):
"""Converts time zone from string to UTC offset.
:param time_zone_string: String describing time zone (examples: "PST",
"MST", etc.).
:return: utc_offset_hours: Local time minus UTC.
"""
time_zone_string = time_zone_stri... | 063622222372c8eeb7f69e1240058088ef65fa2f | 3,603,827 |
import logging
def uc_exp(params, inputFilesFormatString):
"""Universal circuit creation.
params should be a tuple containing (inputLength, numberOfGates)
"""
inputLength, numberOfGates = params
logging.warning('Starting UC generation for %d inputs and %d gates' % params)
ioGen = IndistinguishabilityObfuscat... | b728bb6464e33b025ec54004edc0ec2658a32041 | 3,603,828 |
def cast(s):
""" Function which clarifies the implicit type of
strings, a priori coming from csv-like files.
Example
-------
>>> cast('1')
1
>>> cast('1.')
1.0
>>> cast('1E+0')
1.0
>>> cast('1E+1')
10.0
>>> cast('one')
'one'
>>> cast('One')
'one'
"""
... | 5e2c9b3b913a733608cab614ae0f08421e489196 | 3,603,829 |
def is_macosx_sdk_path(path):
"""
Returns True if 'path' can be located in an OSX SDK
"""
return (path.startswith('/usr/') and not path.startswith('/usr/local')) or path.startswith('/System/') | 59b60fa00bf6dd10cf207e6421ea3e4828de5b9c | 3,603,830 |
def box_iou_np(boxes1: ndarray, boxes2: ndarray) -> ndarray:
"""
Return intersection-over-union (Jaccard index) of boxes.
(Works for ndarrays and Numpy Arrays)
Arguments:
boxes1 (ndarray): boxes; (x1, y1, x2, y2, (z1, z2))[N, dim * 2]
boxes2 (ndarray): boxes; (x1, y1, x2, y2, (z1, z2))[... | 39635de601a725ae34ad881bb42cc0b75151eb46 | 3,603,831 |
import math
def _mean_standard(dist):
"""Find the mean and standard deviation."""
# In the dist dictionary, the key is the value of the metric and
# the value is the number of times it appears. So, the sample
# value is the key and the number of samples for the value is the
# value in dist for th... | 3d90807a619b6fe090571a3f07db807e60c3849c | 3,603,832 |
def load_data():
"""Load data from the CSV files referundum/regions/departments."""
referendum = pd.read_csv("data/referendum.csv", sep=';')
regions = pd.read_csv("data/regions.csv", sep=',')
departments = pd.read_csv("data/departments.csv", sep=',')
return referendum, regions, departments | a16073711331e70fe969fd060e7ff0cacaf6e0b6 | 3,603,833 |
def VolumeDensity(imge, R, z):
"""
Calculates the volume density of an MGE at given position (R,z).
INPUTS
imge : intrinsic MGE, must be given as an astropy Table or QTable
R : intrinsic R, should have the same units as MGE widths
z : intrinsic z, should have the same units... | f81a32d13e390bc95aaa2ee3d2854c316e912922 | 3,603,834 |
def compatible_features(current):
"""Fuzz compatible features header field."""
constraints = [
[(0, UINT64_M)]
]
return selector(current, constraints, bit_validator) | 97d2e17fb3cba1a0fef2133d8f2159a5ede65994 | 3,603,835 |
def is_port_provisioned(context, port_id, host_id=None):
"""Checks if a port is already known to EOS
:returns: True, if yes; False otherwise.
:param port_id: globally unique port ID that connects VM to network
:param host_id: host to which the port is bound to
"""
filters = {
'port_id'... | 1d4dba306471ed462d9791502043fe3fa4b66ad5 | 3,603,836 |
def shift2d(x,w,a,b):
"""Shift a 2d quadrature rule to the box defined by the tuples a and b"""
xs=[[a[0]],[a[1]]]+x*[[b[0]-a[0]],[b[1]-a[1]]]
ws=w*(b[0]-a[0])*(b[1]-a[1])
return xs,ws | 84c2090cc0e1689a79aa2c7fa40fb399bc03f535 | 3,603,837 |
def _get_initial_policy_state(policy, time_steps):
"""Gets the initial state of a policy."""
batch_size = (tf.compat.dimension_at_index(time_steps.discount.shape, 0) or
tf.shape(time_steps.discount)[0])
return policy.get_initial_state(batch_size=batch_size) | 122a0a5e2f846a44a63a789e13050b7171d8d936 | 3,603,838 |
def create_cube(base_query, dimensions, measures):
""" Return cube from give base query, dimensions and measures. """
return aa.Cube(
base_query=base_query,
resolve_table_name="Flight Route",
storage="Full",
dimensions=dimensions,
measures=measures,
) | ed77295cd00b827a0f1ff356e474b47b9e5df1be | 3,603,839 |
def sync_data(request):
"""
View to call sync_data management command.
"""
if not request.user.is_superuser:
raise PermissionDenied
form = SyncDataForm()
if request.method == "GET":
return render(request, "sync_data.html", {"form": form})
call_command("sync_data")
retu... | 9166aba3be9c033b30d51a571e76ec51b7e8ee63 | 3,603,840 |
def search_data_in_documents(search_str):
"""Search data in all the documents
Args:
search_str (str): String to be search in all the documents
Returns:
List of tuples containing document object and content
"""
list_of_documents = []
data_list = models.Data.objects.filter(data__... | 56ec6f3da2acd8b3d1f98b1704defba152f10c7d | 3,603,841 |
def weight_on_edge(data, zxing):
"""
This weight is independent of the cell_width.
So even, when we have already a good estimation of the cell width,
this weight does not need to take the width into account.
"""
value_before = data[zxing]
value_after = data[zxing + 1]
slope = value_aft... | 3af14f15589dd5227a21b53598b896a8cca4c79a | 3,603,842 |
import os
def get_logging_config():
"""
Returns logging configuration file path
:return: str
"""
return os.path.normpath(os.path.join(os.path.dirname(__file__), '__logging__.ini')) | a2322151c261f7f89bbdc004d128acbad701645f | 3,603,843 |
import dill
def hashable(a) -> int:
"""
Hashes many kinds of objects, including some that are unhashable through the builtin `hash` function.
Lists and tuples are hashed based on their elements.
"""
if isinstance(a, dict):
# first hash the keys and values with hashable
# then hash ... | 29f55a4586f09156618a70e8443dc8b847260e14 | 3,603,844 |
def pygal_parser(preprocessor, tag, markup):
""" Simple pygal parser """
# Find JSON payload
data = loads(markup)
if tag == 'pygal' and data is not None:
# Run generation of chart
output = run_pygal(data)
# Return embedded SVG image
return '<div class="pygal" style="text-... | a6b8abb3c688ccfa13c05c3ca14db3f4ff0a8cd3 | 3,603,845 |
def effective_kernel(kernel_shape, dilations):
"""
Args:
kernel_shape: tuple[int] representing the kernel shape in each
given dimension.
dilations: tuple[int] representing the dilation of the kernel
in each given dimension. Must be the same length as
kernel_... | a955d185c924514bf981c2512a8e78646d523144 | 3,603,846 |
from typing import Union
from typing import Optional
from typing import Tuple
from typing import Any
def eval_step_single_learner(
jax_task: base_task.SingleTask,
states: TrainState,
prng_key: JTensor,
inputs: Union[JTensor, NestedMap],
data_parallel_axis_name: Optional[str] = 'batch',
fprop_d... | 6af0eab44e1c112b4358d7e67da87ed3ac33f0ad | 3,603,847 |
def get_or_create_global_step():
"""
Checks if global step variable exists otherwise creates it
:return:
Global step tensor
"""
global_step = tf.train.get_global_step()
if global_step is None:
global_step = tf.train.create_global_step()
return global_step | 52d4b64874d8f0295be6c606ba5851a384bc6c7e | 3,603,848 |
from typing import Sequence
def fasta_reader(fasta_path):
"""
:param fasta_path: the path to the file to parse
:type fasta_path: string
:return: a sequence
:rtype: Sequence instance
"""
with open(fasta_path, 'r') as fasta_infile:
id_ = ''
comment = ''
sequence = ''
... | 325aafabf553cf2880bdfc4116ee1e03b4a1e39f | 3,603,849 |
def get_slice_hostnames( slice_name ):
"""
Query the Django DB and get the list of hosts running in a slice.
"""
openstack_slice = Slice.objects.get( name=slice_name )
if openstack_slice is None:
logger.error("No such slice '%s'" % slice_name)
return None
hostnames = [s.node.name for s... | 5bf374d4252189fb21ca0dc8d461b671d5ef39bf | 3,603,850 |
def CreateFigure(FigSizeFormat="default", AspectRatio=16./9.):
"""
This function creates a default matplotlib figure object
Args:
FigSizeFormat: the figure size format according to journal for which the figure is intended
values are geomorphology,ESURF, ESPL, EPSL, JGR, big
... | 3b88c73bc197d129db3f7f8a8a45e9b5d0f8657a | 3,603,851 |
def choose_random_nm(odd=False):
"""Choose random n and m.
Optional argument specifies whether n and m are seperated by a factor of 2 or not.
"""
m = np.nan
n = np.nan
# make sure m and n are seperated by a factor of 2 otherwise
# we'll get all zeros
while (m - n + odd) % 2:
# c... | a82c7b1953de3991cc6461bbfddadffb8a3ff215 | 3,603,852 |
def dim_change_fn(img_A, img_B, opt, scale, default_int_method,
crop_size, A_crop_size, ds_kernels):
"""Fix the images dimensions if smaller than crop sizes
"""
# TODO: test to be removed
# w, h = image_size(img_B)
# w_A, h_A = image_size(img_A)
# img_B = transforms.Resize((crop_size-10,... | 567d5dc6c38cdaaf38301c92e181c171c3e2531d | 3,603,853 |
def int_from_32bit_array(val):
"""Converts an integer from a 32 bit bytearray
:param val: the value to convert to an int
:type val: int
:rtype: int
"""
rval = 0
for fragment in bytearray(val):
rval <<= 8
rval |= fragment
return rval | ca2f32c7eac6f42aeed688510fa57e717edfacdf | 3,603,854 |
def build_evaluation_from_config_item(configuration_item, compliance_type, annotation=None):
"""Form an evaluation as a dictionary. Usually suited to report on configuration change rules.
Keyword arguments:
configuration_item -- the configurationItem dictionary in the invokingEvent
compliance_type -- ei... | 05769fc549acdcec7ed611abeff5f0b4f695e57e | 3,603,855 |
import os
import json
def load_json_config(app, config_filename):
""" Adds support for eventador's config.json format """
filename = os.path.join(app.config.root_path, config_filename)
with open(filename) as json_file:
obj = json.load(json_file)
keys = list(obj.keys())
for key in k... | f3156d41b075cabc04628f1ad2e8f5ca7bb8551b | 3,603,856 |
import os
def resolve_path_o(model_dict):
"""
Resolve absolute paths of output data for different datasets
Parameters
----------
model_dict : dictionary contains model's parameters
Returns
-------
absolute path to output directory
"""
dataset = model_dict['dataset']
chan... | cf1866b984aecda48548eb80fea9750e7d8c9700 | 3,603,857 |
import os
def module_configuration():
"""
module configuration
Returns:
JSON/Dict module configuration
"""
return {
"username": "admin",
"password": generate_token(16),
"extra_docker_options":
["--volume {0}/tmp:/var/log/apache2/".format(os.getcwd())],
... | d967179c7a5c359d27efe4e6de9143da1faa67ad | 3,603,858 |
from typing import Union
def STEP(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""
A. Dudek, Z. Szkutnik, "Minimax unfolding spheres size distribution from linear sections", Statistica Sinica 18 (2008) 1063–1080
"""
return np.where(x <= 1 / 3, 0.6, np.where(x <= 3 / 4, 0.9, 1.7)) | de66d9b75d1c4d86109db3c448201a2042913b79 | 3,603,859 |
import functools
def requires_attr(attr_name, raiser):
"""
Methods wrapped in this decorator raise an error if a required
attribute is not set.
"""
def decorator(meth):
@functools.wraps(meth)
def wrapper(self, *args, **kwargs):
if getattr(self, attr_name, None) is None:... | e88d5ecfc39688683c7c29fbfc68db79cc760216 | 3,603,860 |
import sys
def parse_context(operation):
"""
Initialize a HandlerUtil object for this operation.
If the required modules have not been imported, this will return None.
"""
hutil = None
if ('Utils.WAAgentUtil' in sys.modules
and 'Utils.HandlerUtil' in sys.modules):
try:
... | 581f5c2b6985435a92ab764b8c07cabacafa06f0 | 3,603,861 |
def to_qsw(orbit):
"""In the QSW Local Orbital Reference Frame, x is oriented along the position vector,
z along the angular momentum, and y complete the frame.
The frame is sometimes also called RSW (where R stands for radial) or LVLH (Local
Vertical Local Horizontal).
Args:
orbit (list):... | 1aa4b1f82626e0a6176202708ce4f25eeeb3c1c7 | 3,603,862 |
import logging
def status():
"""
REST API endpoint to get the complete status of slideshow
:return: json confirmation message
"""
success = True
message = "Successfully retrieved current slideshow status/information"
# Logging message
logging.debug(message) if success else logging.erro... | 6fa172ef5b01d22848f11397ac5e5b990cf21031 | 3,603,863 |
from typing import List
def get_possible_proteins(fasta_data: List[str]) -> str:
"""
:param fasta_data: A DNA sequence in FASTA format
:return: a formatted set of possible proteins encoded in DNA
"""
strands = parse_fasta(fasta_data)
# there should be only one sequence
strand, = strands
... | 67a3b9b42badf2a74d82075cd610c7691e961d23 | 3,603,864 |
def theta(flag, S, K, t, r, sigma):
"""Return Black-Scholes theta of an option.
:param S: underlying asset price
:type S: float
:param K: strike price
:type K: float
:param sigma: annualized standard deviation, or volatility
:type sigma: float
:param t: time to expiration in years
:... | ae962cb0e7111140de01909a797f361a3aa8964f | 3,603,865 |
def _pretty_print_label(d):
"""Internal utility to pretty print point label info."""
s = " %s: "%repr(d[0])
entry_keys = list(d[1].keys())
ki = 0
kimax = len(entry_keys)
for k in entry_keys:
keys = list(d[1][k].keys())
if len(keys) == 0:
s += "{%s: {}}"%k
else... | 4972b54d2402d87e6fe276605c59d21cfdc91533 | 3,603,866 |
def test_load_snapshot_default():
"""Loads the default snapshot.
"""
sp = GOSnapshot()
summaries = []
summaries.append(sp.summary)
df = to_df(summaries)
return True | 1a37e07151f5a21dd15c15350554476176167253 | 3,603,867 |
def traverse_graph(prev_layer, layers):
"""Traverse keras sequential graph."""
for layer in layers:
if isinstance(layer, (tf.keras.Sequential, tf.keras.Model)):
prev_layer = traverse_graph(prev_layer, layer.layers)
else:
prev_layer = layer(prev_layer)
return prev_layer | 75ccdc55b6ec9b141c3a7d15fa554ce894afb7f3 | 3,603,868 |
def peak_locked_percentile(signals, fs, peak_loc, t_plot,
percentiles=['mean']):
"""
Compute the mean of each signal in signals, locked to the peaks
Parameters
----------
signals : shape (n_signals, n_epochs, n_points)
fs : sampling frequency
peak_loc ... | 1c99ed358c05e0d33dd906bda3e7b64a641d2364 | 3,603,869 |
def dict2obj(target, change_dict=True):
"""
将dict转换成obj对象
change_dict 用于控制是否转换target内部dict为obj
:param target: dict
:param change_dict: bool
:return: obj
"""
class Obj(object):
def __init__(self, d, change_dict):
for a, b in d.items():
if change_dict ... | 4beec4d45528e2939a0c63333b8a401e34df3b3d | 3,603,870 |
def simulate_output_data(func, xvals, param_dict, **metadata):
"""Generate arbitrary fit data."""
__shots = 100000
expected_probs = func(xvals, **param_dict)
counts = np.asarray(expected_probs * __shots, dtype=int)
data = [
{
"counts": {"0": __shots - count, "1": count},
... | 2c0c143cf533f6aab8c06ac399b4f62efcd6709f | 3,603,871 |
def user_logged_in():
"""Checks if user logged in.
"""
if 'active_user' not in app.session:
return False
username = app.session['active_user']
return mongo.db.users.count({'username': username}) > 0 | 7ff3b4f6f7882fc48f9cc0cadfc6e895765fadb1 | 3,603,872 |
def ewins(freq, H, nf='None', residues=False, type='d', o_fr=0):
"""
Arguments:
- freq - frequency vector
- H - a row or a column of FRF matrix
- o_fr - list of optionally chosen frequencies in Hz. If it is
not set, optional points are set automatically and are
... | 8bb249a8c6fd8805cad724c73256635612746b4c | 3,603,873 |
def splitbycharset(txt, charset):
"""Splits a string at the first occurrence of a character in a set.
Args:
txt: Text to split.
chars: Chars to look for (specified as string).
Returns:
(char, before, after) where char is the character from the character
set whic... | c23577eb96c9621909acaa816e8791e95dbf493d | 3,603,874 |
from typing import Optional
def mean(
x: ArrayLike,
axis: Axis = None,
keepdims: bool = False,
*,
constant: Optional[bool] = None
) -> Tensor:
"""
Mean of tensor elements over a given axis.
Parameters
----------
x : ArrayLike
axis : Optional[int, Tuple[ints, ...]
... | 816abd2b2a1f9c8c868bc1e7be52b650f35be166 | 3,603,875 |
import os
def comparedirs(dir1, dir2, files1=None, files2=None):
"""
Compare directory contents, but not actual files;
may need bytes listdir arg for undecodable filenames on some platforms
"""
print('Comparing', dir1, 'to', dir2)
files1 = os.listdir(dir1) if files1 is None else files1
fi... | e9e98ceef3a1a91dfc15c736c67de808a4eb0bee | 3,603,876 |
def mmdagg(
seed, X, Y, alpha, kernel_type, approx_type, weights_type, l_minus, l_plus, B1, B2, B3
):
"""
Compute MMDAgg as defined in Algorithm 1 in our paper using the collection of
bandwidths defined in Eq. (16) and the weighting strategies proposed in Section 5.1.
inputs: seed: integer random se... | dee823fecde9ab44172e0d80ee721e45ac914a81 | 3,603,877 |
def _get_masses(fitnesses):
"""Convert fitnesses into masses, as given by GSA algorithm."""
# Obtain constants
best_fitness = max(fitnesses)
worst_fitness = min(fitnesses)
fitness_range = best_fitness - worst_fitness
# Calculate raw masses for each solution
raw_masses = []
for fitness i... | 12e2b4414ce53a9477420ed0d58006f7f0248081 | 3,603,878 |
from typing import Optional
from typing import List
def format( # pylint: disable=redefined-builtin
files: Optional[List[str]] = typer.Argument(default=None), # noqa: B008
check: bool = typer.Option( # noqa: B008
default=False, help='Only checks instead of modifying.'
),
) -> List[Result]:
... | c12a02170751fbf09ff88b059fc90518b7f45d8b | 3,603,879 |
def make_plot(source):
"""Creation of simple graphs in bokeh"""
# Set up plot
p = figure(plot_width=400, plot_height=400, tooltips=tooltips)
#p.vline_stack(['S', 'R', 'I'], x='t', source=source)
p.vline_stack(['S'], x='t', source=source, color='blue', width=4, legend_label="Susceptible")
p.vlin... | ecf0a7cf9bab6518d94f799e1956fcd7e2eb0507 | 3,603,880 |
def makeGeneratorConfig(couchDatabase):
"""
_makeGeneratorConfig_
Create a bogus config cache document for the montecarlo generation and
inject it into couch. Return the ID of the document.
"""
newConfig = Document()
newConfig["info"] = None
newConfig["config"] = None
newConfig["m... | b65015b6c06311d6de0d6b031a736bdecf084318 | 3,603,881 |
def poly2ac(poly, efinal):
""" Convert prediction filter polynomial to autocorrelation sequence
:param array poly: the AR parameters
:param efinal: an estimate of the final error
:return: the autocorrelation sequence in complex format.
.. doctest::
>>> from numpy import array
>>>... | 1993bdca9cb6642a03307bb013b157ef4f3c7e11 | 3,603,882 |
def arctan(x):
"""Returns a new Var with arctangent applied to the input Var x
:param x: object on which arctangent is applied, required
:type x: AD_Object.Var
:return: new object with arctangent applied to input
:rtype: AD_Object.Var
:example:
>>> from autodiff.AD_BasicMath import... | aa889e8056a44defbc509616ef9831f6c35c6e43 | 3,603,883 |
def process_meta_review(meta_review):
"""
Do something with the meta-review JSON!
This is where you would:
1. Translate meta_review["ty_id"] to your own hotel ID, dropping any unmapped hotels
2. Traverse the JSON structure to find the data you are interested in, documented at
http://api.trustyo... | 681ace9b9685f4bfd284ac6e41efde12bafbb1b9 | 3,603,884 |
def ray_partition_get_data_label(partition_data,
allow_tuple=True,
allow_list=True,
has_label=True):
"""
:param partition_data: The data partition from Spark RDD, which should be a list of records.
:param allo... | e99c316a22e1828556abfef6928e74634955cfa8 | 3,603,885 |
def get_pdf_of_normal_distribution(x, mu, sigma):
"""Compute the probability of ``x`` under a normal distribution.
This implementation is faster than calling ``scipy.stats.norm.pdf``.
Parameters
----------
x : float or np.ndarray
The probability is calculated for this value.
mu : float... | 8f8f8ec43f21d4f2596337fb9b5f799358faa23e | 3,603,886 |
def compute_mesh_laplacian(verts, tris):
"""
computes a sparse matrix representing the discretized laplace-beltrami operator of the mesh
given by n vertex positions ("verts") and a m triangles ("tris")
verts: (n, 3) array (float)
tris: (m, 3) array (int) - indices into the verts array
compute... | 118300945fa1573e29f389bf807ada5f11e36cac | 3,603,887 |
def find_natural_number(position: int) -> tuple:
"""Return natural number at specified position and number its a part of."""
num_range = ""
counter = 0
while len(str(num_range)) < position:
counter += 1
num_range += str(counter)
return int(num_range[-1]), counter | 62aff0c400ac007fc67dafd25eb4cacf63262105 | 3,603,888 |
def camel_case(snake_case: str) -> str:
"""Converts snake case strings to camel case
Args:
snake_case (str): raw snake case string, eg `sample_text`
Returns:
str: camel cased string
"""
cpnts = snake_case.split("_")
return cpnts[0] + "".join(x.title() for x in cpnts[1:]) | b3080a3e3520209581cbd381ffaff24045343115 | 3,603,889 |
def get_onnx_shape(model):
"""Just input shape"""
shape = {}
for t in model.graph.input:
name, etype, dims, dynamic = value_info_parse(t)
shape[name] = dims
return shape | c36335c1a13c80cb66e8aa51cd7d08d7a9b27c16 | 3,603,890 |
from datetime import datetime
import os
import re
def dump(doc, typed_categories=None, untyped_categories=None, export_path=None, filters=None):
"""
Writes element data for chosen categories, ids, location and params to specified csv
with the possibility to filter: e.g. {'type':{'Type Name':r"^[X][X]_.+"}... | 4ee02ca34749a68e36793310762798d2238c5655 | 3,603,891 |
def calculate_mp_value(
pert_df: pd.DataFrame,
control_df: pd.DataFrame,
params: dict = {},
) -> pd.Series:
"""Given perturbation and control dataframes, calculate mp-value per perturbation
Usage: Designed to be called within a pandas.DataFrame().groupby().apply(). See
:py:func:`cytominer_eval.... | 24e5e7dae2cb894fe01e1ad47c12fbbfb8a1c21c | 3,603,892 |
from unittest.mock import patch
def test_query_asset_movements_sandbox(
sandbox_kuckoin,
inquirer, # pylint: disable=unused-argument
):
"""Unfortunately the sandbox environment does not support deposits and
withdrawals, therefore they must be mocked.
Below a list of the movements and the... | 6e5269d4b69afc71a56992e0795d3036c1c58557 | 3,603,893 |
def ellipse_params(uamp, upha, vamp, vpha):
"""Calculates ellipse parameters based on the amplitude
and phase for a tidal constituent.
:arg uamp: u fitted amplitude of the chosen constituent
:type uamp: :py:class:`numpy.ndarray`
:arg upha: u fitted phase of the chosen constituent
:type upha: :... | a7e9b98f71bb36c157288ba8d38a7670a822d7f8 | 3,603,894 |
def _guess_bounds(cube, coords):
"""Guess bounds of a cube, or not."""
# check for bounds just in case
for coord in coords:
if not cube.coord(coord).has_bounds():
cube.coord(coord).guess_bounds()
return cube | 44cdcdc8ee0dd821d3abdef880efe11c7cf8d48e | 3,603,895 |
def render_to(template):
"""
Decorator for Django views that sends returned dict to render function.
If view doesn't return dict then decorator simply returns output.
Additionally view can return two-tuple, which must contain dict as first
element and string with template name as second. This strin... | d053cc3ddb7cd0406da19b64ed09c61347c19c6a | 3,603,896 |
def eigenvals(
tb_model: orm.SinglefileData, kpoints: orm.KpointsData
) -> orm.BandsData:
"""Calculate the eigenvalues of a model at given k-points.
Parameters
----------
tb_model :
The tight-binding model.
kpoints :
The k-points at which the eigenvalues should be evaluated.
... | 93eb57d8c448bbdd524fd791914d0724f62d70bf | 3,603,897 |
def get_segment_model():
"""
Returns the review model class.
"""
if get_review_app_name() != DEFAULT_REVIEWS_APP and hasattr(get_review_app(), "get_segment_model"):
return get_review_app().get_segment_model()
else:
return ReviewSegment | 0ca78bcf2e0b88cade7f2a4e9b06d53c903be336 | 3,603,898 |
import re
import os
import logging
import tqdm
import pandas
def main(network_edges_path, hazard_tifs, output_path):
"""
Split the entries in network_edges_path according to the cells they occupy in the
grids of the hazard_dir. Write the results to a .geoparquet file (output_path)
and a similarly-name... | 30d446a326d28a4e32c413a5419d1b5c1fd9d9d3 | 3,603,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.