content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def data_coded_table(request, project_pk):
"""This returns the labeled data.
Args:
request: The POST request
project_pk: Primary key of the project
Returns:
data: a list of data information
"""
project = Project.objects.get(pk=project_pk)
data_objs = DataLabel.objects.f... | 4,200 |
def when(name, converters=None):
"""When step decorator.
:param name: Step name.
:param converters: Optional `dict` of the argument or parameter converters in form
{<param_name>: <converter function>}.
:param parser: name of the step parser to use
:param parser_args: optional... | 4,201 |
def plot_roc_curve(y_true, predictions, title='Dementia'):
"""
Plots the ROC curve of many models together
Parameters
----------
y_true : True labels
predictions : Dictionary with one (key, value) par for each model's predictions.
Returns
-------
"""
plt.figu... | 4,202 |
def displacement(current: np.ndarray, previous: np.ndarray) -> np.array:
"""Computes the displacement vector between the centroids of two storms.
:param current: the intensity-weighted centroid of the storm in the current time slice, given as a tuple.
:param previous: the intensity-weighted centroid of the ... | 4,203 |
def update_datapackage(datapackage, mappings):
"""Update the field names and delete the `maps_to` properties."""
for i, resource in enumerate(datapackage['resources']):
fields = []
for field in resource['schema']['fields']:
fiscal_key = mappings[i][field['name']]
if fi... | 4,204 |
def get_molpro_mol(logfile):
"""
Returns xyz file from molpro logfile.
"""
import pybel
return pybel.readfile('mpo',logfile).next() | 4,205 |
def tbody(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", transl... | 4,206 |
def create_controller():
"""
1. Check the token
2. Call the worker method
3. Show results
"""
minimum_buffer_min = 3
token_ok = views.ds_token_ok(minimum_buffer_min)
if token_ok and 'envelope_id' in session:
# 2. Call the worker method
args = {
'account_id': s... | 4,207 |
def pack(number, word_size = None, endianness = None, sign = None, **kwargs):
"""pack(number, word_size = None, endianness = None, sign = None, **kwargs) -> str
Packs arbitrary-sized integer.
Word-size, endianness and signedness is done according to context.
`word_size` can be any positive number or ... | 4,208 |
def getSourceUrls(db):
"""获取未被爬取的文献来源链接"""
sql = """
SELECT DISTINCT
re_article_source.url_source
FROM
re_article_source
LEFT JOIN source ON re_article_source.url_source = source.url
WHERE
source.url IS NULL
... | 4,209 |
def ML_bump(x,v=None,logger=None):
"""
ML fit of the bump function
Parameters
----------
x : (n,d) ndarray
coML estimatearaites
v : (n,) ndarray
weight for each sample
Returns
-------
mu : (n,d) ndarray
bump mean parameter (for each dimension)
sigma : (... | 4,210 |
def read_message_handler(stream):
"""
Send message to user if the opponent has read the message
"""
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
user_opponent = packet.get('username')
message_id = packet.get('message_id')
if ... | 4,211 |
def parse_arguments(args_to_parse):
""" Parse the command line arguments.
"""
description = "Find targets which contain a None reference"
parser = argparse.ArgumentParser(description=description)
parser.add_argument(
'-d', '--directory-to-search', type=str, required=True,
help='Dire... | 4,212 |
def user_with_some_privileges(self, table_type, node=None):
"""Check that user with any permutation of ALTER INDEX subprivileges is able
to alter the table for privileges granted, and not for privileges not granted.
"""
if node is None:
node = self.context.node
table_name = f"merge_tree_{ge... | 4,213 |
def function_f1a(x):
"""Function with one argument, returning one value.
:type x: types.IntType
:rtype: types.StringType
"""
return '{}'.format(x) | 4,214 |
def is_port_in_use(hostname: str, port: Union[int, str]) -> bool:
"""
Check if TCP/IP `port` on `hostname` is in use
"""
with socket() as sock:
try:
sock.bind((hostname, int(port)))
return False
except OSError as err:
if "Address already in use" in rep... | 4,215 |
def _pos_from_before_after(
before: int, after: int, length: int, base0: bool
) -> int:
"""Get the position to insert from before and after"""
if before is not None and after is not None:
raise ValueError("Can't specify both `_before` and `_after`.")
if before is None and after is None:
... | 4,216 |
def prep_incorporation_correction_filing(session, business, original_filing_id, payment_id, option,
name_change_with_new_nr):
"""Return a new incorporation correction filing prepped for email notification."""
filing_template = copy.deepcopy(CORRECTION_INCORPORATION)
... | 4,217 |
def get_logger():
"""
Return the custom showyourwork logger.
Sets up the logging if needed.
"""
logger = logging.getLogger("showyourwork")
# Add showyourwork stream & file handlers
if not logger.handlers:
# Root level
logger.setLevel(logging.DEBUG)
# Terminal: al... | 4,218 |
def web_videos_random_archived(channel):
"""Play random archived video.
Chooses random archived video from selected channel and redirects to its
detail page view.
Args:
channel (str): YouTube channel ID.
Returns:
flask.Response: Selected video detail view.
"""
try:
... | 4,219 |
def p_function_stmt(p):
"""function_stmt : FUNCTION subroutine_name
| prefix_spec_list FUNCTION subroutine_name
"""
if len(p) > 3:
p[0] = (p[3], p[0])
else:
p[0] = (p[2], None) | 4,220 |
def fundamental_mode_mfd_marcuse(wl, r, na):
"""Calculates the mode field diameter of the fundamental mode with vacuum wavelength wl using Marcuse's equation.
:param wl: Wavelength of the mode
:type wl: float
:param r: Core radius
:type r: float
:param na: Core numerical aperture
:type na: ... | 4,221 |
def create_pdf(source_image_file, ta_pages, config, output_filename ):
"""透明なテキストと画像入りのPDFを作成するメソッド"""
print("processing pdf: {0}".format(output_filename))
is_normalized = False
# PDFまたは画像をページ分割
if re.search(r'\.pdf$', source_image_file ) :
images = convert_pdf_to_img(source_image_file, ... | 4,222 |
def generate_ansible_coverage_config(): # type: () -> str
"""Generate code coverage configuration for Ansible tests."""
coverage_config = '''
[run]
branch = True
concurrency = multiprocessing
parallel = True
omit =
*/python*/dist-packages/*
*/python*/site-packages/*
*/python*/distutils/*
*/pys... | 4,223 |
def gauss_smooth_shift(input, shift, stddev, scale=1.0):
"""
smooths the input with gaussian smooothing with standarddeviation and shifts its delay positions
:param input: The input array
:param shift: the amount of indices to shift the result
:param the stddev for the gaussian smoothing (in index ... | 4,224 |
def mel_to_hz(mel):
"""From Young et al. "The HTK book", Chapter 5.4."""
return 700.0 * (10.0**(mel / 2595.0) - 1.0) | 4,225 |
def create_app(path=None, user_content=False, context=None, username=None,
password=None, render_offline=False, render_wide=False,
render_inline=False, api_url=None, title=None, text=None,
autorefresh=None, quiet=None, grip_class=None):
"""
Creates an Grip applicatio... | 4,226 |
def get_simulator_version():
""" Get the installed version of XPP
Returns:
:obj:`str`: version
"""
result = subprocess.run(["xppaut", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
if result.returncode != 0:
raise RuntimeError('XPP failed: {}'.format(resul... | 4,227 |
def enumerate_joint(variables, e, P):
"""Return the sum of those entries in P consistent with e,
provided variables is P's remaining variables (the ones not in e)."""
if not variables:
return P[e]
Y, rest = variables[0], variables[1:]
return sum([enumerate_joint(rest, extend(e, Y, y), P)
... | 4,228 |
def fetch_gene_id(gene_id, ENSEMBL_REST_SERVER = GRCH37_ENSEMBL_REST_SERVER):
"""
Get gene details from name
* string
Returntype: Gene
"""
server = ENSEMBL_REST_SERVER
ext = "/lookup/id/%s?content-type=application/json" % (gene_id)
try:
hash = postgap.REST.get(server, ext)
return Gene(
name = hash['... | 4,229 |
def allCategoriesJSON():
"""
Generates JSON for all categories
"""
categories = db_session.query(Category).all()
return jsonify(categories=[c.serialize for c in categories]) | 4,230 |
def get_rrule(rule, since, until):
"""
Compute an RRULE for the execution scheduler.
:param rule: A dictionary representing a scheduling rule.
Rules are of the following possible formats (e.g.):
{'recurrence': '2 weeks', 'count': 5, 'weekdays': ['SU', 'MO', 'TH']}
= run every 2 weeks... | 4,231 |
def site_id(request):
"""Site id of the site to test."""
return request.param if hasattr(request, 'param') else None | 4,232 |
def raise_if(cond: bool, cls: type, msg: str):
"""Raise exception if cond is true."""
if cond:
raise cls(msg) | 4,233 |
def foo():
"""Example function"""
# TO-DO
raise NotImplementedError | 4,234 |
def parse(limit_string):
"""
parses a single rate limit in string notation
(e.g. '1/second' or '1 per second'
:param string limit_string: rate limit string using :ref:`ratelimit-string`
:raise ValueError: if the string notation is invalid.
:return: an instance of :class:`RateLimitItem`
"""... | 4,235 |
def change_balance(email):
"""Change a user's balance."""
if not isinstance(request.json.get('change'), int):
abort(400, {'message': 'The change in innopoints must be specified as an integer.'})
user = Account.query.get_or_404(email)
if request.json['change'] != 0:
new_transaction = Tra... | 4,236 |
def install():
""" Install the package (in development mode). """
click.echo("Installing mitoviz...")
subprocess.check_call(["pip", "install", "-e", "."])
click.echo("Done.") | 4,237 |
def contact_infectivity_asymptomatic_40x70():
"""
Real Name: b'contact infectivity asymptomatic 40x70'
Original Eqn: b'contacts per person normal 40x70*infectivity per contact'
Units: b'1/Day'
Limits: (None, None)
Type: component
b''
"""
return contacts_per_person_normal_40x70() * i... | 4,238 |
def generate_resource_link(pid, resource_path, static=False, title=None):
"""
Returns a valid html link to a public resource within an autogenerated instance.
Args:
pid: the problem id
resource_path: the resource path
static: boolean whether or not it is a static resource
ti... | 4,239 |
def test_df_upload(mock_put, la_uploader):
"""Check DataFrame upload."""
response = Response()
response.status_code = 200
mock_put.return_value = response
data_path = Path(_TEST_DATA).joinpath("syslog_data.csv")
data = pd.read_csv(data_path)
la_uploader.upload_df(data, "test") | 4,240 |
def make_cointegrated(seed, n_samples, gamma):
"""
cointegrated pair:
- x0_t = x0_t-1 + gauss[:, 0]
- x1_t = gamma * x0_t + gauss[:, 1]
for various gamma.
cf: Hamilton [19.11.1, 19.11.2]
"""
np.random.seed(seed)
x0 = np.random.randn(n_samples).cumsum()
x1 = gamma * x0 + ... | 4,241 |
def test_process_data_path(tmp_raster_fixture):
"""
Checks the raster processing for multiple images.
"""
in_path, _ = tmp_raster_fixture
img_file_list = [in_path]
feature_list: List[Feature] = []
for img_path in img_file_list:
bbox = [2.5, 1.0, 4.0, 5.0]
geom = box(*bbox)
... | 4,242 |
def web_index():
"""主页"""
news = db.session.query(HotHomeNews).to_dicts
home = list()
hot = list()
temp = 30
for index, i in enumerate(news):
temp -= random.randint(0, 2)
i['date'] = '2021-04' + '-' + str(temp)
if i['hot'] == 1:
hot.append(i)
else:
... | 4,243 |
def test_parametrize():
"""Tests parametrizing a function"""
@arg.parametrize(val=arg.val('vals'))
def double(val):
return val * 2
assert double(vals=[1, 2, 3]) == [2, 4, 6]
# This should result in a lazy bind error
with pytest.raises(arg.BindError):
double(val=1)
# Parti... | 4,244 |
def F_to_C(Tf):
"""convertit une temperature de Fahrenheit en Celsius"""
Tc = (Tf-32)*5/9
return Tc | 4,245 |
def generate_mdn_sample_from_ouput(output, test_size,distribution = 'Normal',
params = None):
"""
Using the output layer from the prediction on a fitted mdn model
generate test_size number of samples. (Note output corresponds to a
one-dimensional output).
Paramete... | 4,246 |
def infer_folding_rates(clusters, activation_energies, prefactors, G, temperatures):
"""
Takes Arrenius parameters and uses detailed balance to compute folding rates
"""
print('Inferring unknown folding rates from detailed balance...')
Nclusters = len(clusters)
folding_rates=np.nan*np.zeros((Nc... | 4,247 |
def create_cry_nqubit(qc: qiskit.QuantumCircuit, thetas: np.ndarray):
"""Create control Control-RY state
Args:
- qc (qiskit.QuantumCircuit): init circuit
- thetas (np.ndarray): parameters
Returns:
- qiskit.QuantumCircuit
"""
for i in range(0, qc.num_qubits - 1, 2):
... | 4,248 |
def get_region(h5_dset, reg_ref_name):
"""
Gets the region in a dataset specified by a region reference
Parameters
----------
h5_dset : h5py.Dataset
Dataset containing the region reference
reg_ref_name : str / unicode
Name of the region reference
Returns
-------
val... | 4,249 |
def terminate_simulation_when(reqID, req, line):
"""Function implementing the 'terminate simulation when' statement."""
makeRequirement(RequirementType.terminateSimulationWhen, reqID, req, line) | 4,250 |
def agent(game, n_ep, n_mcts, max_ep_len, lr, c, gamma, data_size, batch_size,
temp, n_hidden_layers, n_hidden_units):
""" Outer training loop """
seed_best = None
a_best = None
episode_returns = [] # storage
timepoints = []
# environments
env = make_game(game)
is_atari = is_a... | 4,251 |
def butter_bandpass_filter(data, lowcut, highcut, sample_rate, order):
"""
Bandpass filter the data using Butterworth IIR filters.
Two digital Butterworth IIR filters with the specified order are created, one highpass filter for the lower critical
frequency and one lowpass filter for the higher critica... | 4,252 |
def _check_tensor_info(*tensors, size, dtype, device):
"""Check if sizes, dtypes, and devices of input tensors all match prescribed values."""
tensors = list(filter(torch.is_tensor, tensors))
if dtype is None and len(tensors) == 0:
dtype = torch.get_default_dtype()
if device is None and len(ten... | 4,253 |
def generate_dataset(df, n_past, n_future):
"""
df : Dataframe
n_past: Number of past observations
n_future: Number of future observations
Returns:
X: Past steps
Y: Future steps (Sequence target)
Z: Sequence category"""
# Split the dataframe with respect to IDs
series_ids =... | 4,254 |
def test_build_feedstock_default(mocker):
"""
Tests that the default arguments for 'build_feedstock' generate the correct 'conda_build.api.build' input args.
"""
mocker.patch(
'os.getcwd',
return_value="/test/test_recipe"
)
mocker.patch(
'os.path.exists',
return_v... | 4,255 |
def safe_mkdir(path):
"""
Create a directory if there isn't one already
Deprecated in favor of os.makedirs(path, exist_ok=True)
"""
try:
os.mkdir(path)
except OSError:
pass | 4,256 |
def setup_exps_rllib(flow_params,
n_cpus,
n_rollouts,
reward_specification=None,
policy_graphs=None,
policy_mapping_fn=None,
policies_to_train=None):
"""Return the relevant components of an RLlib experiment.
Parameters
----------
flow... | 4,257 |
def upsampling2D(
inputs: Optional[tf.Tensor] = None,
size: Tuple[int, int] = (2, 2),
mode: Literal['pad', 'nearest', 'bilinear'] = 'nearest',
name: Optional[str] = None,
) -> Union[tf.Tensor, Resampling2D]:
""" Upsampling"""
layer = Resampling2D(size, mode, name=name)
if inputs is None:
retur... | 4,258 |
def sns_msg_body_user_notify_topic(message, autoscale_group, instance_id, details=None):
"""
Purpose: To prepare dict with correct values for user topic
Parameters: message, group name, instance_id, details
Returns: dict
Raises:
"""
# Constructing a JSON object as per AWS SNS requireme... | 4,259 |
def moderator_name():
"""Return the name of the test game moderator."""
return 'Hannah' | 4,260 |
def sync_model(sender, app_config, **kwargs):
"""Push django model data to google fusion table."""
if django.apps.apps.ready:
for model_string in app_settings.MODELS_TO_SYNC:
model_class = django.apps.apps.get_model(model_string)
signals.post_save.connect(push_data, sender=model_... | 4,261 |
def course(x=0, y=0):
""" Faire avancer le cavalier autant que possible. """
HISTORIQUE.append((x, y))
last_move = (0, 0)
afficher(last_move)
while True:
(x, y) = HISTORIQUE[-1]
poss = proposer(x, y)
if poss == []:
input("BLOQUE ! Seul choix possible : arrière."... | 4,262 |
def delete_downloads():
"""Delete all downloaded examples to free space or update the files."""
shutil.rmtree(geoist.EXAMPLES_PATH)
os.makedirs(geoist.EXAMPLES_PATH)
return True | 4,263 |
def test_raises_when_not_on_correct_branch(git_server, qisrc_action, record_messages):
""" Test Raises When Not On Correct Branch """
git_server.create_repo("foo")
git_server.switch_manifest_branch("devel")
git_server.change_branch("foo", "devel")
qisrc_action("init", git_server.manifest_url, "--bra... | 4,264 |
def reversebits2(max_bits, num):
""" Like reversebits1, plus small optimization regarding bit index
calculation. """
rev_num = 0
high_shift = max_bits - 1
low_shift = 0
for _ in range(0, (max_bits + 1) // 2):
low_bit = (num & (1 << low_shift)) >> low_shift
high_bit = (num &... | 4,265 |
def _get_builder_cls(
ds_to_build: str,
) -> Tuple[Type[tfds.core.DatasetBuilder], Dict[str, str]]:
"""Infer the builder class to build.
Args:
ds_to_build: Dataset argument.
Returns:
builder_cls: The dataset class to download and prepare
kwargs:
"""
# 1st case: Requested dataset is a path to... | 4,266 |
def stop_logging() -> None:
"""
Stop logging output to file
This function will clear the `atomica_file_handler` and close
the last-opened log file. If file logging has not started, this
function will return normally without raising an error
"""
for handler in logger.handlers:
if h... | 4,267 |
def quick_sort(data, start, end, draw_data, time_delay):
"""Quicksort function with a modification that allows for drawing of the
sorted data onto the canvas
Color information:
- rectangles that are swapped are light green,
- to the left and to the right of the pivot in the partitioned list,
... | 4,268 |
def keypoints_to_bbox(keypoints_list, image):
"""Prepare bboxes from keypoints for object tracking.
args:
keypoints_list (np.ndarray): trtpose keypoints list
return:
bboxes (np.ndarray): bbox of (xmin, ymin, width, height)
"""
bboxes = []
img_h, img_w = image.shape[:2]
for ... | 4,269 |
def view():
""" WIP: View admins. """
if current_user.is_admin():
admins = UserMetadata.select().where(UserMetadata.key == 'admin')
postcount = SubPost.select(SubPost.uid, fn.Count(SubPost.pid).alias('post_count')).group_by(SubPost.uid).alias(
'post_count')
commcount = SubPo... | 4,270 |
def seamAnalysis(analysis, img1, img2, mask=None, linktype=None, arguments=dict(), directory='.'):
"""
Perform SIFT regardless of the global change status. If neighbor mask is is constructed, indicating the seams
can be calculated, then mark as not Global.
:param analysis:
:param img1:
:param i... | 4,271 |
def get_market_offers(session, ids, base_market_url=BASE_MARKET_URL):
"""\nMain function for interaction with this library.
\nProvided a sequence of Character Ids, returns a dictionary of offers for each. \
Requires a session which has already authenticated with Urban Rivals.
\nOptional: provide a base ... | 4,272 |
def band_listing(request):
"""A view of all bands."""
bands = Band.objects.all()
return render(request, 'bands/band_listing.html', {'bands': bands}) | 4,273 |
def test_noisy():
"""
tests function to add noise to a colour image.
"""
timage = np.zeros((10, 10, 1), np.uint8)
image = utilities.noisy_image(timage)
assert image.shape == (10, 10, 1) | 4,274 |
def check_mismatched_bracket_type(path: str) -> Optional[BracketErrorType]:
"""
Check for miss matched brackets
:param path: path to file
:return: Type of miss match or None if there is none
"""
file_as_string = utils.read_file(path)
brackets_count = utils.count_brackets(file_as_string)
... | 4,275 |
def create_initiator(cluster: str, headers_inc: str) -> None:
"""Create a Initiator Group"""
print()
show_svm(cluster, headers_inc)
print()
svm_name = input(
"Enter the name of the SVM on which the volume needs to be created:- ")
igroup_name = input(
"Enter the name of th... | 4,276 |
def update(ctx, ticket_id, target, amount, account):
""" Update staking time of a voting ballot.
Changes the stake-lock duration of a voting ticket. Can update full amount
of a ticket or a partial amount. If partial, result is two separate
tickets, putting optional AMOUNT on the new ticket/time-target... | 4,277 |
def get_rank(
day: int = day_idx,
year: int = year
) -> Union[None, Tuple[str]]:
"""
Returns the rank for the current day.
Arguments
---------
day -- The day to get the rank for.
year -- The year to get the rank for.
Returns
-------
The rank for the specified d... | 4,278 |
def _check_flags(sorted_seq_to_filepath):
"""Ensure regional indicators are only in sequences of one or two, and
never mixed."""
for seq, fp in sorted_seq_to_filepath.iteritems():
have_reg = None
for cp in seq:
is_reg = _is_regional_indicator(cp)
if have_reg == None:
have_reg = is_reg
... | 4,279 |
def get_taste(dm):
"""
Get the classification of a matrix defining a tangent vector field of the
form:
| R | t |
| - - - |
| 0 | 0 |
:param dm: input tangent matrix
:return: number from 1 to 6 corresponding to taste. see randomgen_linear_by_taste.
"""
rot... | 4,280 |
def wait_for_sge_jobs(jids, wait_timeout=None, run_timeout=None):
"""
Wait for all sge job ids {jids} to complete before exiting.
Return sge job ids that have been killed by qdel.
If wait_timeout is set, qdel all jobs regardless job status after
{wait_timeout} seconds have passed.
If wait_timeo... | 4,281 |
def _check_removal_required(submission: Submission, cfg: Config) -> Tuple[bool, bool]:
"""
Check whether the submission has to be removed and whether this is reported.
Note that this function returns a Tuple of booleans, where the first
is to signify whether the submission is to be removed and the latt... | 4,282 |
def subjects(request, unique_id,form=None):
"""
Enlists all the subjects of a classroom ,
subjects can be added by admins
"""
classroom = get_object_or_404(Classroom,unique_id=unique_id)
#querysets
members = classroom.members.all()
subjects = Subject.objects.filter(classroom=classroom)
... | 4,283 |
def retrieve_settings(skill_id: str) -> JSONStructure:
"""Retrieves skill's settings by leveraging the mycroft-api skill
Send `skillmanager.list` message and wait for `mycroft.skills.list`
message to appear on the bus.
:param skill_id: Skill ID to retrieve the settings
:type skill_id: str
:ret... | 4,284 |
def make_project(alias='project', root=None, **kwargs):
"""Initialize a project for testing purposes
The initialized project has a few operations and a few jobs that are in
various points in the workflow defined by the project.
"""
init(alias=alias, root=root, template='testing')
project = sig... | 4,285 |
def _get_sensors_data(driver_info):
"""Get sensors data.
:param driver_info: node's driver info
:raises: FailedToGetSensorData when getting the sensor data fails.
:returns: returns a dict of sensor data group by sensor type.
"""
try:
ipmicmd = ipmi_command.Command(bmc=driver_info['addre... | 4,286 |
def dominates(lhs, rhs):
"""Weak strict domination relation: lhs =] rhs and lhs [!= rhs."""
lhs_rhs = try_decide_less(lhs, rhs)
rhs_lhs = try_decide_less(rhs, lhs)
return rhs_lhs is True and lhs_rhs is False | 4,287 |
def complex_to_xy(complex_point):
"""turns complex point (x+yj) into cartesian point [x,y]"""
xy_point = [complex_point.real, complex_point.imag]
return xy_point | 4,288 |
def test_ap_interworking_element_update(dev, apdev):
"""Dynamic Interworking element update"""
bssid = apdev[0]['bssid']
params = hs20_ap_params()
params['hessid'] = bssid
hapd = hostapd.add_ap(apdev[0], params)
dev[0].hs20_enable()
dev[0].scan_for_bss(bssid, freq="2412")
bss = dev[0].g... | 4,289 |
def setup_mock_accessory(controller):
"""Add a bridge accessory to a test controller."""
bridge = Accessories()
accessory = Accessory.create_with_info(
name="Koogeek-LS1-20833F",
manufacturer="Koogeek",
model="LS1",
serial_number="12345",
firmware_revision="1.1",
... | 4,290 |
def match_array_placeholder(loc, term, element):
"""Determine if the JSPEC array placeholder matches the JSON element.
Args:
loc (str): The current location in the JSON
term (JSPECArrayPlaceholder): The JSPEC array placeholder.
element (obj): The Python native object representing a JSON... | 4,291 |
def get_mask_index(timeDict, mask='Spine', use_B=False, noise_th=None):
"""
:param timeDict: timeDict to use
:param mask: options are 'Spine' and 'Dendrite'
:param use_B: Make masksB etc.
:param noise_th: if None will return all mask index if float will return mean noise < then threshold
... | 4,292 |
def coverageSection(*coverItems):
"""Combine multiple coverage items into a single decorator.
Args:
*coverItems ((multiple) :class:`CoverItem`): coverage primitives to be
combined.
Example:
>>> my_coverage = coverage.coverageSection(
... coverage.CoverPoint("x", ...),
... | 4,293 |
def test_masks(dtype_device):
"""test if masks are applied from boundary conditions"""
dtype, device = dtype_device
lattice = Lattice(D2Q9, dtype=dtype, device=device)
flow = Obstacle2D(10, 5, 100, 0.1, lattice, 2)
flow.mask[1,1] = 1
streaming = StandardStreaming(lattice)
simulation = Simula... | 4,294 |
def get_operator_metatypes() -> List[Type[OperatorMetatype]]:
"""
Returns a list of the operator metatypes.
:return: List of operator metatypes .
"""
return list(PT_OPERATOR_METATYPES.registry_dict.values()) | 4,295 |
def gsutil_downloader(
cfg: config.Loader, logger: logging.Logger, uri: str, **kwargs
) -> Generator[Dict[str, Any], Dict[str, Any], None]:
"""
Built-in downloader plugin for public gs:// URIs; registered by setup.cfg entry_points section
TODO: adopt security credentials from runtime environment
""... | 4,296 |
def fnl_fix_first_line(preprocessor: Preprocessor, string: str) -> str:
"""final action to ensures file starts with a non-empty
non-whitespace line (if it is not empty)"""
while string != "":
pos = string.find("\n")
if pos == -1:
if string.isspace():
return preprocessor.replace_string(0, len(string), stri... | 4,297 |
def rf_rasterize(geometry_col, bounds_col, value_col, num_cols_col, num_rows_col):
"""Create a tile where cells in the grid defined by cols, rows, and bounds are filled with the given value."""
jfcn = RFContext.active().lookup('rf_rasterize')
return Column(jfcn(_to_java_column(geometry_col), _to_java_column... | 4,298 |
def make_heatmap(ax, gs, is_sh=False, make_cbar=False):
"""Helper to make a heatmap."""
results = pd.DataFrame.from_dict(gs.cv_results_)
results["params_str"] = results.params.apply(str)
if is_sh:
# SH dataframe: get mean_test_score values for the highest iter
scores_matrix = results.sor... | 4,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.