content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _async_untrack_devices(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Remove tracking for devices owned by this config entry."""
devices = hass.data[DOMAIN][NMAP_TRACKED_DEVICES]
remove_mac_addresses = [
mac_address
for mac_address, entry_id in devices.config_entry_owner.items()
... | 10,800 |
def test_greyscale_display():
"""
SSD1362 OLED screen can draw and display a greyscale image.
"""
device = ssd1362(serial, mode="RGB", framebuffer=full_frame())
serial.reset_mock()
# Use the same drawing primitives as the demo
with canvas(device) as draw:
primitives(device, draw)
... | 10,801 |
def fix_random_seed(seed: int = 42) -> None:
"""
乱数のシードを固定する。
Parameters
----------
seed : int
乱数のシード。
"""
os.environ['PYTHONHASHSEED'] = str(seed)
random.seed(seed)
np.random.seed(seed) | 10,802 |
def ensure_dict(value):
"""Convert None to empty dict."""
if value is None:
return {}
return value | 10,803 |
def mutSet(individual):
"""Mutation that pops or add an element."""
if random.random() < 0.5:
if len(individual) > 0: # We cannot pop from an empty set
individual.remove(random.choice(sorted(tuple(individual))))
else:
individual.add(random.randrange(param.NBR_ITEMS))
return ... | 10,804 |
def test_get_redirect(test_case, page):
"""
Test whether the page returns a redirection.
:param test_case: test class, must be an instance of unittest.TestCase
:param page: str with the page of the flask_monitoringdashboard
"""
with test_case.app.test_client() as c:
test_case.assertEqual... | 10,805 |
def validate_tweet(tweet: str) -> bool:
"""It validates a tweet.
Args:
tweet (str): The text to tweet.
Raises:
ValueError: Raises if tweet length is more than 280 unicode characters.
Returns:
bool: True if validation holds.
"""
str_len = ((tweet).join(tweet)).count(twe... | 10,806 |
def put_dir(src, dest):
"""Tar the src directory, upload it to the current active
host, untar it, and perform renaming if necessary.
src: str
directory to be copied to remote host
dest: str
pathname of directory on remote host
"""
tmpdir = tempfile.mkdtemp()
tarpath = tar_d... | 10,807 |
def feed(data, batch_size, reuse=True):
"""Feed data in batches"""
if type(data)==list or type(data)==tuple and len(data)==2:
data_seqs, data_vals = data
yield_vals = True
else:
data_seqs = data
yield_vals = False
num_batches = len(data_seqs) // batch_size
if num_batches == 0:
raise Except... | 10,808 |
def train_and_eval(model, model_dir, train_input_fn, eval_input_fn,
steps_per_epoch, epochs, eval_steps):
"""Train and evaluate."""
train_dataset = train_input_fn()
eval_dataset = eval_input_fn()
callbacks = get_callbacks(model, model_dir)
history = model.fit(
x=train_dataset,
... | 10,809 |
def open_website(url):
""" Open website and return a class ready to work on """
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36'
' (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}
page = requests.get(url, headers=headers... | 10,810 |
def train():
"""Trains the model"""
if not request.is_json:
return jsonify(error='Request must be json'), 400
try:
frame = data_uri_to_cv2_img(request.json['frame'])
except: # pylint: disable=bare-except
e_type, value, _ = sys.exc_info()
print(e_type)
print(valu... | 10,811 |
def euclidean3d(v1, v2):
"""Faster implementation of euclidean distance for the 3D case."""
if not len(v1) == 3 and len(v2) == 3:
print("Vectors are not in 3D space. Returning None.")
return None
return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2) | 10,812 |
def blast_seqs(seqs,
blast_constructor,
blast_db=None,
blast_mat_root=None,
params={},
add_seq_names=True,
out_filename=None,
WorkingDir=None,
SuppressStderr=None,
Sup... | 10,813 |
def merge_dicts(dicts, handle_duplicate=None):
"""Merge a list of dictionaries.
Invoke handle_duplicate(key, val1, val2) when two dicts maps the
same key to different values val1 and val2, maybe logging the
duplication.
"""
if not dicts:
return {}
if len(dicts) == 1:
retur... | 10,814 |
def _timestamp(line: str) -> Timestamp:
"""Returns the report timestamp from the first line"""
start = line.find("GUIDANCE") + 11
text = line[start : start + 16].strip()
timestamp = datetime.strptime(text, r"%m/%d/%Y %H%M")
return Timestamp(text, timestamp.replace(tzinfo=timezone.utc)) | 10,815 |
def spread(ctx, source_repo):
"""Spread an issue with ISSUE_ID from SOURCE_REPO to the rest of the repos."""
ghm = GitHubMux(ctx.obj['organization'], ctx.obj['token'], ctx.obj['exclude'])
ghm.spread_issue(ctx.obj['issue_id'], source_repo) | 10,816 |
def start_qpsworkers(languages, worker_hosts):
"""Starts QPS workers as background jobs."""
if not worker_hosts:
# run two workers locally (for each language)
workers=[(None, 10000), (None, 10010)]
elif len(worker_hosts) == 1:
# run two workers on the remote host (for each language)
workers=[(work... | 10,817 |
def is_source_ext(filename):
"""
Tells if filename (filepath) is a source file. For our purposes "sources"
are any files that can #include and can be included.
"""
_, ext = os.path.splitext(filename)
return ext in [".h", ".hh", ".hpp", ".inc", ".c", ".cc", ".cxx", ".cpp", ".f", ".F"] | 10,818 |
def MCE(conf, pred, true, bin_size = 0.1):
"""
Maximal Calibration Error
Args:
conf (numpy.ndarray): list of confidences
pred (numpy.ndarray): list of predictions
true (numpy.ndarray): list of true labels
bin_size: (float): size of one bin (0,1) # TODO should ... | 10,819 |
def validate_frame_range(shots, start_time, end_time, sequence_time=False):
"""
Verify if the given frame range is overlapping existing shots timeline
range. If it is overlapping any shot tail, it redefine the start frame at
the end of it. If it is overlapping any shot head, it will push back all
sh... | 10,820 |
def sparse_add(sv1, sv2):
"""dict, dict -> dict
Returns a new dictionary that is the sum of the other two.
>>>sparse_add(sv1, sv2)
{0: 5, 1: 6, 2: 9}
"""
newdict = {}
keys = set(sv1.keys()) | set(sv2.keys())
for key in keys:
x = sv1.get(key, 0) + sv2.get(key, 0)
newdict... | 10,821 |
def return_flagger(video_ID):
"""
In GET request
- Returns the username of the user that flagged the video with the corresponding video ID from the FLAGS table.
"""
if request.method == 'GET':
return str(db.get_flagger(video_ID)) | 10,822 |
def distanceModulus(sc, d2dm=True, **kw):
"""Distance Modulus.
DM = 5 log10(d / 10) + A
Parameters
----------
sc: SkyCoord
d2dm: bool
if true: distance -> DM
else: DM -> distance
Returns
-------
DM or distance: scalar, array
TODO
----
A, obs
... | 10,823 |
def get_all_hits():
"""Retrieves all hits.
"""
hits = [ i for i in get_connection().get_all_hits()]
pn = 1
total_pages = 1
while pn < total_pages:
pn = pn + 1
print "Request hits page %i" % pn
temp_hits = get_connection().get_all_hits(page_number=pn)
hits.extend(temp_hits)
return hits | 10,824 |
def create_socket(
host: str = "", port: int = 14443, anidb_server: str = "", anidb_port: int = 0
) -> socket.socket:
"""Create a socket to be use to communicate with the server.
This function is called internally, so you only have to call it if you want to change the default parameters.
:param host: ... | 10,825 |
def aten_eq(mapper, graph, node):
""" 构造判断数值是否相等的PaddleLayer。
TorchScript示例:
%125 : bool = aten::eq(%124, %123)
参数含义:
%125 (bool): 对比后结果。
%124 (-): 需对比的输入1。
%123 (-): 需对比的输入2。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_output... | 10,826 |
def flip_es_aliases():
"""Flip elasticsearch aliases to the latest version"""
_require_target()
with cd(env.code_root):
sudo('%(virtualenv_root)s/bin/python manage.py ptop_es_manage --flip_all_aliases' % env) | 10,827 |
def _create_simple_tf1_conv_model(
use_variable_for_filter=False) -> Tuple[core.Tensor, core.Tensor]:
"""Creates a basic convolution model.
This is intended to be used for TF1 (graph mode) tests.
Args:
use_variable_for_filter: Setting this to `True` makes the filter for the
conv operation a `tf.Va... | 10,828 |
def plot_diversity_bootstrapped(diversity_df):
"""Plots the result of bootstrapped diversity"""
div_lines = (
alt.Chart()
.mark_line()
.encode(
x="year:O",
y=alt.Y("mean(score)", scale=alt.Scale(zero=False)),
color="parametre_set",
)
)
... | 10,829 |
def test_atomic_unsigned_int_total_digits_nistxml_sv_iv_atomic_unsigned_int_total_digits_1_2(mode, save_output, output_format):
"""
Type atomic/unsignedInt is restricted by facet totalDigits with value
1.
"""
assert_bindings(
schema="nistData/atomic/unsignedInt/Schema+Instance/NISTSchema-SV-... | 10,830 |
def escape(s):
"""
Returns the given string with ampersands, quotes and carets encoded.
>>> escape('<b>oh hai</b>')
'<b>oh hai</b>'
>>> escape("Quote's Test")
'Quote's Test'
"""
mapping = (
('&', '&'),
('<', '<'),
('>', '>'),
(... | 10,831 |
def _get_db_columns_for_model(model):
"""
Return list of columns names for passed model.
"""
return [field.column for field in model._meta._fields()] | 10,832 |
def downgrade():
"""Migrations for the downgrade."""
raise NotImplementedError('Downgrade of 535039300e4a.') | 10,833 |
def mvkth(val):
""" Moves kth motor in the in the Kappa chamber
"""
name="kth"
Move_Motor_vs_Branch(name,val) | 10,834 |
def get_UV(filename):
"""
Input: filename (including path)
Output: (wave_leftedges, wav_rightedges, surface radiance) in units of (nm, nm, photons/cm2/sec/nm)
"""
wav_leftedges, wav_rightedges, wav, toa_intensity, surface_flux, SS,surface_intensity, surface_intensity_diffuse, surface_intensity_direct=np.genfromtx... | 10,835 |
def flip_robot_elbow(*args):
"""
Toggles Inverse Kinematic Solution 2 Boolean
:param args:
:return:
"""
robots = get_robot_roots()
if not robots:
pm.warning('Nothing Selected; Select a valid robot')
return
for robot in robots:
target_ctrl_attr = get_target_ctrl_... | 10,836 |
def load_chunks(chunk_file_location, chunk_ids):
"""Load patch paths from specified chunks in chunk file
Parameters
----------
chunks : list of int
The IDs of chunks to retrieve patch paths from
Returns
-------
list of str
Patch paths from the chunks
"""
patch_paths... | 10,837 |
def set_arguments() -> argparse.Namespace:
"""Setting the arguments to run from CMD
:return: arguments
"""
# Adding main description
parser = argparse.ArgumentParser(
description=f'{m.__description__}',
epilog=f'{m.__copyright__}\n | Versioon: {m.__version__}')
# Postional argu... | 10,838 |
def get_model_input(batch, input_id=None):
"""
Get model input from batch
batch: batch of model input samples
"""
if isinstance(batch, dict) or isinstance(batch, list):
assert input_id is not None
return batch[input_id]
else:
return batch | 10,839 |
def issym(b3):
"""test if a list has equal number of positive
and negative values; zeros belong to both. """
npos = 0; nneg = 0
for item in b3:
if (item >= 0):
npos +=1
if (item <= 0):
nneg +=1
if (npos==nneg):
return True
else:
return False | 10,840 |
def get_token(user, pwd, expires_in=3600, expire_on=None, device=None):
"""
Get the JWT Token
:param user: The user in ctx
:param pwd: Pwd to auth
:param expires_in: number of seconds till expiry
:param expire_on: yyyy-mm-dd HH:mm:ss to specify the expiry (deprecated)
:param device: The device in ctx
""... | 10,841 |
def predictOneVsAll(all_theta, X):
"""will return a vector of predictions
for each example in the matrix X. Note that X contains the examples in
rows. all_theta is a matrix where the i-th row is a trained logistic
regression theta vector for the i-th class. You should set p to a vector
of values fro... | 10,842 |
def lecture_produit(ligne : str) -> Tuple[str, int, float]:
"""Précondition : la ligne de texte décrit une commande de produit.
Renvoie la commande produit (nom, quantité, prix unitaire).
"""
lmots : List[str] = decoupage_mots(ligne)
nom_produit : str = lmots[0]
quantite : int = int(lmots[1])
... | 10,843 |
def print_curation_topic_tree(menu_topics, slugs=[]):
"""
Print the `menu_topics` obtained from `get_ka_learn_menu_topics` in the form
of a dict tree structure suitable for inclusion in `curaiton.py`.
The output of the function can be added to `TOPIC_TREE_REPLACMENTS_PER_LANG`
in `curation.py` to ob... | 10,844 |
def affinity_matrix(test_specs):
"""Generate a random user/item affinity matrix. By increasing the likehood of 0 elements we simulate
a typical recommending situation where the input matrix is highly sparse.
Args:
users (int): number of users (rows).
items (int): number of items (columns).
... | 10,845 |
def get_wm_desktop(window):
"""
Get the desktop index of the window.
:param window: A window identifier.
:return: The window's virtual desktop index.
:rtype: util.PropertyCookieSingle (CARDINAL/32)
"""
return util.PropertyCookieSingle(util.get_property(window,
... | 10,846 |
def get_parents(tech_id, model_config):
"""
Returns the full inheritance tree from which ``tech`` descends,
ending with its base technology group.
To get the base technology group,
use ``get_parents(...)[-1]``.
Parameters
----------
tech : str
model_config : AttrDict
"""
... | 10,847 |
def load_dynamic_configuration(
config: Configuration, secrets: Secrets = None
) -> Configuration:
"""
This is for loading a dynamic configuration if exists.
The dynamic config is a regular activity (probe) in the configuration
section. If there's a use-case for setting a configuration dynamically
... | 10,848 |
def _download_all_example_data(verbose=True):
"""Download all datasets used in examples and tutorials."""
# This function is designed primarily to be used by CircleCI. It has
# verbose=True by default so we get nice status messages
# Consider adding datasets from here to CircleCI for PR-auto-build
f... | 10,849 |
def main(argv=None):
"""Main function: Parse, process, print"""
if argv is None:
argv = sys.argv
args = parse_args(argv)
if not args:
exit(1)
original_tags = copy.deepcopy(tags.load(args["config"]))
with io.open(args["src"], "r", encoding="utf-8", errors="ignore") as fin:
... | 10,850 |
async def guess(botti, message, botData):
"""
Für alle ausführbar
Dieser Befehl schätzt eine Zahl zwischen 1 und 100 mit Einsatz.
!guess {ZAHL} {EINSATZ}
{ZAHL} Ganze positive Zahl <= 100
{EINSATZ} Ganze Zahl >= 0, "allin" [Setzt alles]
!guess 50 1000
"""
try:
guessValue = ... | 10,851 |
def profile_avatar(user, size=200):
"""Return a URL to the user's avatar."""
try: # This is mostly for tests.
profile = user.profile
except (Profile.DoesNotExist, AttributeError):
avatar = settings.STATIC_URL + settings.DEFAULT_AVATAR
profile = None
else:
if profile.is_f... | 10,852 |
def szz_reverse_blame(ss_path, sha_to_blame_on, buggy_line_num, buggy_file_path_in_ss, buggy_SHA):
"""Reverse-blames `buggy_line_num` (added in `buggy_SHA`) onto `sha_to_blame_on`."""
ss_repo = Repo(ss_path)
ss_name = pathLeaf(ss_path)
try:
# If buggy_SHA equals sha_to_blame_on, then git-blame-... | 10,853 |
def union(graphs, use_tqdm: bool = False):
"""Take the union over a collection of graphs into a new graph.
Assumes iterator is longer than 2, but not infinite.
:param iter[BELGraph] graphs: An iterator over BEL graphs. Can't be infinite.
:param use_tqdm: Should a progress bar be displayed?
:return... | 10,854 |
def merge_ondisk(trained_index: faiss.Index,
shard_fnames: List[str],
ivfdata_fname: str) -> None:
""" Add the contents of the indexes stored in shard_fnames into the index
trained_index. The on-disk data is stored in ivfdata_fname """
# merge the images into an on-disk ind... | 10,855 |
def get_month_n_days_from_cumulative(monthly_cumulative_days):
"""
Transform consecutive number of days in monthly data to actual number of days.
EnergyPlus monthly results report a total consecutive number of days for each day.
Raw data reports table as 31, 59..., this function calculates and returns
... | 10,856 |
def check_split_window(start, stop, lookup, transitions):
"""Check all possible splits"""
for split in range(start + 1, stop):
assert start < split < stop
m1, first = lookup.get((start, split), (None, None))
m2, second = lookup.get((split, stop), (None, None))
if first and second... | 10,857 |
def get_text(name):
"""Returns some text"""
return "Hello " + name | 10,858 |
def apply_template(assets):
"""
Processes the template.
Used for overwrite ``docutils.writers._html_base.Writer.apply_template``
method.
``apply_template(<assets>)``
``assets`` (dictionary)
Assets to add at the template, see ``ntdocutils.writer.Writer.assets``.
returns
functi... | 10,859 |
def test_easom_bound_fail(outbound):
"""Test easom bound exception"""
with pytest.raises(ValueError):
x = outbound(b["easom"].low, b["easom"].high, size=(3, 2))
fx.easom(x) | 10,860 |
def harvest(post):
"""
Filter the post data for just the funding allocation formset data.
"""
data = {k: post[k] for k in post if k.startswith("fundingallocation")}
return data | 10,861 |
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
... | 10,862 |
def model2(x, input_size, output_size):
"""! Fully connected model [InSize]x800x[OutSize]
Implementation of a [InSize]x800x[OutSize] fully connected model.
Parameters
----------
@param x : placeholder for input data
@param input_size : size of input data
@param output_size : size of output data
Returns... | 10,863 |
def test_optional_step_matching(env_boston, feature_engineer):
"""Tests that a Space containing `optional` `Categorical` Feature Engineering steps matches with
the expected saved Experiments. This regression test is focused on issues that arise when
`EngineerStep`s other than the last one in the `FeatureEng... | 10,864 |
def init_db():
"""For use on command line for setting up
the database.
"""
db.drop_all()
db.create_all() | 10,865 |
def cut_bin_depths(
dataset: xr.Dataset,
depth_range: tp.Union[int, float, list] = None
) -> xr.Dataset:
"""
Return dataset with cut bin depths if the depth_range are not outside the depth span.
Parameters
----------
dataset :
depth_range :
min or (min, max) to be include... | 10,866 |
async def test_if_action_before_sunrise_no_offset_kotzebue(hass, hass_ws_client, calls):
"""
Test if action was before sunrise.
Local timezone: Alaska time
Location: Kotzebue, which has a very skewed local timezone with sunrise
at 7 AM and sunset at 3AM during summer
After sunrise is true from ... | 10,867 |
def create_edgelist(file, df):
"""
creates an edgelist based on genre info
"""
# load edges from the (sub)genres themselves
df1 = (pd
.read_csv(file,
dtype='str'))
# get edges from the book descriptions df
df2 = (df[['title',
'subclass']]
... | 10,868 |
def CodeRange(code1, code2):
"""
CodeRange(code1, code2) is an RE which matches any character
with a code |c| in the range |code1| <= |c| < |code2|.
"""
if code1 <= nl_code < code2:
return Alt(RawCodeRange(code1, nl_code),
RawNewline,
... | 10,869 |
def test_wrong_data_path():
"""
Check that the error is thrown if the connector is a part of the signature,
but this particular data path (input or output) is already hidden
by a previously connected transformation.
"""
N = 200
coeff_dtype = numpy.float32
arr_type = Type(numpy.complex64... | 10,870 |
def build_raw_mint(fee, txhash, txix, out_addr1, out_addr2, in_lovelace,
policy_id, tokens, script, metadata, out_file = "matx.raw", burn_tokens = []):
"""
Generates the raw transaction for sending newly minted ingredients.
Always sends along 2 Ada, to be on the safe side for the minimal ... | 10,871 |
def sort_by_date(data):
"""
The sort_by_date function sorts the lists by their datetime
object
:param data: the list of lists containing parsed UA data
:return: the sorted date list of lists
"""
# Supply the reverse option to sort by descending order
return [x[0:6:4] for x in sorted(data, k... | 10,872 |
def get_menu_option():
"""
Function to display menu options and asking the user to choose one.
"""
print("1. View their next 5 fixtures...")
print("2. View their last 5 fixtures...")
print("3. View their entire current season...")
print("4. View their position in the table...")
print("... | 10,873 |
def pdf(mu_no):
""" the probability distribution function which the number of fibers per MU should follow """
return pdf_unscaled(mu_no) / scaling_factor_pdf | 10,874 |
def get_weather_by_key(key):
"""
Returns weather information for a given database key
Args:
key (string) -- database key for weather information
Returns:
None or Dict
"""
url = "%s/weather/%s.json" % (settings.FIREBASE_URL, key)
r = requests.get(url)
if r.status_code != 200:
... | 10,875 |
def source_receiver_midpoints(survey, **kwargs):
"""
Calculate source receiver midpoints.
Input:
:param SimPEG.electromagnetics.static.resistivity.Survey survey: DC survey object
Output:
:return numpy.ndarray midx: midpoints x location
:return numpy.ndarray midz: mi... | 10,876 |
def set_logger_class() -> None:
"""
Override python's logging logger class. This should be called as soon as possible.
"""
if logging.getLoggerClass() is not MCookBookLoggingClass:
logging.setLoggerClass(MCookBookLoggingClass)
logging.setLogRecordFactory(LogRecord)
logging.root... | 10,877 |
def test_mean_radial_velocity_vs_r4():
""" Brute force comparison of <Vr> calculation to pure python implementation,
with PBCs turned on, and cross-correlation is tested
"""
npts1, npts2 = 150, 151
with NumpyRNGContext(fixed_seed):
sample1 = np.random.random((npts1, 3))
sample2 = np.... | 10,878 |
def fix_source_scale(
transformer, output_std: float = 1, n_samples: int = 1000, use_copy: bool = True,
) -> float:
""" Adjust the scale for a data source to fix the output variance of a
transformer.
The transformer's data source must have a `scale` parameter.
Parameters
----------
transfo... | 10,879 |
def samplePinDuringCapture(f, pin, clock):
"""\
Configure Arduino to enable sampling of a particular light sensor or audio
signal input pin. Only enabled pins are read when capture() is subsequently called.
:param f: file handle for the serial connection to the Arduino Due
:param pin: The pin to en... | 10,880 |
def year_filter(year = None):
"""
Determine whether the input year is single value or not
Parameters
----------
year :
The input year
Returns
-------
boolean
whether the inputed year is a single value - True
"""
if year[0] == year[1]:
single_year ... | 10,881 |
def distance(p1, p2):
"""
Return the Euclidean distance between two QPointF objects.
Euclidean distance function in 2D using Pythagoras Theorem and linear algebra
objects. QPointF and QVector2D member functions.
"""
if not (isinstance(p1, QPointF) and isinstance(p2, QPointF)):
... | 10,882 |
def make_primarybeammap(gps, delays, frequency, model, extension='png',
plottype='beamsky', figsize=14, directory=None, resolution=1000, zenithnorm=True,
b_add_sources=False):
"""
"""
print("Output beam file resolution = %d , output directory = %s" % (resoluti... | 10,883 |
def view_page(request, content_id=None):
"""Displays the content in a more detailed way"""
if request.method == "GET":
if content_id:
if content_id.isdigit():
try:
# Get the contents details
content_data = Content.objects.get(pk=int(content_id))
content_data.fire = int(content_data.conten... | 10,884 |
def run_feat_model(fsf_file):
""" runs FSL's feat_model which uses the fsf file to generate
files necessary to run film_gls to fit design matrix to timeseries"""
clean_fsf = fsf_file.strip('.fsf')
cmd = 'feat_model %s'%(clean_fsf)
out = CommandLine(cmd).run()
if not out.runtime.returncode == 0:
... | 10,885 |
def test_list_ncname_length_1_nistxml_sv_iv_list_ncname_length_2_2(mode, save_output, output_format):
"""
Type list/NCName is restricted by facet length with value 6.
"""
assert_bindings(
schema="nistData/list/NCName/Schema+Instance/NISTSchema-SV-IV-list-NCName-length-2.xsd",
instance="n... | 10,886 |
def exportDSV(input, delimiter = ',', textQualifier = '"', quoteall = 0, newline = '\n'):
"""
PROTOTYPE:
exportDSV(input, delimiter = ',', textQualifier = '\"', quoteall = 0)
DESCRIPTION:
Exports to DSV (delimiter-separated values) format.
ARGUMENTS:
- input is list of lists of data (a... | 10,887 |
def DatasetSplit(X, y):
#Creating the test set and validation set.
# separating the target
""" To create the validation set, we need to make sure that the distribution of each class is similar
in both training and validation sets. stratify = y (which is the class or tags of each frame) keeps
... | 10,888 |
def test_good_input1() -> None:
""" Works on good input """
rv, out = getstatusoutput(f'{RUN} {SAMPLE1}')
assert rv == 0
assert out == 'Rosalind_0808 60.919540' | 10,889 |
def x_distance2(mesh):
"""Signed distances in the triangle planes from the opposite
edge towards the node for all evalution points in R
"""
# TODO: with gradient, needs mesh info
pass | 10,890 |
def parse_children(root):
"""
:param root: root tags of .xml file
"""
attrib_list = set()
for child in root:
text = child.text
if text:
text = text.strip(' \n\t\r')
attrib_list = attrib_list | get_words_with_point(text)
attrib_list = attrib_l... | 10,891 |
def load_data(ETF):
"""
Function to load the ETF data from a file, remove NaN values and set the Date column as index.
...
Attributes
----------
ETF : filepath
"""
data = pd.read_csv(ETF, usecols=[0,4], parse_dates=[0], header=0)
data.dropna(subset = ['Close', 'Date'... | 10,892 |
def update_disambiguation_report(authors, publication_uri):
"""
Given the authors structure and thte publication_uri, add to the report
if any of the authors need to be disambiguated
"""
for value in authors.values():
if value[8] == "Disambig":
if publication_uri in disambiguatio... | 10,893 |
def preprocess_LLIL_GOTO(bv, llil_instruction):
""" Replaces integer addresses of llil instructions with hex addresses of assembly """
func = get_function_at(bv, llil_instruction.address)
# We have to use the lifted IL since the LLIL ignores comparisons and tests
lifted_instruction = list(
[k fo... | 10,894 |
def _print_config() -> None:
"""print config"""
config = {
"Label": needs_response_label,
"Minimum Response Time": minimum_response_time,
"Exempt User List": exempt_user_list,
"Exempt Labels": exempt_labels,
"Exempt Authors": exempt_authors,
"Repo": repo.name,
... | 10,895 |
async def get_limited_f_result(request, task_id):
"""
This endpoint accepts the task_id and returns the result if ready.
"""
task_result = AsyncResult(task_id)
result = {
"task_id": task_id,
"task_status": task_result.status,
"task_result": task_result.result
}
return... | 10,896 |
async def main() -> None:
"""Create the aiohttp session and run the example."""
async with ClientSession() as session:
logging.basicConfig(level=logging.DEBUG)
try:
simplisafe = await API.async_from_refresh_token(
SIMPLISAFE_REFRESH_TOKEN, session=session
... | 10,897 |
def join_synset(pred_matrix, pb_defns, csvout, reject_non_english, use_model, synset):
"""
Dumps a (frame, synset) relation to CSVOUT by joining predicate matrix with FinnPropBank.
"""
# Load mapping from English PropBank senses to English WordNet senses
mapping = get_eng_pb_wn_map(pred_matrix, reje... | 10,898 |
def _test_qrcode():
"""二维码图片上传时识别"""
file_name = 'test_object_sdk_qrcode.file'
with open(file_name, 'rb') as fp:
# fp验证
opts = '{"is_pic_info":1,"rules":[{"fileid":"format.jpg","rule":"QRcode/cover/1"}]}'
response, data = client.ci_put_object_from_local_file_and_get_qrcode(
... | 10,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.