content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def datetime_attribute_timeseries(time_index: Union[pd.DatetimeIndex, TimeSeries],
attribute: str,
one_hot: bool = False) -> TimeSeries:
"""
Returns a new TimeSeries with index `time_index` and one or more dimensions containing
(optionally ... | 42,000 |
def hexscale_from_cmap(cmap, N):
"""
Evaluate a colormap at N points.
Parameters
----------
cmap : function
a function taking a scalar value between 0 and 1 and giving a color as
rgb(a) with values between 0 and 1. These are for example the pyplot
colormaps, like plt.cm.viri... | 42,001 |
def getFirebaseData(userID):
"""
This gets the data from the Firebase database and converts it to a readable dictionary
Args:
userID (string): the id of the user
"""
cred = credentials.Certificate("serviceAccountKey.json")
a = firebase_admin.initialize_app(cred)
ourDatabase = f... | 42,002 |
def gen_tracer(code, f_globals):
""" Generate a trace function from a code object.
Parameters
----------
code : CodeType
The code object created by the Enaml compiler.
f_globals : dict
The global scope for the returned function.
Returns
-------
result : FunctionType
... | 42,003 |
def MAD(AnalogSignal):
""" median absolute deviation of an AnalogSignal """
X = AnalogSignal.magnitude
mad = sp.median(sp.absolute(X - sp.median(X))) * AnalogSignal.units
return mad | 42,004 |
def angular_frequency(vacuum_wavelength):
"""Angular frequency :math:`\omega = 2\pi c / \lambda`
Args:
vacuum_wavelength (float): Vacuum wavelength in length unit
Returns:
Angular frequency in the units of c=1 (time units=length units). This is at the same time the vacuum wavenumber.
"... | 42,005 |
def span(spans):
"""Merge adjacent spans with the same omit/don't omit
status. spans is a list of (omit, start_time) tuples.
Note the last span won't include the end of the file."""
i = iter(spans)
last = i.next()
for s in i:
if s[0] != last[0]:
yield (last[0], last[1], s[1])... | 42,006 |
def web_urls():
"""Builds and returns the web_urls for web.py.
"""
urls = (
'/export/?', RestHandler,
'/export/bdbag/?', ExportBag,
'/export/bdbag/([^/]+)', ExportRetrieve,
'/export/bdbag/([^/]+)/(.+)', ExportRetrieve,
'/export/file/?', ExportFiles,
'/export/f... | 42,007 |
def box_cxcywh_norm_to_cxcywh(box: TensorOrArray, height: int, width: int) -> TensorOrArray:
"""Converts bounding boxes from (cx, cy, w, h) norm format to (cx, cy, w, h)
format.
(cx, cy) refers to center of bounding box.
(a, r) refers to area (width * height) and aspect ratio (width / height) of
... | 42,008 |
def write_html(address):
"""
Update the index.html file used for rendering the environment state.
"""
s = """<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styles.css">
<script>var wsServerAddress = "{}";</script>
<script src="js/init.js"></script>
<script src="js/device... | 42,009 |
def lyrics_from_url(url):
"""Return a tuple with song's name, author and lyrics."""
source = identify_url(url)
extractor = {
'letras': (lyrics_from_letrasmus, info_from_letrasmus),
'vagalume': (lyrics_from_vagalume, info_from_vagalume)
}
html = html_from_url(url)
if source in ex... | 42,010 |
def test_nameserver_proxy_shutdown_no_agents():
"""
Shutdown a name server through a proxy when the name server has no
agents registered.
"""
ns = run_nameserver()
ns.shutdown() | 42,011 |
def _get_pycons():
"""Helper function that retrieves required PyCon data
and returns a list of PyCon objects
"""
with open(pycons_file, "r", encoding="utf-8") as f:
return [
PyCon(
pycon["name"],
pycon["city"],
pycon["country"],
... | 42,012 |
async def invite(ctx):
"""get noface bot invite link"""
embed = discord.Embed(title=" http://noface.cf ")
await bot.say(embed=embed) | 42,013 |
def save_np(file_path, np_data):
"""Saves np array at file_path."""
tf.io.gfile.makedirs(os.path.dirname(file_path))
with tf.io.gfile.GFile(file_path, "wb") as fout:
np.save(fout, np_data) | 42,014 |
def delete_folder(folder):
"""
Delete folder
Parameters
----------
folder : Google Folder
Google Drive folder to delete
"""
if Settings.is_delete():
try:
Settings.print("Deleting folder: {}".format(folder["title"]))
folder.Trash()
except Exce... | 42,015 |
def f_function(chromosome):
"""Define Fitness Function Here."""
x = chromosome.convert_to_integer()
return (15 * x[0]) - (x[0] * x[0])
# return (((15 * x[0]) - (x[0] * x[0])) * -1) + 1000 To Find Minimum Solution
| 42,016 |
def _GetRevsAroundRev(data_series, revision):
"""Gets a list of revisions from before to after a given revision.
Args:
data_series: A list of (revision, value).
revision: A revision number.
Returns:
A list of revisions.
"""
if not _MAX_SEGMENT_SIZE_AROUND_ANOMALY:
return [revision]
middle... | 42,017 |
def get_label_file_dict(self, use_session = True):
"""
Get Project label file id dict for project
Arguments
self
Expects
self.project_string_id
self.directory_id
Returns
sets self.name_to_file_id to the dict returned
"""
if self.project_string_id is None:
... | 42,018 |
def test_month_on_month():
"""Test month on month."""
func = TIME_RANGES_BY_KEY["month_on_month"]["function"]
base_start_date = date(2020, 2, 1)
base_end_date = date(2020, 2, 29)
rca_start_date = date(2020, 3, 1)
rca_end_date = date(2020, 3, 5)
output = func(rca_end_date)
assert output... | 42,019 |
def get_output_length():
"""Returns the length of the convnet output."""
return conv_base.layers[-1].output_shape[-1] | 42,020 |
def rules(command, working_directory=None, root=True, **kargs):
"""
Main entry point for build_rules.py.
When ``makeprojects``, ``cleanme``, or ``buildme`` is executed, they will
call this function to perform the actions required for build customization.
The parameter ``working_directory`` is requ... | 42,021 |
def get_py_func_body(line_numbers, file_name, annot):
""" Function to get method/function body from files
@parameters
filename: Path to the file
line_num: function/method line number
annot: Annotation condition (Ex: @Test)
@return
This function returns python function... | 42,022 |
def extract_optional_annotation(annotation: Any) -> Any:
"""
Determine if the given annotation is an Optional field
"""
if (
hasattr(annotation, "__origin__")
and annotation.__origin__ is Union
and getattr(annotation, "__args__", None) is not None
and len(annotation.__arg... | 42,023 |
def rerun(dry_run, sources, paths, provider, config):
"""Recreate files generated by a sequence of ``run`` commands."""
from renku.core.commands.format.activity import tabulate_activities
from renku.core.commands.rerun import rerun_command
communicator = ClickCallback()
try:
result = (
... | 42,024 |
def combine_pred_and_truth(prediction, truth_file):
"""
Combine the predicted labels and the ground truth labels for testing purposes.
:param prediction: The prediction labels.
:param truth_file: The ground truth file.
:return: The combined prediction and ground truth labels.
"""
f = open(t... | 42,025 |
def consume(config):
"""
Read from a RabbitMQ queue.
Fetch message from a given queue in an endless loop.
See rbmq_config.py for the possible parameters.
"""
while True:
try:
connection = pika.BlockingConnection(
get_connection_parameters(config)
... | 42,026 |
def problem448():
"""
The function lcm(a,b) denotes the least common multiple of a and b.
Let A(n) be the average of the values of lcm(n,i) for 1≤i≤n.
E.g: A(2)=(2+2)/2=2 and A(10)=(10+10+30+20+10+30+70+40+90+10)/10=32.
Let S(n)=∑A(k) for 1≤k≤n.
S(100)=122726.
Find S(99999... | 42,027 |
def calc_cogs_time_series(days, cogs_annual):
"""
Cost of Goods Sold Formula
Notes
-----
Can adjust for days/weekly/monthly/annually in the future - ASSUMED: CONSUMABLES PURCHASED MONTHLY
"""
cogs_time_series = []
for i in range(days):
if i % DAYS_IN_MONTH == ... | 42,028 |
def test_daily_offset():
"""Compute the offsets"""
ts = utc(2013, 1, 1, 0, 0)
offset = iemre.daily_offset(ts)
assert offset == 0
ts = datetime.date(2013, 2, 1)
offset = iemre.daily_offset(ts)
assert offset == 31
ts = utc(2013, 1, 5, 12, 0)
offset = iemre.daily_offset(ts)
assert... | 42,029 |
def make_regridder_L2L(
llres_in, llres_out, weightsdir='.', reuse_weights=False,
in_extent=[-180, 180, -90, 90],
out_extent=[-180, 180, -90, 90]):
"""
Create an xESMF regridder between two lat/lon grids
Args:
llres_in: str
Resolution of input grid in format 'lat... | 42,030 |
def stations():
""" Returning the all Stations """
station_list = session.query(station.name).all()
jsonify_sation = list(np.ravel(station_list))
#Jsonify results
return jsonify(jsonify_sation) | 42,031 |
def test_load_one_file_01(insert_sequences_batch, info):
"""Load mixed sequences from a file into the atram database."""
cxn, args = set_up()
db.BATCH_SIZE = 5
file_1 = join('tests', 'data', 'load_seq1.txt')
core_preprocessor.load_one_file(args, cxn, file_1, 'mixed_ends')
msg = 'Loading "{}" i... | 42,032 |
def test_run_sht_rudeadyet_default(tmpdir) -> int:
"""
Purpose:
Test to make sure sht-rudeadyet run works
Args:
N/A
Returns:
(Int): 0 if passed run, -1 if not
"""
attack = "sht_rudeadyet"
run_config = "configs/mw_locust-sht_rudeadyet.json"
return magicwand_run(tmp... | 42,033 |
def _clean_markdown_cells(ntbk):
"""Clean up cell text of an nbformat NotebookNode."""
# Remove '#' from the end of markdown headers
for cell in ntbk.cells:
if cell.cell_type == "markdown":
cell_lines = cell.source.split('\n')
for ii, line in enumerate(cell_lines):
... | 42,034 |
def get_thread_wrapper(target, name):
"""Returns a target thread that prints unexpected exceptions to the logging.
Args:
target: Func or coroutine to wrap.
name(str): Task name.
"""
@wraps(target)
def wrapper(*args, **kwargs):
try:
result = target(*args, **kwarg... | 42,035 |
def scale_pairs(arr, scalgo="deseq"):
"""Scales observed paired columns of read-overlap counts.
- arr(``path``) input array regions x (markX in A, markX in B, markY in A, markY in B ...)
- scalgo(``str``) scaling algorithm
"""
chk_exit(*inp_file(path(arr)))
with open(arr) as fh:
nam... | 42,036 |
def getStructType(ea):
"""
Get type information from an ea. Used to get the structure type id
"""
flags = idaapi.getFlags(ea)
ti = idaapi.opinfo_t()
oi = idaapi.get_opinfo(ea, 0, flags, ti)
if oi is not None:
return ti
else:
return None | 42,037 |
def confirm_email(token):
"""
GET endpoint that confirms the new officer user. This endpoint link is normally within
the confirmation email.
"""
club_email = flask_exts.email_verifier.confirm_token(token, 'confirm-email')
if club_email is None:
raise JsonError(status='error', reason='Th... | 42,038 |
def xcrun_field_value_from_output(field: str, output: str) -> str:
"""
Get value of a given field from xcrun output.
If field is not found empty string is returned.
"""
field_prefix = field + ': '
for line in output.splitlines():
line = line.strip()
if line.startswith(field_pre... | 42,039 |
def CacheRewriter(response):
"""Update the cache header."""
if response.status_code == httplib.NOT_MODIFIED:
return
if not 'Cache-Control' in response.headers:
response.headers['Cache-Control'] = 'no-cache'
if not 'Expires' in response.headers:
response.headers['Expires'] = 'Fri, 01 Jan 1990 ... | 42,040 |
def get_all_markets_num():
"""
获取交易所有的市场
:return: "5/2"
"""
markets = list(set([str(i["stockId"]) + "/" + str(i["moneyId"]) for i in res["result"]]))
return markets | 42,041 |
def main():
"""
The main program: instantiate a problem, then use odes package to solve it
"""
uinput = input("Solve as\n 1 = index 2 problem\n 2 = index 1 problem\n"
" 3 = index 1 problem with jacobian\n 4 = info\n\n"
"Answer (1,2,3 or 4) : ")
jac = None
if uinpu... | 42,042 |
async def test_invalid_config(hass, mock_client, config_ext, get_write_api):
"""Test the setup with invalid config or config options specified for wrong version."""
config = {"influxdb": {}}
config["influxdb"].update(config_ext)
assert not await async_setup_component(hass, influxdb.DOMAIN, config) | 42,043 |
def mae(s, o):
"""
Mean Absolute Error
input:
s: simulated
o: observed
output:
maes: mean absolute error
"""
s, o = filter_nan(s, o)
return np.mean(abs(s - o)) | 42,044 |
def test_version():
"""
Verify that dt.version() returns what is expected. It can be called as a
static method on the class (dt.version()) or as a method on a dt object:
q = dt()
q.version()
"""
pytest.dbgfunc()
assert dt.version() == version._v
assert dt().version() == vers... | 42,045 |
def error_mult_gap_qa_atom(
df_qc, df_qats, target_label, target_charge=0,
basis_set='aug-cc-pV5Z', use_ts=True,
max_qats_order=4, ignore_one_row=False,
considered_lambdas=None, return_qats_vs_qa=False):
"""Computes QATS errors in system multiplicity gaps.
Parameters
----------
df_qc : ... | 42,046 |
def frequency_weighting(frequencies, kind="A", **kw):
"""Compute the weighting of a set of frequencies.
Parameters
----------
frequencies : scalar or np.ndarray [shape=(n,)]
One or more frequencies (in Hz)
kind : str in
The weighting kind. e.g. `'A'`, `'B'`, `'C'`, `'D'`, `'Z'`
... | 42,047 |
def collect(storage: Storage):
"""Collect data from the data source"""
data_source = DataSource(
'datagovcz',
'Národní katalog otevřených dat ČR',
'Otevřená data zveřejňovaná institucemi českého státu',
'https://data.gov.cz/')
region = storage.regions['cze']
# Pensions
... | 42,048 |
async def materialize_classpath(request: MaterializedClasspathRequest) -> MaterializedClasspath:
"""Resolve, fetch, and merge various classpath types to a single `Digest` and metadata."""
artifact_requirements_lockfiles = await MultiGet(
Get(CoursierResolvedLockfile, ArtifactRequirements, artifact_requ... | 42,049 |
def Real_Entropy(timeseries):
""" Calculates an approximation of the time-correlated entropy
Input:
timeseries: list of strings or numbers,
e.g. ['1', '2', '3'] or [1, 2, 3]
Output:
approximation of Real Entropy (time-correlated entropy), e.g. 1.09
"""
def is_sublist(ali... | 42,050 |
def test_futures_loan_collateral_repay_limit():
"""Tests the API endpoint to Check Collateral Repay Limit"""
client = Client(key, secret)
response = client.futures_loan_collateral_repay_limit(**params)
response.should.equal(mock_item) | 42,051 |
def hom(X, mode):
"""
It converts transformation X (translation, rotation or rigid motion)
to homogenous form.
Input:
X: tf.float32 array, which can be either
[B, 3] float32, 3D translation vectors
[B, 3, 3] float32, rotation matrices
[B, 3, 4] float32, rigid motion matrix
mode: one of 'T', 'R' or 'P' deno... | 42,052 |
def test_update_input_states():
"""MarkovNetwork.test_update_input_states()"""
np.random.seed(98342)
test_mn = MarkovNetwork(2, 4, 2)
test_mn.update_input_states([1, 1])
assert np.all(test_mn.states[:2] == np.array([1, 1])) | 42,053 |
def parse_sl(comments: str):
"""Parses comments for SL on an order"""
parsed = None
sl_at = "(SL\s{0,1}@\s{0,1})"
sl_price = "([0-9]{0,3}\.[0-9]{1,2}((?!\S)|(?=[)])))"
pattern = sl_at + sl_price
match = re.search(pattern, comments)
if match:
match.groups()
parsed = match.grou... | 42,054 |
def nhpp_thinning(rate_fn, tmax, delta, lbound=None):
"""Nonhomogeneous Poisson process with intensity function `rate_fn` for
time range (0, tmax) using the algorithm by Lewis and Shelder 1978.
rate_fn: a function `f(t)` of one variable `t` that returns a finite non negative
value for `t` in trang... | 42,055 |
def send_text(driver, text, delay):
"""Send `text` to text input box first working driver in `drivers` dict"""
try:
# Click the input box when it can be clicked
wait = WebDriverWait(driver, 15)
elem = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "txtInput")))
except Timeout... | 42,056 |
def execute_rule_engine(rule_name, body):
"""
:param rule_name:
:param body:
:return:
"""
__logger.info("inside execute_rule_engine for " + rule_name)
__logger.info(json.dumps(body, indent=4, sort_keys=True, default=str))
try:
result = rule_engine_service.execute_rule_engine_se... | 42,057 |
def get_tags():
"""
Updates tags, then returns a list of all tags.
"""
print("Pulling latest tags...")
subprocess.run(["git", "fetch", "--tags"], cwd=CPY_DIR, check=True)
result = subprocess.run(
["git", "tag"], cwd=CPY_DIR, check=True, text=True, capture_output=True
)
tags = set... | 42,058 |
def get():
"""
Create and return an instance of the FileSelectionContext
subclass which is appropriate to the currently active application.
"""
windowClass = ContextUtils.getForegroundClassNameUnicode()
if windowClass == u"ConsoleWindowClass":
fsContext = NullFileSelection... | 42,059 |
def calc_accuracy(y_true, y_predict, display=True):
"""Analysis the score with sklearn.metrics.
This module includes score functions, performance metrics
and pairwise metrics and distance computations.
Parameters
==========
y_true: numpy.array
y_predict: numpy.array
display: Boolea... | 42,060 |
def parse_requirements(filename: str, *,
constraint: bool = False, weak: bool = False) \
-> Generator[Union[Package, str], None, None]:
"""Parse a requirements file.
Comments are stripped, ``-c`` and ``-r`` options are handled recursively,
and the remaining non-blank lines ar... | 42,061 |
def HSV_to_HSL(hsv):
"""Converts HSV color space to HSL"""
rgb = HSV_to_RGB(hsv)
return RGB_to_HSL(rgb) | 42,062 |
def run_inference_and_make_csv(sess, probs, tensordict, num_images):
"""Build and run inference on the target images and labels."""
tensordict = OrderedDict(tensordict) # To preserve orders
## initialize csv_makers
tensor_names = tensordict.keys()
tensors = list(tensordict.values())
csv_makers... | 42,063 |
def prosodic_meter_query(
collection,
):
"""
Function for returning all Prosodic Meters that contain the queried collection of
:obj:`fragment.GreekFoot` objects.
:param collection: an iterable collection of :obj:`fragment.GreekFoot` objects.
"""
all_prosodic_meters = get_all_prosodic_meters()
res = []
for m... | 42,064 |
def get_model(loss=keras.losses.MeanSquaredError(), optimizer=keras.optimizers.Adam(), metrics=[keras.metrics.MeanSquaredError()]):
"""
Loads and compiles the model
"""
model = unet3D_model()
model.compile(loss=loss, optimizer=optimizer, metrics=[metrics])
return model | 42,065 |
def mps_kph(m_per_s):
"""Convert speed from m/s to km/hr.
:kbd:`m_per_s` may be either a scalar number or a
:py:class:`numpy.ndarray` object,
and the return value will be of the same type.
:arg m_per_s: Speed in m/s to convert.
:returns: Speed in km/hr.
"""
return m_per_s * M_PER_S__K... | 42,066 |
def evaluate(model: nn.Module, loss_func: nn.Module, loader: iter, logger: Logger, device: str = None):
""" Evaluate the parameters of the model by computing the loss on the data. """
if device is None:
device = next(model.parameters()).device
model.eval()
y_hats, y_s = [], []
with torch.no... | 42,067 |
def glm_likelihood_bernoulli(parms, X, Y, lamb=1, l_p=1, neg=True, log=True):
"""The likelihood for a logistic regression or bernoulli model with a penalty
term (can accept any norm, default is 1 for L1).
Parameters
----------
parms : numpy array (numeric)
The coefficients (including in... | 42,068 |
def to_tvm(graph, shape_dict, layout, mode='tensorflow'):
"""convert frontend graph to nnvm graph"""
assert mode in FRAME_SUPPORTED
if mode == 'tensorflow':
mod, params = tvm.relay.frontend.from_tensorflow(graph, layout=layout, shape=shape_dict)
elif mode == 'keras':
mod, params = tvm.re... | 42,069 |
def getAxes():
""" Get each of the axes over which the data is measured. """
df = load_file("atyeo_covid")
df = df.filter(regex='SampleID|Ig|Fc|SNA|RCA', axis=1)
axes = df.filter(regex='Ig|Fc|SNA|RCA', axis=1)
axes = axes.columns.str.split(" ", expand = True)
subject = df['SampleID']
subje... | 42,070 |
def stretching_current(ref, cur, dvmin, dvmax, nbtrial, window,t_vec):
"""
Function to perform the stretching of the waveforms:
This function compares the Reference waveform to stretched/compressed current waveforms to get the relative seismic velocity variation (and associated error).
It also computes... | 42,071 |
def add_value(tree, keys, value, container_type = dict):
""" """
node = add_branch(tree, keys, container_type)
if isinstance(node, list):
node.append(value)
elif isinstance(node, set):
node.add(value)
else:
node[keys[-1]] = value | 42,072 |
def convert_to_int(var):
"""
Tries to convert an number to int.
:param var
:returns the value of the int or None if it fails
"""
try:
return int(var)
except ValueError:
return None | 42,073 |
def eval_input_fn(filepath, example_parser, batch_size):
"""
模型的eval阶段input_fn
Args:
filepath (str): 训练集/验证集的路径
example_parser (function): 解析example的函数
batch_size (int): 每个batch样本大小
Returns:
dataset
"""
dataset = tf.data.TFRecordDataset(filepath)
dataset... | 42,074 |
def ring_forming_scission_ts_zmatrix(rxn, ts_geo):
""" z-matrix for a ring-forming scission transition state geometry
:param rxn: a Reaction object
:param ts_geo: a transition state geometry
"""
rxn = rxn.copy()
# 1. Get keys to linear or near-linear atoms
lin_idxs = list(automol.geom.line... | 42,075 |
def trip(u, v):
"""
Returns the scalar triple product of vectors u and v and z axis.
The convention is z dot (u cross v). Dotting with the z axis simplifies
it to the z component of the u cross v
The product is:
positive if v is to the left of u, that is,
the shortest right hand ro... | 42,076 |
def one_cpc(request, hmc_session): # noqa: F811
"""
Fixture representing a single, arbitrary CPC managed by the HMC.
Returns a `zhmcclient.Cpc` object, with full properties.
"""
client = zhmcclient.Client(hmc_session)
cpcs = client.cpcs.list()
assert len(cpcs) >= 1
cpc = cpcs[0]
cp... | 42,077 |
def reconstruct(paramfile, obsfile, dbfile):
"""
Reconstruct a likely reproduction rate function given a set of experimental observations
"""
# Generate observed dictionary from input observations
observed = simtools.parse_observations(obsfile)
print('Observed data:', observed)
# Set simul... | 42,078 |
def yield_with_display(future_or_iterable, every, timeout=None):
""" Yields for a future and display status every x seconds
:param future_or_iterable: A future to yield on, or a list of futures
:param every: The number of seconds between updates
:param timeout: The total number of seconds to... | 42,079 |
def query(cmd, db, cgi='http://www.ncbi.nlm.nih.gov/sites/entrez',
**keywds):
"""query(cmd, db, cgi='http://www.ncbi.nlm.nih.gov/sites/entrez',
**keywds) -> handle
Query Entrez and return a handle to the results, consisting of
a web page in HTML format.
See the online documentation for an... | 42,080 |
def Q2B(uchar):
"""单个字符 全角转半角"""
inside_code = ord(uchar)
if inside_code == 0x3000:
inside_code = 0x0020
else:
inside_code -= 0xfee0
if inside_code < 0x0020 or inside_code > 0x7e: # 转完之后不是半角字符返回原来的字符
return uchar
return chr(inside_code) | 42,081 |
def sciwing_group():
"""Root command for everything else in sciwing
"""
pass | 42,082 |
def _colormap_plot_beamforming_time(cmaps):
"""
Plot for illustrating colormaps: beamforming.
:param cmaps: list of :class:`~matplotlib.colors.Colormap`
:rtype: None
"""
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from obspy import UTCDateTime
from obspy.signa... | 42,083 |
def parsedate(date, formats=None, bias=None):
"""parse a localized date/time and return a (unixtime, offset) tuple.
The date may be a "unixtime offset" string or in one of the specified
formats. If the date already is a (unixtime, offset) tuple, it is returned.
>>> parsedate(b' today ') == parsedate(
... | 42,084 |
def prepare_lv2_data(change_price=False):
"""
read lv1 data and ensemble to make submission
"""
train_files = glob('./models/level1_model_files/train/*')
test_files = glob('./models/level1_model_files/test/*')
num_feat = len(train_files)
nrow = pd.read_csv(train_files[0]).shape[0]
X_trai... | 42,085 |
def _send_request(limiter, bucket_ids, start_time, n_request):
"""Rate-limited test function to send a single request, using a shared Limiter.
Defined in module scope so it can be serialized to multiple processes.
"""
with limiter.ratelimit(*bucket_ids, delay=True):
logger.debug(f"t + {(perf_cou... | 42,086 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('clldmpg')
config.include('clld_glottologfamily_plugin')
config.include('clld_phylogeny_plugin')
config.register_datatable('familys', datatab... | 42,087 |
def dwwc(graph, metapath, damping=0.5, dense_threshold=0, dtype=numpy.float64, dwwc_method=None):
"""
Compute the degree-weighted walk count (DWWC) in which nodes can be
repeated within a path.
Parameters
----------
graph : hetio.hetnet.Graph
metapath : hetio.hetnet.MetaPath
damping : f... | 42,088 |
def fba_and_min_enzyme(cobra_model, coefficients_forward, coefficients_reverse):
"""
Performs FBA followed by minimization of enzyme content
"""
with cobra_model as model:
model.optimize()
cobra.util.fix_objective_as_constraint(model)
set_enzymatic_objective(model, coefficients_... | 42,089 |
def logi_led_shutdown():
""" shutdowns the SDK for the thread. """
if led_dll:
return bool(led_dll.LogiLedShutdown())
else:
return False | 42,090 |
def is_ci() -> bool:
"""Return whether running in CI environment."""
return os.environ.get("CI", "") != "" | 42,091 |
def get_blank_adjustments_for_strat(transitions: list) -> Dict[str, dict]:
"""
Provide a blank set of flow adjustments to be populated by the update_adjustments_for_strat function below.
Args:
transitions: All the transition flows we will be modifying through the clinical stratification process
... | 42,092 |
def test_subq_disassembles():
"""
Test to see that sub can be assembled from some input
Example case used:
MOVE.W #$123,D0
SUBQ.B #1,D0 - which results in 122
"""
data = bytearray.fromhex('5300') # SUBQ.B #1,D0
result = Subq.disassemble_instruction(data)
assert result ... | 42,093 |
def test_init():
"""Test if the commands work as expected when no tags are defined"""
expected = 'Nothing to list\n'
assert run('dtags') == expected
assert run('dtags list') == expected
assert run('dtags list test') == expected
assert run('dtags reverse') == expected
assert run('dtags revers... | 42,094 |
def get_instance(module, name, config):
"""
Get module indicated in config[name]['type'];
If there are args to specify the module, specify in config[name]['args']
"""
func_args = config[name]['args'] if 'args' in config[name] else None
# if any argument specified in config[name]['args']
if ... | 42,095 |
def separable_hnn(num_points, input_h_s=None, input_model=None,
save_path='temp_save_path', train=True, epoch_save=100):
"""
Separable Hamiltonian network.
:return:
"""
if input_h_s:
h_s = input_h_s
model = input_model
else:
h_s = HNN1DWaveSeparable(nn.... | 42,096 |
def get_n_largest(n, lst, to_compare=lambda x: x):
"""
This returns largest n elements from list in descending order
"""
largests = [lst[0]]*n # this will be in descending order
for x in lst[1:]:
if to_compare(x) <= to_compare(largests[-1]):
continue
else:
fo... | 42,097 |
def test_error_if_resetting_running_timer():
"""Test that resetting a running timer raises an error"""
t = AccumulatedTimer(TIME_MESSAGE)
t.start()
with pytest.raises(exceptions.TimerRunning):
t.reset() | 42,098 |
def base_scatter(
x: Optional[Union[np.ndarray, list]],
y: Optional[Union[np.ndarray, list]],
hue: Optional[Union[np.ndarray, list]] = None,
ax=None,
title: str = None,
x_label: str = None,
y_label: str = None,
color_bar: bool = False,
bad_color: s... | 42,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.