content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def merge_vocab(pair: Tuple[str, str], input_vocab: Dict[str, int]) -> Tuple[Dict[str, int], List]:
"""
>>> pair = ('w', 'o')
>>> input_vocab = {'b i r d @': 3, 'w o r d @': 7, 'w o g @': 13}
>>> new_vocab, new_pairs = merge_vocab(pair, input_vocab)
>>> new_vocab
{'b i r d @': 3, 'wo r d @': 7, ... | 13,000 |
def _handle_ping(dispatch, action):
"""Reply with PONG"""
handle = "hdmimatrix@dummy"
if action["payload"] == handle or action["payload"] == "*":
dispatch(pong()) | 13,001 |
def visualize_bbox_act(img, bboxes,labels, act_preds,
classes=None,thickness=1,
font_scale=0.4,show=False,
wait_time=0,out_file=None):
"""Show the tracks with opencv."""
assert bboxes.ndim == 2
assert labels.ndim == 1
assert bboxes.shape[0] == labels.shape[0]
... | 13,002 |
def calculate_similarity(subgraph_degrees):
"""
Given a list of subgraph degrees, this function calls the guidance
function and calculates the similarity of a particular node with all it's
non-connected nodes.
:param subgraph_degrees: A list of lists containing the non connected node
and degree... | 13,003 |
def balance_thetas(theta_sets_types, theta_sets_values):
"""Repeats theta values such that all thetas lists have the same length """
n_sets = max([len(thetas) for thetas in theta_sets_types])
for i, (types, values) in enumerate(zip(theta_sets_types, theta_sets_values)):
assert len(types) == len(va... | 13,004 |
def _format_weights(df, col, targets, regs):
"""
Reformat the edge table (target -> regulator) that's output by amusr into a pivoted table that the rest of the
inferelator workflow can handle
:param df: pd.DataFrame
An edge table (regulator -> target) with columns containing model values
:pa... | 13,005 |
def put_thread(req_thread: ReqThreadPut):
"""Put thread for video to DynamoDB"""
try:
input = thread_input.update_item(req_thread)
res = table.update_item(**input)
return res
except ClientError as err:
err_message = err.response["Error"]["Message"]
raise HTTPExcepti... | 13,006 |
def test_envelope_connection_id():
"""Test the property Envelope.connection_id."""
envelope_context = EnvelopeContext(
uri=URI("connection/author/connection_name/0.1.0")
)
envelope = Envelope(
to="to",
sender="sender",
protocol_id=PublicId("author", "name", "0.1.0"),
... | 13,007 |
def _get_or_create_campaign_team(name, owner, tasks, redudancy):
"""
Creates CampaignTeam instance, if it does not exist yet.
Returns reference to CampaignTeam instance.
"""
# pylint: disable-msg=no-member
_cteam = CampaignTeam.objects.get_or_create(
teamName=name,
owne... | 13,008 |
def pytest_configure(config):
"""
Prerequisites which needs to done in Before Suite
"""
os.environ["env"] = config.getoption("--env")
os.environ["api_retry_limit"] = config.getoption("--api_retry_limit")
os.environ["log_level"] = config.getoption("--log_level")
os.environ["api_wait_time"... | 13,009 |
def scaling_sorted(args):
"""
"""
scale_idx = args.scalecol - 1 # Python: 0-based indexing
with open(args.affinity, 'r') as affn:
header = affn.readline()
sys.stdout.write(header)
with open(args.signalScales, 'r') as scales:
for aln, sln in zip(affn, scales):
... | 13,010 |
def check_method(adata):
"""Check that method output fits expected API."""
assert "labels_pred" in adata.obs
return True | 13,011 |
async def test_get_subscriber_subscriptions(web_client, container):
"""Check subscriber subscriptions getting handler."""
newsfeed_id = '123'
subscription_storage = container.subscription_storage()
await subscription_storage.add(
{
'id': str(uuid.uuid4()),
'newsfeed_id':... | 13,012 |
def build_index_block(in_channels,
out_channels,
kernel_size,
stride=2,
padding=0,
groups=1,
norm_cfg=dict(type='BN'),
use_nonlinear=False,
expa... | 13,013 |
def nodes(*paths, type=None):
"""Call node() on each given path and return the list of results.
nodes('foo', 'bar', ...) is equivalent to
[node('foo'), node('bar'), ...]
"""
return list(map(lambda p: node(p, type=type), paths)) | 13,014 |
def GetCodeBucket(app, project):
"""Gets a bucket reference for a Cloud Build.
Args:
app: App resource for this project
project: str, The name of the current project.
Returns:
storage_util.BucketReference, The bucket to use.
"""
# Attempt to retrieve the default appspot bucket, if one can be cre... | 13,015 |
def parse_rule(parameter_string):
"""Parse a parameter string into its constituent name, type, and
pattern
For example:
`parse_parameter_string('<param_one:[A-z]>')` ->
('param_one', str, '[A-z]')
:param parameter_string: String to parse
:return: tuple containing
(parameter_nam... | 13,016 |
def plan():
"""
改进方案
:return:
"""
return render_template('plan.htm') | 13,017 |
def get_repo_meta(instance, **kwargs):
"""
Get and create git repository of user with token in commandline.
Post Save is called twice in Abstract User class.
Async produce unpredictible behaviour (Hence, populate some duplicate instance in repo)
"""
# async(tasks.get_repo, instance)
if not ... | 13,018 |
def extract_traceback(notebook):
""" Extracts information about an error from the notebook.
Parameters
----------
notebook: :class:`nbformat.notebooknode.NotebookNode`
Executed notebook to find an error traceback.
Returns
-------
bool
Whether the executed notebook has an er... | 13,019 |
def start(bot, update):
"""Send a message when the command /start is issued."""
update.message.reply_text('Здравствуйте! Чем можем помочь?') | 13,020 |
def test_insert_items_with_priority_add_all_at_that_priority(empty_priorityq):
"""Test inserting items into the queue adds them at given priority."""
q = empty_priorityq
q.insert(5, 6)
q.insert(3, 6)
q.insert(1, 6)
assert q._size == 1
assert q._all_values[1].priority == 6
assert len(q._a... | 13,021 |
def get_log() -> str:
"""get_log() -> str
(internal)
"""
return str() | 13,022 |
def start_server(self, parameters): # pragma: no cover
"""adds the server start to celery's queue
Args:
parameters(dict): The POST JSON parameters
"""
self.update_state(state=CeleryStates.started)
session = ServerSession(parameters)
return session() | 13,023 |
def generate_config(context):
""" Entry point for the deployment resources. """
properties = context.properties
name = properties.get('name', context.env['name'])
project_id = properties.get('project', context.env['project'])
bgp = properties.get('bgp', {'asn': properties.get('asn')})
router ... | 13,024 |
def MakeRootForHref(rootkml,region,lod,root_href):
"""Make a NetworkLink KML file to the root
Put the proper network URL here and publish this file.
All NetworkLinks below are relative to this.
Args:
rootkml - name of file to create
region - region of root of hierarchy
lod - minLodPixels
ro... | 13,025 |
def cachedmethod(timeout):
"""
Function decorator to enable caching for instance methods.
"""
def _cached(func):
if not(hasattr(func, 'expires')):
func.expires = {}
func.cache = {}
def __cached(self, *args, **kwargs):
if(timeout and func.expires.get(repr(self), 0) < time.time()):
if(repr(self) in f... | 13,026 |
def test_bad_construction():
"""Test bad construction parameters."""
with pytest.raises(ValueError):
OnExecutionComplete(
target_action='not-an-action',
on_completion=lambda *args: None
)
with pytest.raises(ValueError):
OnExecutionComplete(
target... | 13,027 |
def __build_pyramid(models, features):
"""Applies all submodels to each FPN level.
Args:
models (list): List of submodels to run on each pyramid level
(by default only regression, classifcation).
features (list): The FPN features.
Returns:
list: A list of tensors, one f... | 13,028 |
def get_ap_list():
"""
Method to return list of aps present in the network
"""
return jsonify_params(
CELLULAR_NETWORK.ap_list
) | 13,029 |
def test_sample_dataframe_schema() -> None:
"""Test the sample argument of schema.validate."""
df = pd.DataFrame({"col1": range(1, 1001)})
# assert all values -1
schema = DataFrameSchema(
columns={"col1": Column(Int, Check(lambda s: s == -1))}
)
for seed in [11, 123456, 9000, 654]:
... | 13,030 |
def set_title_z_offset(obj, offset):
"""
Set z-axis title offset
:param obj: drawable object
:type obj: TH1X, TGraph
:param offset: axis title offset value
:type offset: float
:return: nothing
:rtype: None
"""
set_axis_title_offset(obj, offset, 'z') | 13,031 |
def _merge_url_rule(rule_before, rule_after):
"""
Merges two url rule parts.
Parameters
----------
rule_before : `None` or `tuple` of `tuple` (`int`, `str`)
First url part if any to join `rule_after` to.
rule_after : `None` or `tuple` of `tuple` (`int`, `str`)
Second url part wh... | 13,032 |
def parse_options(args):
"""
Parse commandline arguments into options for Monitor
:param args:
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--tcp",
required=True,
action="append",
help="TCP/IP address to monitor, e.g. google.com:80. F... | 13,033 |
def check_file_executable(exe):
"""
Check the file can be executed
"""
try:
output=subprocess.check_output([exe,"--version"],stderr=subprocess.STDOUT)
except EnvironmentError as error:
if error.errno == errno.EACCES:
sys.exit("ERROR: Unable to execute software: " + e... | 13,034 |
def create_graphic_model(nodes, edges, gtype):
"""
Create a graphic model given nodes and edges
Parameters
----------
nodes : dict
for each node {key, text, math}
edges : dict
for each edge {key, text, math}
gtype : str [default="text"]
"text" for a verbose version, ... | 13,035 |
def zero_cross_bounds(arr, dim, num_cross):
"""Find the values bounding an array's zero crossing."""
sign_switch = np.sign(arr).diff(dim)
switch_val = arr[dim].where(sign_switch, drop=True)[num_cross]
lower_bound = max(0.999*switch_val, np.min(arr[dim]))
upper_bound = min(1.001*switch_val, np.max(ar... | 13,036 |
def remove_tseqs(t: ST_Type) -> ST_Type:
"""
Get just the sseqs and the non-nested types, removing the tseqs
"""
if type(t) == ST_SSeq or type(t) == ST_SSeq_Tuple:
inner_tseqs_removed = remove_tseqs(t.t)
return replace(t, t=inner_tseqs_removed)
elif is_nested(t):
return remov... | 13,037 |
def prod_cart(in_list_1: list, in_list_2: list) -> list:
"""
Compute the cartesian product of two list
:param in_list_1: the first list to be evaluated
:param in_list_2: the second list to be evaluated
:return: the prodotto cartesiano result as [[x,y],..]
"""
_list = []
for element_1 in ... | 13,038 |
def list_host(args):
"""List hosts"""
clientstable = PrettyTable(["Client", "Type", "Enabled", "Current"])
clientstable.align["Client"] = "l"
baseconfig = Kconfig(client=args.client, debug=args.debug).baseconfig
clients = baseconfig.list_hosts(empty()).clients
for entry in clients:
clien... | 13,039 |
def _write_building(buildings, lines):
"""
Args:
buildings (idf_MSequence): IDF object from idf.idfobjects()
lines (list): Text to create the T3D file (IDF file to import in
TRNBuild). To be appended (insert) here
"""
# Get line number where to write
log("Writing building... | 13,040 |
def classFactory(iface): # pylint: disable=invalid-name
"""Load esrimap class from file esrimap.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
from .esri_basemap import esrimap
return esrimap(iface) | 13,041 |
def gpib_open(name):
"""
Start a device session.
Returns a unique integer for the instrument at the specified GPIB address.
For example::
>>> gpib_open(lan[158.154.1.110]:19)
4
@param name : LAN/GPIB address of the device
@type name : str
@return: int
"""
(devtype,devID) = name.split()
add... | 13,042 |
def myjobs_view(request):
"""
Renderbox view
:param request:
:return:
"""
return render(request, 'renderbox/myjobs.html') | 13,043 |
def set_task_payload(func):
"""Set TASK_PAYLOAD and unset TASK_PAYLOAD."""
@functools.wraps(func)
def wrapper(task):
"""Wrapper."""
environment.set_value('TASK_PAYLOAD', task.payload())
try:
return func(task)
except: # Truly catch *all* exceptions.
e = sys.exc_info()[1]
e.extra... | 13,044 |
def _set_status(file_id, status):
"""Update status for file with id ``file_id``."""
assert file_id, 'Eh? No file_id?'
LOG.debug(f'Updating status file_id {file_id} with "{status}"')
with connect() as conn:
with conn.cursor() as cur:
cur.execute('UPDATE local_ega.files SET status = %(... | 13,045 |
def geometry_extractor_osm(locator, config):
"""this is where the action happens if it is more than a few lines in ``main``.
NOTE: ADD YOUR SCRIPT'S DOCUMENATION HERE (how)
NOTE: RENAME THIS FUNCTION (SHOULD PROBABLY BE THE SAME NAME AS THE MODULE)
"""
# local variables:
buffer_m = config.surro... | 13,046 |
def _match_contact(filter_criteria):
"""
This default matching strategy function will attempt to get a single result
for the specified criteria.
It will fail with an `unmatched` result if there are no matching contacts.
It will fail with a `multiple_matches` result if there are multiple matches
... | 13,047 |
def get_objects_dictionary():
"""
creates a dictionary with the types and the circuit objects
:return: Dictionary instance
"""
object_types = {'bus': Bus(),
'load': Load(),
'static_generator': StaticGenerator(),
'battery': Battery(),
... | 13,048 |
def create_stripe_onboarding_link(request, stripe_id=None,):
"""Creates stripe connect onboarding link by calling Stripe API."""
account_links = stripe.AccountLink.create(
account=stripe_id,
return_url=request.build_absolute_uri(
reverse("users:stripe_callback")
),
re... | 13,049 |
def add_scheme_if_missing(url):
"""
>>> add_scheme_if_missing("example.org")
'http://example.org'
>>> add_scheme_if_missing("https://example.org")
'https://example.org'
"""
if "//" not in url:
url = "http://%s" % url
return url | 13,050 |
def monkeypatch_pkg_resources(monkeypatch, monkeypatch_entrypoint):
"""Monkeypatching pkg_resources.iter_entry_points with our list of entry points."""
monkeypatch.setattr(pkg_resources, 'iter_entry_points', get_entry_points) | 13,051 |
def _extract_assembly_information(job_context: Dict) -> Dict:
"""Determine the Ensembl assembly version and name used for this index.
Ensembl will periodically release updated versions of the
assemblies which are where the input files for this processor
comes from. All divisions other than the main on... | 13,052 |
def fixture_circle_2() -> Circle:
"""Return an example circle."""
return Circle(Point(0.0, 0.0), 1.0) | 13,053 |
def parse_fortran(source, filename="<floopy code>", free_form=None, strict=None,
seq_dependencies=None, auto_dependencies=None, target=None):
"""
:returns: a :class:`loopy.TranslationUnit`
"""
parse_plog = ProcessLogger(logger, "parsing fortran file '%s'" % filename)
if seq_dependencies is... | 13,054 |
def plot_curve(lr_list, args, iters_per_epoch, by_epoch=True):
"""Plot learning rate vs iter graph."""
try:
import seaborn as sns
sns.set_style(args.style)
except ImportError:
print("Attention: The plot style won't be applied because 'seaborn' "
'package is not installe... | 13,055 |
def compute_sources(radius, evolved_vars):
"""
Computes source terms for the symmetry.
"""
mass_density = evolved_vars[0]
momentum_density = evolved_vars[1]
energy_density = evolved_vars[2]
factor = -_symmetry_alpha / radius
pressure = compute_pressure(mass_density, momentum_density, ene... | 13,056 |
def average_pq(ps, qs):
""" average the multiple position and quaternion array
Args:
ps (np.array): multiple position array of shape Nx3
qs (np.array): multiple quaternion array of shape Nx4
Returns:
p_mean (np.array): averaged position array
q_mean (np.array): averaged qua... | 13,057 |
def logobase(**kwargs):
"""Create a PyGraphviz graph for a logo."""
ag = pygraphviz.AGraph(bgcolor='#D0D0D0', strict=False, directed=True, ranksep=0.3, **kwargs)
ag.edge_attr['penwidth'] = 1.4
ag.edge_attr['arrowsize'] = 0.8
return ag | 13,058 |
def integral_raycasting(
pixels: Tensor,
mu: Tensor,
rho: Tensor,
lambd: Tensor,
appearance: Tensor,
background_appearance: Tensor,
K: Tensor,
dist_coef: Tensor = None,
alpha: float = 2.5e-2,
beta: float = 2e0,
eps: float = 1e-8,
) -> Tensor:
"""
:param pixels: [H, W... | 13,059 |
async def cors_handler(request, handler):
"""Middleware to add CORS response headers
"""
response = await handler(request)
response.headers['Access-Control-Allow-Origin'] = '*'
return response | 13,060 |
def validate_image(task: ExternalTask):
"""
To simulate BPMN/Failure/Success, this handler uses image name variable (to be passed when launching the process)
"""
log_context = {"WORKER_ID": task.get_worker_id(),
"TASK_ID": task.get_task_id(),
"TOPIC": task.get_topic... | 13,061 |
def simulate_patch(app, path, **kwargs):
"""Simulates a PATCH request to a WSGI application.
Equivalent to::
simulate_request(app, 'PATCH', path, **kwargs)
Args:
app (callable): The WSGI application to call
path (str): The URL path to request
Keyword Args:
params (di... | 13,062 |
def capture_video_frames(source_path: string, dest_path: string, duration: float, fps: int = 24):
"""
Used for preparing a data set. Loads a video, which is expected to be in the .mp4 format
and stores the single frames of this video.
--------------------------------------------------------------------... | 13,063 |
def test_render_template_broken():
"""A broken template should raise an error"""
with pytest.raises(TemplateSyntaxError) as ex:
render_template(BROKEN_TEMPLATE, context=VARS)
assert "Invalid block tag" in ex.value.args[0] | 13,064 |
def purge_files():
""" Remove all generated files from previous runs. """
for fname in glob.glob("*.png"):
print("Deleting {!r} ...".format(fname))
os.unlink(fname)
for fname in glob.glob("*.png.old"):
print("Deleting {!r} ...".format(fname))
os.unlink(fname) | 13,065 |
def _merge_nbval_coverage_data(cov):
"""Merge nbval coverage data into pytest-cov data."""
if not cov:
return
if coverage.version_info > (5, 0):
data = cov.get_data()
nbval_data = coverage.CoverageData(data.data_filename(), suffix='.nbval', debug=cov.debug)
nbval_dat... | 13,066 |
def minimum_image_box(sizes):
"""Creates a distance wrapper using the minimum image convention
Arguments:
sizes (array-like of float): box sizes
"""
def _box(sizes, distance_vectors):
"""A minimum image wrapper for distances"""
shift = sizes[None, None, :] * np.round(distance_ve... | 13,067 |
def mlrPredict(W, data):
"""
mlrObjFunction predicts the label of data given the data and parameter W
of Logistic Regression
Input:
W: the matrix of weight of size (D + 1) x 10. Each column is the weight
vector of a Logistic Regression classifier.
X: the data matri... | 13,068 |
def plot_binary_logistic_boundary(logreg, X, y, xlim, ylim):
"""Plots the boundary given by the trained logistic regressor
:param logreg: Logistic Regrssor model
:type logreg: logistic_regression.LogisticRegressionModel
:param X: The features and samples used to train
:type X: np.ndarray
:p... | 13,069 |
def _wrap(wrapper, func):
"""
save wrapped function if multiple decorators are used
:param func:
:return:
"""
setattr(wrapper, '__wrapped__', func) | 13,070 |
def calc_mean_score(movies):
"""Helper method to calculate mean of list of Movie namedtuples,
round the mean to 1 decimal place"""
return round(sum([movie.score for movie in movies]) / len(movies), 1) | 13,071 |
def get_proxy_signature(query_dict, secret):
"""
Calculate the signature of the given query dict as per Shopify's documentation for proxy requests.
See: http://docs.shopify.com/api/tutorials/application-proxies#security
"""
# Sort and combine query parameters into a single string.
sorted_params... | 13,072 |
def candlestick_echarts(data_frame: pd.DataFrame, time_field: str = 'time', open_field: str = "open",
high_field: str = 'high',
low_field: str = 'low',
close_field: str = 'close',
volume_field: str = 'volume', mas: list = [5... | 13,073 |
def select_sounder_hac(path_sounder, sounder):
"""
Donne les indices pour un sondeur (sounder) dans un hac (path sounder), et retourne les index de sondeur et de transducer correspondant
inputs:
path_sounder: path du hac à analyser
sounder: nom du transducer
outputs:
index du son... | 13,074 |
def check_configured_topic(host, topic_configuration,
topic_name, kafka_servers, deleted_options=None):
"""
Test if topic configuration is what was defined
"""
# Forcing api_version to 0.11.0 in order to be sure that a
# Metadata_v1 is sent (so that we get the controller i... | 13,075 |
def upvote_checklist(request, checklist_id):
# for "messages", refer https://stackoverflow.com/a/61603003/6543250
"""if user cannot retract upvote, then this code be uncommented
if Upvote.objects.filter(user=User.objects.filter(username=username).first(), checklist=Checklist.objects.get(id=checklist_id)):
... | 13,076 |
def index(request):
"""查询页面"""
ctx = {}
Advert_1 = Advert.objects.get(advert_num=1) # 广告1
Advert_2 = Advert.objects.get(advert_num=2) # 广告2
ctx['Adverturl1'] = Advert_1.advert_url
ctx['Adverturl2'] = Advert_2.advert_url
ctx['Advertimg1'] = '/advert/'+ str(Advert_1.img)
ctx['A... | 13,077 |
def load_amazon():
"""
"""
df = pd.read_csv('data/amazon.txt',
header=None,
delimiter='\t')
X_data = df[0].tolist()
y_data = df[1].tolist()
print 'Preprocessing...'
vectorizer = TfidfVectorizer(strip_accents='unicode',
lowercase=True,
stop_words='english',
ngram_range=(1, 2),
max_df=0.5,
min_df=5... | 13,078 |
def get_switch_filters(
switch_id, exception_when_missing=True,
user=None, session=None, **kwargs
):
"""get filters of a switch."""
return _get_switch(
switch_id, session=session,
exception_when_missing=exception_when_missing
) | 13,079 |
def generalized_zielonka_with_psolC(g):
"""
Zielonka's algorithm with psolC partial solver.
:param g: the game to solve.
:return: the solution in the following format : (W_0, W_1).
"""
return generalized_parity_solver_with_partial(g, psolC_gen.psolC_generalized) | 13,080 |
def plot_matrix(mat, figsize=(7, 4), draw_cbar=True, vmin=0, vmax=1, cmap=None):
"""
wrapper for plotting a matrix of probabilities.
attribues (optional) are used as xlabels
"""
if np.any(mat < 0):
print('rescaling matrix to probabilities')
mat = .5 * (mat + 1)
try:
imp... | 13,081 |
def dump_txt(records: Iterable[Record], file: TextIO) -> None:
"""Saves AnimData records to a tabbed text file.
:param records: Iterable of `Record`s to write to the `file`.
:param file:
A text file object, or any any object with a `write()` method.
If `file` is a file object, it should be ... | 13,082 |
def read_properties_core(xml_source):
"""Read assorted file properties."""
properties = DocumentProperties()
root = fromstring(xml_source)
creator_node = root.find(QName(NAMESPACES['dc'], 'creator').text)
if creator_node is not None:
properties.creator = creator_node.text
else:
p... | 13,083 |
def batch_decode(loc, priors, variances):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offse... | 13,084 |
def __save_image_file__(img, file_name, output_path, wmode):
"""
Saves the PIL image to a file
:param img: PIL image
:param file_name: File name
:param output_path: Output path
:param wmode: Work mode
"""
# create output directory if it doesn't exist
dir = os.path.dirname(output_path... | 13,085 |
def generate_app():
"""Creates a summary report for hte generated builds."""
click.echo(click.style(f'Building app in {os.getcwd()}', bg='green'))
config = load_appear_config()
if config is False:
exit(1) | 13,086 |
async def test_service_unload(hass):
"""Verify service unload works."""
hass.data[deconz.services.DECONZ_SERVICES] = True
with patch(
"homeassistant.core.ServiceRegistry.async_remove", return_value=Mock(True)
) as async_remove:
await deconz.services.async_unload_services(hass)
as... | 13,087 |
def _step2_macs_seq (configs):
"""Step2 MACS if the raw data type is seq. So it will use the output from step1.
"""
# check the input
t_rep_files = configs["samtools.treat_output_replicates"]
t_comb_file = configs["samtools.treat_output"]
c_comb_file = configs["samtools.control_output"]
... | 13,088 |
def menu_entry_to_db(entry):
"""
Converts a MenuEntry into Meal, Menu, and MenuItem objects which are stored in the database.
"""
menu, _ = Menu.objects.get_or_create(date=entry.date)
meal = Meal.objects.create(meal_type=entry.meal_type, vendor=entry.vendor)
for item_name in entry.items:
... | 13,089 |
def get_device_of(tensor: torch.Tensor) -> int:
"""
Returns the device of the tensor.
"""
if not tensor.is_cuda:
return -1
else:
return tensor.get_device() | 13,090 |
def test_script_task(scheduler: Scheduler) -> None:
"""
Tasks should be definable as shell scripts.
"""
@task(script=True)
def task1(message):
return """echo Hello, {message}!""".format(message=message)
assert scheduler.run(task1("World")) == b"Hello, World!\n" | 13,091 |
def initialize(indexCallback=None):
"""
@param indexCallback: A function which is called when eSpeak reaches an index.
It is called with one argument:
the number of the index or C{None} when speech stops.
"""
global espeakDLL, bgThread, bgQueue, player, onIndexReached
espeakDLL = cdll.LoadLibrary(os.pat... | 13,092 |
def __yaml_tag_test(*args, **kwargs):
"""YAML tag constructor for testing only"""
import copy
return copy.deepcopy(args), copy.deepcopy(kwargs) | 13,093 |
def _create_fake_bids_dataset(base_dir='', n_sub=10, n_ses=2,
tasks=['localizer', 'main'],
n_runs=[1, 3], with_derivatives=True,
with_confounds=True, no_session=False):
"""Creates a fake bids dataset directory with dummy files... | 13,094 |
def format_data_for_training(data):
"""
Create numpy array with planet features ready to feed to the neural net.
:param data: parsed features
:return: numpy array of shape (number of frames, PLANET_MAX_NUM, PER_PLANET_FEATURES)
"""
training_input = []
training_output = []
for d in data:
... | 13,095 |
def idcardcert(appcode, card_no):
""" 身份证实名认证身份证二要素一致性验证 """
host = 'http://idquery.market.alicloudapi.com'
path = '/idcard/query'
# method = 'GET'
appcode = appcode
querys = 'number=%s' % card_no
# bodys = {}
url = host + path + '?' + querys
try:
request = urllib.request.Req... | 13,096 |
def custom_error_exception(error=None, exception=None):
"""Define custom exceptions for MySQL server errors
This function defines custom exceptions for MySQL server errors and
returns the current set customizations.
If error is a MySQL Server error number, then you have to pass also the
exception ... | 13,097 |
def cal_md5(content):
"""
计算content字符串的md5
:param content:
:return:
"""
# 使用encode
result = hashlib.md5(content.encode())
# 打印hash
md5 = result.hexdigest()
return md5 | 13,098 |
def get_arkouda_server_info_file():
"""
Returns the name of a file to store connection information for the server.
Defaults to ARKOUDA_HOME + ak-server-info, but can be overridden with
ARKOUDA_SERVER_CONNECTION_INFO
:return: server connection info file name as a string
:rtype: str
"""
... | 13,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.