content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _read_config_file(filename, schema):
"""Read a YAML configuration file."""
# Ignore nonexisting files.
if not os.path.exists(filename):
return None
elif not os.path.isfile(filename):
raise ConfigFileError(
"Invalid configuration. %s exists but is not a file." % filename)... | 45,600 |
def shortest_path_search(start, successors, is_goal):
"""Find the shortest path from start state to a state
such that is_goal(state) is true."""
# your code here
if is_goal(start):
return [start]
explored = set() # set of states we have visited
frontier = [ [start] ] # ordered list of pa... | 45,601 |
def to_tensor(X: Union[np.ndarray, tf.Tensor], **kwargs) -> Optional[tf.Tensor]:
"""
Converts tensor to tf.Tensor
Returns
-------
tf.Tensor conversion.
"""
if X is not None:
if isinstance(X, tf.Tensor):
return X
return tf.constant(X)
return None | 45,602 |
def get_explicit_positions(parsed_str_format):
"""
>>> parsed = parse_str_format("all/{}/is/{2}/position/{except}{this}{0}")
>>> get_explicit_positions(parsed)
{0, 2}
"""
return set(
map(
int,
filter(
lambda x: isinstance(x, str) and str.isnumeric(... | 45,603 |
def get_git_repo(path_to_repo: OptionalPath=None) -> Optional[git.Repo]:
"""
Return a git.Repo object. If path_to_repo is None,
check the environment variable MHEALTH_REPO.
"""
if not path_to_repo:
path_to_repo = os.getenv("MHEALTH_ROOT")
if not path_to_repo:
candidate = Path(__f... | 45,604 |
def msg_parser_disable(id):
"""
Disable a Parser
- Disconnect a Parser from a Channel
CLI API for shell scripts & to be called by S3Method
"""
db = current.db
s3db = current.s3db
table = s3db.msg_parser
record = db(table.id == id).select(table.id, # needed for update_re... | 45,605 |
def fetch(team, event, token):
"""
Fetch and store TBA data for use on dashboard.
:param team: Team to tailor data to.
:param event: Key of event to get data on.
:param token: TBA token to use for fetching data.
"""
# Initialize TBA API
tba = tbapy.TBA(token)
print('Getting Team #{... | 45,606 |
def filter_is(field, target):
"""
Check if a log field is the specified value.
A boolean is returned.
Case-insensitive checks are made.
"""
lowfield = field.lower()
retval = lowfield == target
# print "is:\t<%s>\t<%s>\t" % (field, target), retval
return(retval) | 45,607 |
async def get_server_port(node: Node) -> int:
"""
Returns the port which the WebSocket server is running on
"""
client = node.create_client(GetParameters, "/rosbridge_websocket/get_parameters")
try:
if not client.wait_for_service(5):
raise RuntimeError("GetParameters service not ... | 45,608 |
def search_vac(search_phrase):
"""Get vacancies with search phrase in JSON"""
con = sqlite3.connect("testdb.db")
cur = con.cursor()
sql = 'SELECT * FROM vacancies WHERE json LIKE "%{}%" ORDER BY id DESC LIMIT 100;'.format(search_phrase)
cur.execute(sql)
vac = cur.fetchall()
con.close()
d... | 45,609 |
def test_axis_off_vis_false(pt_line_plt):
"""Check assert_axis_off for case when axis visibility set to False"""
pt_line_plt.ax.xaxis.set_visible(False)
pt_line_plt.ax.yaxis.set_visible(False)
pt_line_plt.assert_axis_off()
plt.close() | 45,610 |
def make_task(task_type, **config_task):
"""
Factory function for Task object.
Parameters
----------
task_type : str
Type of task:
"regression" : Symbolic regression task.
"control" : Episodic reinforcement learning task.
config_task : kwargs
Task-specific argu... | 45,611 |
def detectar_lenguaje(texto, devolver_proba=False):
"""
Identifica el lenguaje en el que está escrito el texto de entrada.
:param texto: Texto de entrada.
:type texto: str
:param devolver_proba: Indica si se retorna el porcentaje de \
confiabilidad del lenguaje identificado. Valor por \
... | 45,612 |
def list_backup_sets(
state, active, inactive, org_uid, include_usernames, format,
):
"""Get information about many devices and their backup sets."""
if inactive:
active = False
columns = ["guid", "userUid"]
df = _get_device_dataframe(state.sdk, columns, active, org_uid)
if include_usern... | 45,613 |
def get_tablenames():
"""get table names from database. """
con = get_db()
cursor = con.cursor()
select_tn_cmd = "SELECT name FROM sqlite_master WHERE type='table';"
tablenames, res = [], cursor.execute(select_tn_cmd).fetchall()
for tn in res:
tablenames += [tn['name']]
return tablen... | 45,614 |
def echo(object, f=sys.stderr) :
"""Print an object is f
If the object has a method Print(), this method is used.
repr(object) is used otherwise
"""
import itk
ss = itk.StringStream()
try :
try:
object.Print(ss.GetStream())
except:
object.Print(ss.GetStream(),Inden... | 45,615 |
def expando_distinct_values(model_class, field_name):
""" Returns all possible values for a specific expando field.
Useful for search forms widgets.
"""
ct = ContentType.objects.get_for_model(model_class)
qs = Expando.objects.filter(content_type=ct, key=field_name)
return qs.distinct().value... | 45,616 |
def oconner(w, r):
"""
Optimistic for low reps. Between Lombardi and Brzycki for high reps.
"""
return w * (1 + r/40) | 45,617 |
def unionPart(* partsList):
"""Finds the union of several partitions"""
mat = part2graph(util.concat(* partsList))
parts = graph.connectedComponents(mat.keys(), lambda x: mat[x].keys())
# remove parition ids from partitioning
parts = map(lambda part: filter(lambda x: type(x) != int, part), parts)
... | 45,618 |
def add_upper_log_level(logger, method_name, event_dict):
"""
Add the log level to the event dict.
"""
event_dict["level"] = method_name.upper()
return event_dict | 45,619 |
def tanh_cl(a):
""" Hyperbolic tangent of GPUArray elements.
Parameters
----------
a : gpuarray
GPUArray with elements to be operated on.
Returns
-------
gpuarray
tanh(GPUArray)
Examples
--------
>>> a = tanh_cl(give_cl(queue, [0, pi/4]))
[ 0., 0.6557942]... | 45,620 |
def CleanGitWorkingDir(directory, reset=False, path=None, logger=None):
"""Clean all or part of an existing git checkout.
Args:
directory: Directory where the git repo is currently checked out
reset: If True, also reset the working directory to HEAD
path: path to clean, relative to the repo direc... | 45,621 |
def get_logger(log_file=None):
"""
Initialize global logger and return it.
:param log_file: log to this file, or to standard output if None
:return: created logger
"""
formatter = logging.Formatter(
fmt='%(asctime)s p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',
... | 45,622 |
def register(bl_info):
"""Registering the operators in this module"""
# safer failure in case of issue loading module
if updater.error:
print("Exiting updater registration, " + updater.error)
return
updater.clear_state() # clear internal vars, avoids reloading oddities
# confirm your updater "engine" (Github ... | 45,623 |
def main(config):
"""Executes cbs.regionaal.flow in DaskExecutor.
"""
""" Trigger in Prefect, load column description first and when finished only then load the data.
"""
flow.set_reference_tasks([regionaal_column_description])
# executor = DaskExecutor(n_workers=8)
flow.run(
# exe... | 45,624 |
def local_execute_from_command_line(argv=None, **sandbox_overrides):
"""Execute commands in the local sandbox"""
return _execute_from_command_line(sandbox.LOCAL, argv or sys.argv, **sandbox_overrides) | 45,625 |
def run_draw_signal(plot):
"""
Run unit tests on S5Pplot::draw_signal
"""
print('Run unit tests on S5Pplot::draw_signal')
msm = get_test_data(error=.1)
msm_ref = get_test_data(error=0.025)
nlines = 40 # 35
fig_info_in = FIGinfo('right')
for ii in range(nlines):
fig_info_in.... | 45,626 |
def process_model(n):
"""Insert description here"""
#####################################
# Model identifiers
tags, pdb_path = PDBs_Info[n]
mutant, group, pdb_name = tags
model_tags = Tags(mutant = mutant, group = group, pdb_name = pdb_name)
session.add(model_tags)
#####################... | 45,627 |
def sweep_depth(sketch_class):
"""Return a table of shape (len(depth_values), 2) counting number of times the sketch correctly found the heaviest key."""
# 1st column is for the median, 2nd is for the sign alignment estimator
print(sketch_class.__name__)
num_success = np.zeros((len(depth_values), 2))
max_dept... | 45,628 |
def main():
"""Main execution"""
AzureRMBatchApplication() | 45,629 |
def plot_ensemble_results(model, ensemble, expts = None,
style='errorbars',
show_legend = True, loc = 'upper left',
plot_data = True, plot_trajectories = True):
"""
Plot the fits to the given experiments over an ensemble.
Note ... | 45,630 |
def generate_synthetic_gaps(
mean: np.ndarray,
covariance: np.ndarray,
size: int,
chunk_size: int,
threshold: int,
seed: int
) -> np.ndarray:
"""Return numpy array with the coordinates of gaps in matrix mask.
Parameters
------------------
mean: np.ndarray,
Mean of biolog... | 45,631 |
def get_args():
"""Get command line args from the user.
"""
parser = argparse.ArgumentParser(
description='arguments for interacting with vsphere')
parser.add_argument('-s', '--host',
required=True,
action='store',
help='vS... | 45,632 |
def main_atexit(log_handler, db):
"""Disconnect UI from log_handler and close db.
Used with atexit to ensure database connection is closed during abnormal
program termination.
Args:
log_handler: .ui_top.UILogginHandler.
db: .dbdrv.DBDriver.
"""
# Does nothing on a normal exit b... | 45,633 |
def ulmfit_document_classifier(*, model_type, pretrained_encoder_weights, num_classes,
spm_model_args=None, fixed_seq_len=None,
with_batch_normalization=False, activation='softmax'):
"""
Document classification head as per the ULMFiT paper:
- ... | 45,634 |
def test_merge_with_geometries() -> None:
"""Geometries are added to Statistics."""
statistics: pd.DataFrame = pd.DataFrame(
{"small_area": [111], "very_important_data": [42]},
)
dublin_geometries: gpd.GeoDataFrame = gpd.GeoDataFrame(
{"small_area": [111], "geometry": [Point((0, 0))]},
... | 45,635 |
def is_zero_dict( dict ):
"""
Identifies empty feature vectors
"""
has_any_features = False
for key in dict:
has_any_features = has_any_features or dict[key]
return not has_any_features | 45,636 |
def kill():
"""
Terminate containers as fast as possible, might cause corrupted files in the /data directory
"""
local('{default_env} docker-compose kill'.format(default_env=default_env)) | 45,637 |
def register_scale(
convert_to: Dict[str, Callable] = None, convert_from: Dict[str, Callable] = None
) -> Callable[[Callable], Callable]:
"""Decorator used to register new time scales
The scale name is read from the .scale attribute of the Time class.
Args:
convert_to: Functions used to con... | 45,638 |
def get_top_down_ground_truth_static_ego(env_id, start_idx, img_w, img_h, map_w, map_h):
"""
Returns the ground-truth label oriented in the global map frame
:param env_id:
:param start_idx:
:param img_w:
:param img_h:
:param map_w:
:param map_h:
:return:
"""
path = load_path(... | 45,639 |
def test_stratify_compartments(strata, proportions, to_stratify, expected_names, expected_values):
"""
Ensure that `stratify_compartments` splits up compartment names and values correctly.
"""
model = StratifiedModel(**_get_model_kwargs())
model.stratify_compartments("test", strata, proportions, to_... | 45,640 |
def read_project(config_path, timesheet_path=None, replicon_options=None):
"""
Read a project dictionary from a YAML file located at the path ``config_path``, and read a project timesheet from the path ``timesheet_path``.
Parse these files, check them, and, if successful, return a corresponding Project inst... | 45,641 |
def _parse_query_location(
location: Union[Tuple[float, float], Point, MultiPoint, Polygon]
) -> str:
"""Convert given locations into WKT representations.
Args:
location (QueryLocation): Provided location definition.
Raises:
ValueError: Raised for when unable to parse location.
Re... | 45,642 |
def test_register_task_decl_taskcls1(collector, task_decl):
"""Test handling task class issues : failed import no such module.
"""
tb = {}
task_decl.task = 'exopy.tasks.foo:Task'
task_decl.register(collector, tb)
assert 'exopy.Task' in tb and 'import' in tb['exopy.Task'] | 45,643 |
def getuniqueitems(userchoices):
"""return a list of unique items given a bunch of userchoices"""
items = []
for userchoice in userchoices:
if userchoice.item not in items:
items.append(userchoice.item)
return items | 45,644 |
def test_hasher_3_case_3():
"""Test hasher_3 case_3"""
case_dict = test_hasher_3()
urn = case_dict.get("final_urn")
assert case_dict.get("urn_hash") == ash_hash(urn) | 45,645 |
def config(ctx, verbose, provider, size, path, example):
"""
Uses Terraform to create a full Numerai Compute cluster in AWS.
Prompts for your AWS and Numerai API keys on first run, caches them in $HOME/.numerai.
At the end of running, this will output a config file 'nodes.json'.
"""
ctx.ensure_... | 45,646 |
def _as_array(arr, dtype=None):
"""Convert an object to a numerical NumPy array.
Avoid a copy if possible.
"""
if arr is None:
return None
if isinstance(arr, np.ndarray) and dtype is None:
return arr
if isinstance(arr, integer_types + (float,)):
arr = [arr]
out = np.a... | 45,647 |
def _prepare_fixed_ips(client_manager, parsed_args):
"""Fix and properly format fixed_ip option.
Appropriately convert any subnet names to their respective ids.
Convert fixed_ips in parsed args to be in valid dictionary format:
{'subnet': 'foo'}.
"""
client = client_manager.network
ips = []... | 45,648 |
def stitch_together_target_regions(cluster,
flanking=500,
logger=None, circular=False,
revcomp=False):
"""
given a single LociCluster object containing Locus objects (usually)
of length 3 (16,5,and 23 rR... | 45,649 |
def setComponentProperties(properties):
"""Sets the global script component properties"""
global scriptComponentProperties
scriptComponentProperties = properties
# done setting global script config | 45,650 |
def add_region():
""" add a region page function """
# init variables
entry = Region() # creates a model.py instance, instance only has a name right now
error_msg = {}
form_is_valid = True
country_list = Country.query.all()
if request.method == 'GET':
return render_template('regio... | 45,651 |
def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
This function was excerpted from Django project,
modifications have been applied.
The original license is as follows:
```
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistri... | 45,652 |
def test_empty_network():
"""Test creation of empty network."""
network = Network()
assert network is not None | 45,653 |
def initialize_conditions(segment):
"""Sets the specified conditions which are given for the segment type.
Assumptions:
Constant speed, constant descent angle. However, this follows a 2000 meter segment. This is a certification maneuver standard. The last point for the noise measurement is 50 feet.
So... | 45,654 |
def platform_darwin(monkeypatch):
"""Patch platform.system to always return "Darwin"."""
monkeypatch.setattr("platform.system", lambda: "Darwin") | 45,655 |
def remove_component_from_set(name, component_set):
"""
Will remove the component with the specified name from the set with components,
regardless of the version.
:type name: str
:type component_set: set
"""
for component in component_set:
if component.name == name:
component_set.discard(compone... | 45,656 |
def get_host(hostname):
""" Get information about backups for a particular host """
print(f"\nSearching for host '{ hostname }'...\n")
backuppc_data = get_backup_data()
for host in backuppc_data:
if host['hostname'] == hostname:
return host | 45,657 |
def gazebo_get_gravity() -> Vector3:
"""
Function to get the current gravity vector for gazebo.
:return: the gravity vector.
:rtype: Vector3
"""
rospy.wait_for_service("/gazebo/get_physics_properties")
client_get_physics = rospy.ServiceProxy("/gazebo/get_physics_properties", GetPhysicsProp... | 45,658 |
def make_mock_device():
"""
Create a mock host device
"""
def _make_mock_device(xml_def):
mocked_conn = virt.libvirt.openAuth.return_value
if not isinstance(mocked_conn.nodeDeviceLookupByName, MappedResultMock):
mocked_conn.nodeDeviceLookupByName = MappedResultMock()
... | 45,659 |
def load_file(file_name: str, mode: str = "rb") -> Union[str, bytes]:
"""Loads files from resources."""
file_path = get_resource_path(file_name)
with open(file_path, mode) as file:
return file.read() | 45,660 |
def check_folder():
"""Check folder."""
if not os.path.exists(PATH):
os.makedirs(PATH)
if not os.path.exists(PATH_PLAYERS):
os.makedirs(PATH_PLAYERS) | 45,661 |
def path_graph(n, create_using=None):
"""Returns the Path graph `P_n` of linearly connected nodes.
Parameters
----------
n : int or iterable
If an integer, node labels are 0 to n with center 0.
If an iterable of nodes, the center is the first.
create_using : NetworkX graph construct... | 45,662 |
def numpy_shift(array: np.ndarray, periods: int, axis: int, fill_value=np.nan) -> np.ndarray:
"""
numpy implementation for validation
"""
assert axis in range(-array.ndim, array.ndim)
copy_src_indices = [slice(None)] * array.ndim
copy_dst_indices = [slice(None)] * array.ndim
fill_indices = ... | 45,663 |
def draw_rect(im, cords, color = None):
"""Draw the rectangle on the image
Parameters
----------
im : numpy.ndarray
numpy image
cords: numpy.ndarray
Numpy array containing bounding boxes of shape `N X 4` where N is the
number of bounding boxes and the boundin... | 45,664 |
def pcieinfo(check, verbose):
"""Show Device PCIe Info"""
cmd = "sudo pcieutil pcie-show"
if check:
cmd = "sudo pcieutil pcie-check"
clicommon.run_command(cmd, display_cmd=verbose) | 45,665 |
def low_pass_edge_filter_nx(G,pct,attr='weight'):
"""
Remove edges with attr above therehold
Inputs:
-------
G : networkx, directed or undirected
pct: percentile threshold, float, between 0 and 1
attr: str, edge attribute (deftaul 'weight')
"""
weights = [w for (a,b,w) in G.edge... | 45,666 |
def _setup_entities(hass, dev_ids: List[str]):
"""Set up CAME light device."""
manager = hass.data[DOMAIN][CONF_MANAGER] # type: CameManager
entities = []
for dev_id in dev_ids:
device = manager.get_device_by_id(dev_id)
if device is None:
continue
entities.append(Cam... | 45,667 |
def test_backend_get_power_output_enabled() -> None:
"""Test that we can read the enable status of a PowerOutput."""
device = MockUSBPowerBoardDevice("SERIAL0")
backend = SRV4PowerBoardHardwareBackend(device)
for i in range(0, 6):
assert not backend.get_power_output_enabled(i)
with pytest.... | 45,668 |
def image_url_salt():
"""Helper function that generates salt to append to an image URL to prevent browser caches from loading
old images"""
return binascii.b2a_hex(os.urandom(4)).decode('us-ascii') | 45,669 |
def solveNQueens(n):
"""
:type n: int
:rtype: List[List[str]]
"""
pos = [()]*n
result = []
solveNQeensUtil(n, 0, pos, result)
for r in result:
print(r) | 45,670 |
def test_add_equivalent(initialized_tasks_db):
"""Test whether tasks.get() using id returned from tasks.add() works."""
task = Task("Learn Pytest", "Florian", True)
task_id = tasks.add(task)
task_from_db = tasks.get(task_id)
assert equivalent(task_from_db, task) | 45,671 |
def check_doa(geometry, doa, online=False):
"""
Check value of the DoA
"""
if not online:
doas = [doa]
else:
doas = doa
for doa in doas:
if doa < 0:
return False
if geometry == "linear" and doa > 180:
return False
if geometry == "ci... | 45,672 |
def reconnect(force=False, **kwargs): # pylint: disable=unused-argument
"""
Reconnect the NAPALM proxy when the connection
is dropped by the network device.
The connection can be forced to be restarted
using the ``force`` argument.
.. note::
This function can be used only when running... | 45,673 |
def ask_user_for_half_life(access_key):
"""Ask the user for a half life value"""
day_choice = "One day"
hour_choice = "One hour"
week_choice = "One week"
forever_choice = "forever"
while True:
choice = ask_for_choice_or_new("What half life do you want for this key? ({0})".format(access_... | 45,674 |
def _trim_orderbook_list(arr: list, ascending: bool, limit_len: int = 50) -> list:
"""trims prices up to 4 digits precision"""
first_price = arr[0][0]
if first_price < 0.1:
unit = 1e-5
elif first_price < 1:
unit = 1e-4
elif first_price < 10:
unit = 1e-3
elif first_price <... | 45,675 |
def process_piece(piece, op='=', quant=False, **kwargs):
"""
Make a single search obj and value
"""
from corpkit.process import make_name_to_query_dict
if op not in piece:
return False, False
translator = make_name_to_query_dict()
target, criteria = piece.split(op, 1)
criteria =... | 45,676 |
def test_auto_contrast_one_channel_c(plot=False):
"""
Test AutoContrast C implementation with one channel
"""
logger.info("Test AutoContrast C implementation With One Channel Images")
# AutoContrast Images
data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
data_set = data... | 45,677 |
def normal220(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2):
"""
for source and destination id generation
"""
"""
for type of banking work,label of fraud and type of fraud
"""
idvariz=random.choice(bb1)
idgirande=r... | 45,678 |
def sigma_voigt(dgm_sigmaD,dgm_gammaL):
"""compute sigma of the Voigt profile
Args:
dgm_sigmaD: DIT grid matrix for sigmaD
dgm_gammaL: DIT grid matrix for gammaL
Returns:
sigma
"""
fac=2.*np.sqrt(2.*np.log(2.0))
fdgm_gammaL=jnp.min(dgm_gammaL,axis=1)*2.0
fdgm_sigm... | 45,679 |
def zigzag2(i, curr=.45, upper=.48, lower=.13):
"""
Generalized version of the zig-zag function.
Returns points oscillating between two bounds
linearly.
"""
if abs(i) <= (upper-curr):
return curr + i
else:
i = i - (upper-curr)
i = i%(2*(upper-lower))
if i < (u... | 45,680 |
def background_task2():
""" example background task1 """
logger.info('second task') | 45,681 |
def get_len_of_range(start, stop, step):
"""Get the length of a (start, stop, step) range."""
n = 0
if start < stop:
n = ((stop - start - 1) // step + 1);
return n | 45,682 |
def generate_tap(laygen, objectname_pfix, placement_grid, routing_grid_m1m2_thick, devname_tap_boundary, devname_tap_body,
m=1, origin=np.array([0,0]), transform='R0'):
"""generate a tap primitive"""
pg = placement_grid
rg_m1m2_thick = routing_grid_m1m2_thick
# placement
itapbl0 = ... | 45,683 |
def multiply(
x1: Union[ivy.Array, ivy.NativeArray],
x2: Union[ivy.Array, ivy.NativeArray],
out: Optional[Union[ivy.Array, ivy.NativeArray]] = None,
) -> ivy.Array:
"""Calculates the product for each element ``x1_i`` of the input array ``x1`` with
the respective element ``x2_i`` of the input array `... | 45,684 |
def discriminateEvents(events, threshold):
"""
Discriminate triggers when different kind of events are on the same channel.
A time threshold is used to determine if two events are from the same trial.
Parameters
----------
events : instance of pandas.core.DataFrame
Dataframe containing ... | 45,685 |
def whiten(sig, win):
"""Whiten signal, modified from MSNoise."""
npts = len(sig)
nfreq = int(npts // 2 + 1)
assert (len(win) == nfreq)
# fsr = npts / sr
fsig = fft(sig)
# hl = nfreq // 2
half = fsig[: nfreq]
half = win * phase(half)
fsig[: nfreq] = half
fsig[-nfreq + 1:] ... | 45,686 |
def create_slice(request):
"""
Create a slice based on a pattern. User has to be the "production_request" owner. Steps should contain dictionary of step
names which should be copied from the pattern slice as well as modified fields, e.g. {'Simul':{'container_name':'some.container.name'}}
:param produ... | 45,687 |
def get_reverse_charge_recoverable_total(filters):
"""Returns the sum of the total of each Purchase invoice made with recoverable reverse charge."""
query_filters = get_filters(filters)
query_filters.append(['reverse_charge', '=', 'Y'])
query_filters.append(['recoverable_reverse_charge', '>', '0'])
query_filters.a... | 45,688 |
def load_data(url_bam):
"""Load ``MetaData`` from the given ``url_bam``."""
if url_bam.scheme != "file":
raise ExcovisException("Can only load file resources at the moment")
with pysam.AlignmentFile(url_bam.path, "rb") as samfile:
read_groups = samfile.header.as_dict().get("RG", [])
... | 45,689 |
def generate_room_number():
"""
Generates a room number composed of 10 digits.
"""
return "".join(random.sample(string.digits, 10)) | 45,690 |
def copy_package(pkg, from_dist, to_dist):
"""Copy a specific version of package (APTSourcePackage) from
one distribution to another."""
call('-A', 'source', 'copysrc', to_dist, from_dist, pkg.name, str(pkg.version)) | 45,691 |
def is_noiseless(model: Model) -> bool:
"""Check if a given (single-task) botorch model is noiseless"""
if isinstance(model, ModelListGP):
raise ModelError(
"Checking for noisless models only applies to sub-models of ModelListGP"
)
return model.__class__ in NOISELESS_MODELS | 45,692 |
def random_sampling_normalized_variance(sampling_percentages, indepvars, depvars, depvar_names,
n_sample_iterations=1, verbose=True, npts_bandwidth=25, min_bandwidth=None,
max_bandwidth=None, bandwidth_values=None, scale_unit_box=True, n_th... | 45,693 |
def classify_data(X_train, Y_train, X_test):
"""Develop and train your very own variational quantum classifier.
Use the provided training data to train your classifier. The code you write
for this challenge should be completely contained within this function
between the # QHACK # comment markers. The nu... | 45,694 |
def preprocess_embedding(z):
"""Pre-process embedding.
Center and scale embedding to be between -.5, and .5.
Arguments:
z: A 2D NumPy array.
shape=(n_concept, n_dim)
Returns:
z_p: A pre-processed embedding.
"""
# Center embedding.
z_p = z - np.mean(z, axis=0, ... | 45,695 |
def get_folders_from_path(path):
"""
Gets a list of sub folders in the given path
:param path: str
:return: list<str>
"""
folders = list()
while True:
path, folder = os.path.split(path)
if folder != '':
folders.append(folder)
else:
if path != ... | 45,696 |
def firewall_flush(iface):
"""Remove all rules associated to ``iface``."""
fw = Firewall()
for _, target, _, dest, veth in fw._list():
if veth == iface:
fw.delete(dest, iface, target) | 45,697 |
def T_from_Ts(Ts,P,qt,es_formula=es_default):
""" Given theta_e solves implicitly for the temperature at some other pressure,
so that theta_e(T,P,qt) = Te
>>> T_from_Tl(282.75436951,90000,20.e-3)
290.00
"""
def zero(T,Ts,P,qt):
return np.abs(Ts-get_theta_s(T,P,qt,es_formula))
return optim... | 45,698 |
def _get_cli_parser():
"""
mideu argparse parser create
:return: parser
"""
parser = argparse.ArgumentParser(
description="MasterCard IPM file formatter ({version})".format(
version=_version.get_versions()['version'])
)
parser.add_argument("--version", action="version",
... | 45,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.