content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calc_info_frames(site_results_filtered, remove_multiple=None):
"""Return the info frames for the input."""
dat, conf_both, conf_any = get_pipeline_stats(site_results_filtered, log=False)
df_all = get_conf_dfs(conf_any)
if remove_multiple:
url_by_leak = df_all.groupby(["browser", "url"])[["me... | 5,303,900 |
def _cleaner( vbo ):
"""Construct a mapped-array cleaner function to unmap vbo.target"""
def clean( ref ):
try:
_cleaners.pop( vbo )
except Exception as err:
pass
else:
vbo.implementation.glUnmapBuffer( vbo.target )
return clean | 5,303,901 |
def copy_file_to_blob(account_name,sas_token,container_name,
local_path,remote_path):
"""
Copies a local file to blob storage
"""
blob_service_client = BlobServiceClient(account_url=account_name_to_url(account_name),
credential=sas_token... | 5,303,902 |
def winrate_match(timebox, size, map_category):
""" Returns civs with winrate data based on matches. """
sql = QUERIES["win_rates_match"].format(*timebox, filters(map_category, size))
civs = CivDict(WinrateCivilization, size, map_category, "match")
bottom_civs = CivDict(BottomWinrateCivilization, size, ... | 5,303,903 |
def powerLaw(t, m, a, b):
"""
Model for the shower dominated part of a ratescan
"""
return m*np.power(t, a)+b | 5,303,904 |
def reddened_spectra(name='phoenix_m',overwrite=True):
"""Generate a SpecModel of spectra, with reddening."""
m = model.SpecModel.read_model(name)
m0 = model.append_parameter(m,'A_V',0.0)
for av in [0.3,0.6,0.9,1.2,1.5,1.8,2.1,2.4,2.7,3.0]:
mx = m.copy()
mx = model.append_parameter(m,... | 5,303,905 |
def test_connected(spec, config):
"""Tests that the generated grapיh is connected"""
flow = planner.plan(1, spec, **config)
connected_set = set()
added = True
while added:
added = False
for pipeline_id, pipeline in flow:
pipeline_id = './' + pipeline_id
if pip... | 5,303,906 |
def update_unified_dataset(
session: Session, project: SchemaMappingProject
) -> Operation:
"""Apply changes to the unified dataset and wait for the operation to complete
Args:
project: Tamr Schema Mapping project
"""
unified_dataset = unified.from_project(session, project)
op = unified... | 5,303,907 |
def register(config_file:Path = '.config/config.ini', force:bool = False):
"""
register any new data elements, run with --force to regeister existing data elements
"""
env = DataIntakeEnv(config_file)
if force:
if input(
"!!! WARNING --force is a DESTRUCTIVE action, system in... | 5,303,908 |
def make_v_spacer() -> QSpacerItem:
"""Make vertical QSpacerItem."""
widget = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Expanding)
return widget | 5,303,909 |
def combine_measurements(values):
"""Combines a np.array of measurements into one ufloat"""
return ufloat(mean(values), stdDevOfMean(values)) | 5,303,910 |
def rename_guided(expr, resolution_guide):
"""
resolution_guide is a dictionary whose keys are expressions
and values are tuples (previous_pred, new_pred) that guide
the renaming.
"""
replacements = resolution_guide.get(expr, [])
for prev_pred, new_pred in replacements:
expr = expr.r... | 5,303,911 |
def addEdges(node, action, all_nodes, nodes):
"""
recursivlely add edged to a node
"""
for prod in node.model.producers:
name = "%s-%s" % (prod.key, action)
edge = all_nodes.get(name)
if edge:
addEdges(edge, action, all_nodes, nodes)
node.addEdge(edge)
... | 5,303,912 |
def get_base_required_fields_uframe():
""" Get required fields for base asset in uframe.
"""
base_required_fields = [
'assetId',
'assetType',
'@class',
'dataSource'
'de... | 5,303,913 |
def threshold_hard(var):
"""
Threshold the entries of a vector using the hard threshold.
Parameters
----------
var : dict
Local variables used in the threshold operation.
Notes
-----
This threshold operation works "in-line" on the variables in `var`. Hence,
this function do... | 5,303,914 |
def test_issue76():
"""Test resolution of #76"""
ket_0 = BasisKet(0, hs=0)
ket_1 = BasisKet(1, hs=0)
bra_0 = ket_0.dag()
bra_1 = ket_1.dag()
sig_10 = LocalSigma(1, 0, hs=0)
sig_01 = LocalSigma(0, 1, hs=0)
sig_11 = LocalSigma(1, 1, hs=0)
P0 = LocalProjector(0, hs=0)
P1 = LocalProj... | 5,303,915 |
def test_close_alert(mocker):
"""
Given:
- An app client object
- Alert-id = 1234
When:
- Calling function close_alert
Then:
- Ensure the return data is correct
"""
mocker.patch('CommonServerPython.get_demisto_version', return_value={"version": "6.2.0"})
mock_... | 5,303,916 |
def get_comparative_forms(tokens):
"""Identify, color and count comparatives and superlatives"""
# find comp. forms of adjectives
comparatives = [t for t in tokens if t.full_pos in ['ADJA', 'ADJD'] and t.mo.comp == 'Comp']
superlatives = [t for t in tokens if t.full_pos in ['ADJA', 'ADJD'] and t.mo... | 5,303,917 |
def code_phase_difference(dset: "Dataset") -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""Calculate code-phase difference based on code and phase observations
Args:
dset: Dataset
Returns:
Tuple with code-phase difference for frequency 1 and 2 in [m]. Each code-phase difference is saved in... | 5,303,918 |
def assert_natural(n, m = 1):
"""
Assert that n is of type int and is greater than m.
"""
message = '{n} is not a natural number.'.format(n=n)
assert (n % 1 == 0) and (n >= m), message | 5,303,919 |
def fit_hypsometric_bins_poly(hypsometric_bins: pd.DataFrame, value_column: str = "value", degree: int = 3,
iterations: int = 1, count_threshold: Optional[int] = None) -> pd.Series:
"""
Fit a polynomial to the hypsometric bins.
:param hypsometric_bins: Bins where nans will be ... | 5,303,920 |
def get_nvidia_model(summary=True):
"""
Get the keras Model corresponding to the NVIDIA architecture described in:
Bojarski, Mariusz, et al. "End to end learning for self-driving cars."
The paper describes the network architecture but doesn't go into details for some aspects.
Input normalization, a... | 5,303,921 |
def test_toc_latex_funcs_(cli: CliRunner, temp_with_override, file_regression):
"""Testing individaul functions used in latex"""
from jupyter_book.directive.toc import (
has_toc_yaml,
process_toc_dict,
handle_toc_header,
)
subnode = nodes.bullet_list().deepcopy()
globaldict ... | 5,303,922 |
def templateXcorr(datastream, template):
"""
Normalized cross correlation of short template trace against longer data stream
Based off matlab function coralTemplateXcorr.m by Justin Sweet
Args:
datastream: obspy trace of longer time period to search for template matches
template: obspy ... | 5,303,923 |
def _load_dates():
"""Return a dict with the dates from the start_date to the current date.
Returns
-------
dates : dict
Dictionary containing dates and indicies.
"""
dates = {}
end_date = datetime.datetime.now()
curr_date = datetime.datetime(2020, 1, 1)
count... | 5,303,924 |
def _has_arg(fn, arg_name):
"""Returns True if `arg_name` might be a valid parameter for `fn`.
Specifically, this means that `fn` either has a parameter named
`arg_name`, or has a `**kwargs` parameter.
Args:
fn: The function to check.
arg_name: The name fo the parameter.
Returns:
Whether `arg_n... | 5,303,925 |
def logout(request):
"""
Allows a non-SAML 2.0 URL to log out the user and
returns a standard logged-out page. (SalesForce and others use this method,
though it's technically not SAML 2.0).
"""
auth.logout(request)
tv = {}
return render('saml2idp/logged_out.html', tv) | 5,303,926 |
def log_syscall(trace_id, syscall, err=None):
"""
Logs the result of a system call.
"""
name, args, ret = syscall
if err is None:
if SHOW_SYSCALLS:
print "trace", str(trace_id) + ":", shorten_syscall(syscall)
elif isinstance(err, trace_ordering.SyscallDontCare):
if SHOW_SYSCALLS and not SU... | 5,303,927 |
def load(path=None):
"""set the YML File."""
try:
global CONF_FILE
CONF_FILE = yaml.load(open(path, 'r'))
except:
print(traceback.print_exc()) | 5,303,928 |
def auto_norm(data_set):
"""
Get the minimum values of each column
and place in min_vals. max_vals, too.
data_set.min(0) allows you to take the minimums
from the columns, not the rows.
Then calculate the range of possible
values seen in our data.
To get the normalized values,
you sub... | 5,303,929 |
def middleware(type: MiddlewareType) -> Callable[[CoroFunc[Any]], Middleware]:
"""
A decorator that returns a :class:`~subway.objects.Middleware` object.
Parameters
----------
type: :class:`~subway.objects.MiddlewareType`
The type of middleware to register the middleware with.
"""
d... | 5,303,930 |
def add_sorting_info_to_spike_info(original_spike_info, sorted_spike_info, tsne_filename=None, save_to_file=None):
"""
Adds the information in a spike_info dataframe that results after manual sorting (through a t-sne for example)
into the main spike_info. The original_spike_info is the large spike info with... | 5,303,931 |
def test_text_classification(
tmp_path, pipeline_dict, trainer_dict, train_valid_dataset
):
"""Apart from a well specified training, this also tests the vocab creation!"""
random.seed(42)
np.random.seed(422)
torch.manual_seed(4222)
if torch.cuda.is_available():
torch.cuda.manual_seed_al... | 5,303,932 |
def XXX(self, s):
"""
:type s: str
:rtype: int
"""
left, right = 0, 0
while right < len(s):
right += 1
if len(set(s[left:right])) != right-left:
left += 1
return right-left | 5,303,933 |
def people():
"""
View root page function that returns the index page and its data
"""
posts = Post.query.filter_by(category="People").all()
form = SubscriberForm()
if form.validate_on_submit():
email = form.email.data
new_subscriber=Subscriber(email=email)
new_subscribe... | 5,303,934 |
def networkDrawSVG(request, networkKey):
"""
A view called when a user wants to draw the potential energy surface for
a given Network in SVG format.
"""
networkModel = get_object_or_404(Network, pk=networkKey)
networkModel.load()
# Run CanTherm! This may take some time...
networ... | 5,303,935 |
def transform_dict_to_count_df(item_dict):
"""Given a dictionary, where each element of the dictionary is a list,
return the data frame with columns all the elements that occur in any of
the lists (union of the lists) and rows the keys of the dictionary. Each
entry is the number of times that the item o... | 5,303,936 |
def parse_cmscan_tblout(filename):
"""
SNORA74 RF00090 URS00007E391B_9796 - cm 103 201 1 99 + 5' 2 0.49 0.0 97.9 3.2e-26 ! Small nucleolar RNA SNORA74
"""
data = defaultdict(list)
with open(filename, 'r') as f:
for line in f:
... | 5,303,937 |
def p_indented_scomma_list_term(p):
"""indented_scomma_list : INDENT comma_strings DEDENT
"""
p[0] = p[2] | 5,303,938 |
def test_correct_argument_values_own3():
"""
Testing that the input values are valid
Test 3: too many instances of own specified mean/sd
"""
with pytest.raises(ValueError):
std.stdizer(np_data, method="own", method_args=[[1,2],[1,2],[3,2],[8,9],[8,9],[12,12],[3,4]]) | 5,303,939 |
def main(filename):
"""Extract a Google-style docstring from an IUI json file.
This script assumes that the function being called conforms to the InVEST
API: the function has a single parameter, a dictionary of string
argument names mapping to some value. Based on the IUI json dictionary
provided,... | 5,303,940 |
def himmelblauConstraintOne(solution):
"""First restriction
Args:
solution (Solution): Candidate solution
Returns:
bool: True if it meets the constraint, False otherwise
"""
return (26 - (solution[0] - 5) ** 2 - solution[1] ** 2) >= 0 | 5,303,941 |
def test_image_pcal1_results():
"""
Fill the model column using a start-model and an niter=0 with the savemodel
parameter. Important params:
(startmodel='foo.model', niter=0, savemodel='modelcolumn')
"""
targ = TARGETS['G28539']
spw = SPWS['nh3_11']
test_path = 'test_imaging/test_sel... | 5,303,942 |
def patch_try_disk(return_value):
"""
Mocks the InsightsUploadConf.try_disk method so it returns the given parsed file contents.
"""
def decorator(old_function):
patcher = patch("insights.client.collection_rules.InsightsUploadConf.try_disk", return_value=return_value)
return patcher(old_... | 5,303,943 |
def lyric_wikia_capitalize(string, noupper = True):
"""
lyrics.wikia.com page name rules:
- Uppercase All Words
- No all-uppercase WORDS allowed in song titles (but in artist names)
- Keep StrANgeLy cased words
See http://lyrics.wikia.com/wiki/LyricWiki:Page_Names
... | 5,303,944 |
def create_ip_list(addr0, n_addrs):
"""Creates list of IP multicast subscription addresses.
Args:
addr0 (str): first IP address in the list.
n_addrs (int): number of consecutive IP addresses for subscription.
Returns:
addr_list (list): list of IP addresses for subscription.
"""... | 5,303,945 |
def _classify_samples(indexfile, ssparser):
"""Given an ssparser object, go through all samples and decide sample types."""
sample_table = dict()
index_dict_tenX = parse_10X_indexes(indexfile['tenX'])
index_dict_smartseq = parse_smartseq_indexes(indexfile['smartseq'])
for sample in ssparser.data:
... | 5,303,946 |
def debounce_failures(failed_builds, current_builds_successful, build_db):
"""Using trigger information in build_db, make sure we don't double-fire."""
@contextmanager
def save_build_failures(master_url, builder, buildnum, section_hash,
unsatisfied):
yield
build_db.masters[maste... | 5,303,947 |
def get_common_incident_details(static_attributes: dict, editable_attributes: dict, args) -> dict:
"""
Parses the needed incident details into context paths
:param static_attributes: The static attributes of the incident
:param editable_attributes: The editable attributes of the incident
:param args... | 5,303,948 |
def win_prob_to_odds(prob, odds_style="a"):
"""
:param prob: Float. Implied winning % of a given wager
:param odds_style: Integer (American), Float(Decimal), String or Fraction Class (Fractional)
:return: The stated odds of a bet in a given style
"""
try:
if odds_style.lower() == "americ... | 5,303,949 |
def from_pil(pil_image):
"""
Construct Image from supplied PIL image object.
:param pil_image: PIL image object
:type pil_image: PIL.Image.Image
:raises RuntimeError: If the PIL Image provided is not in a recognized
mode.
:returns: New Image instance using the given image's pixels.
:r... | 5,303,950 |
def cxBlend(var1, var2, alpha=0.5):
"""Executes a blend crossover that modify in-place the input individuals.
The blend crossover expects :term:`sequence` individuals of floating point
numbers.
:param var1: The first variable participating in the crossover.
:param var2: The second variable particip... | 5,303,951 |
def CheckForBlacklistedCommand(args, blacklist, warn=True, die=False):
"""Blacklist certain subcommands, and warn the user.
Args:
args: the command line arguments, including the 0th argument which is
the program name.
blacklist: a map of blacklisted commands to the messages that should be
print... | 5,303,952 |
def test_vote_after_logged_in(test, test_app):
""" Check that the validator submits vote txs correctly """
test_app.chain = test.t.chain = test_app.services.chain.chain
test.parse('B J0 B B')
# validator = test_app.services.validator
print('These are the txs', transaction_queue)
# Make sure we a... | 5,303,953 |
def decimal_to_num(obj):
"""
Helper function to convert all decimal valued inputs to the real representation of the value (int or float.)
This function is recursive.
Parameters:
obj (obj): An object to parse for decimals.
Returns:
obj: The passed in object with any transformations made.
... | 5,303,954 |
def find_rap_file_any_grid(
top_directory_name, init_time_unix_sec, lead_time_hours,
raise_error_if_missing=True):
"""Finds RAP (Rapid Refresh) file on any grid.
:param top_directory_name: See doc for `find_ruc_file_any_grid`.
:param init_time_unix_sec: Same.
:param lead_time_hours: Sam... | 5,303,955 |
def compute_consistency_score(returns_test, preds):
"""
Compute Bayesian consistency score.
Parameters
----------
returns_test : pd.Series
Observed cumulative returns.
preds : numpy.array
Multiple (simulated) cumulative returns.
Returns
-------
Consistency score
... | 5,303,956 |
def check_if_sums_are_close(uvd1, uvd2, redgrps, array='data'):
"""
Check whether the sum of the data, flags, or nsamples in two UVData objects
is the same within each redgrp.
"""
close = []
for i, grp in enumerate(redgrps):
sum_uvd1 = np.sum(get_data_redgrp(uvd1, grp, array... | 5,303,957 |
def test_downgrade_spinnaker():
"""Test without any metadata name set -- should default to the account name"""
from swag_client.migrations.versions.v2 import downgrade
account_spinnaker = {
"email": "spinnakertestaccount@test.com",
"services": [
{
"metadata": {},
... | 5,303,958 |
def stats(update, context):
""" Show help info about all secret admins commands """
user = User.get_user(update, context)
if not user.is_admin:
return
text = f"""
*Users*: {User.objects.count()}
*24h active*: {User.objects.filter(modified__gte=now() - datetime.timedelta(hours=24)).count()}
... | 5,303,959 |
def load_blacklist():
"""Return blacklist to be used."""
if blacklistfile:
return get_filebased_blacklist()
return get_threecommas_blacklist() | 5,303,960 |
def test_get(route):
""" GETs are redirected w/o a status code change """
resp = client.get(route)
assert resp.status_code == 200
assert resp.json() == "hello" | 5,303,961 |
def test_metadata(shp_file):
"""Test the metadata in the shapefile header is parsed correctly."""
assert shp_file.meta.shape_type == Shapefile.POINT | 5,303,962 |
def is_valid_mx(value: str):
"""Check if mx record is valid."""
for line in value.splitlines():
try:
priority, hostname = line.split(" ")
except ValueError:
raise ValidationError(
"Each line must be in the following format: [priority] [hostname]"
... | 5,303,963 |
def get_index_path(yaml_data):
"""Find the index path."""
for index_root in yaml_data['index_roots']:
if os.path.exists(os.path.join(index_root, yaml_data['index_path'])):
index_path = os.path.join(index_root, yaml_data['index_path'])
break
return index_path | 5,303,964 |
def context(conn: Connection) -> Generator[Cursor, None, None]:
"""
Run multiple PostgreSQL commands in a single connection:
with context() as cursor:
create_account(cursor, owner)
create_database(cursor, owner)
"""
try:
yield conn.cursor()
finally:
c... | 5,303,965 |
def count_accuracy_raw(pred_corpus, target_corpus):
"""
Test accuracy, Raw accuracy
"""
count_accu = 0
total = 0
pred_sents = pred_corpus.split('.')
target_sents = target_corpus.split('.')
for pred_sent, target_sent in zip(pred_sents, target_sents):
pred_list = pred_sent.split(' ... | 5,303,966 |
def _handle_class_a_table(table, record_children, debug):
"""Handle tables with the table headers across the top row."""
table_data = list()
keys = [item.text for item in table.find_all('tr')[0].find_all('th')]
_debug(debug, 'Found {} keys:\n{}'.format(len(keys), keys))
_debug(debug, 'Found {} rows'... | 5,303,967 |
def filestruct_change(in_path, out_path, re_map,
mode='subj_to_type',
use_symlinks=False, name=""):
"""
change from independent subjects in a folder to breakdown structure
example: filestruct_change('/../in_path', '/../out_path', {'asegs.nii.gz':'asegs', 'norm.n... | 5,303,968 |
def xpdacq_per_step(detectors: list, step: dict, pos_cache: dict,
take_reading: typing.Callable = xpdacq_trigger_and_read) -> typing.Generator:
"""
Inner loop of an N-dimensional step scan
This is the default function for ``per_step`` param`` in ND plans.
Parameters
----------
... | 5,303,969 |
def f(random_state, dfnum, dfden, size=None, chunk_size=None, gpu=None, dtype=None):
"""
Draw samples from an F distribution.
Samples are drawn from an F distribution with specified parameters,
`dfnum` (degrees of freedom in numerator) and `dfden` (degrees of
freedom in denominator), where both par... | 5,303,970 |
def get_callers_info(callers_file, callers_package, callers, res_dir):
"""
Tries to create a map between the top callers and its associated file, using a best effort approach, by parsing the
package declaration, in case this is need. If a file matches to a caller in the dataset, it retrieves any required
... | 5,303,971 |
def _get_connection_options(data: Union[str, Dict[str, Any]]) -> Dict[str, ConnectionOptions]:
"""Create per-platform ConnectionOptions objects from configuration dict
Args:
data (str|dict): Connection options in dict or JSON format
Returns:
dict of per-platform connection options
"""
... | 5,303,972 |
def plyify(r, t, ply_thickness, reverse=False):
"""Fill thickness distribution using plies."""
active = []
done = []
np = len(r)
for i in range(np):
while t[i] > len(active) * ply_thickness:
active.append([r[i], -1])
while t[i] <= (len(active) - 1) * ply_thickness:
... | 5,303,973 |
def info(repo=False):
"""List all installed packages with their respective port origin."""
pkg_info = env.flags["chroot"] + "/usr/local/sbin/pkg"
if not os.path.isfile(pkg_info):
return False
if repo:
return ("pkg", "rquery", "%n-%v:%o")
else:
return ("pkg", "query", "%n-%v:%... | 5,303,974 |
def subdivide_array(shape: tuple[int, ...], count: int) -> np.ndarray:
"""
Create indices for subdivison of an array in a number of blocks.
If 'count' is divisible by the product of 'shape', the amount of cells in each block will be equal.
If 'count' is not divisible, the amount of cells in each block ... | 5,303,975 |
def up(services_ctx, services, no_wait):
"""Boots up the required services."""
services_up(
services=list(services),
filepath=services_ctx.filepath,
wait=(not no_wait)
)
click.secho("Services up!", fg="green") | 5,303,976 |
def __hidden(element: Element) -> bool:
"""Element is hidden"""
return element.hidden | 5,303,977 |
def who_confers_recognition(data ,members=None):
"""
Args:
members - possible, group of people who are influenced by authority.
"""
return | 5,303,978 |
def average(runs: List[TrecRun], depth: int = None, k: int = None):
"""Perform fusion by averaging on a list of ``TrecRun`` objects.
Parameters
----------
runs : List[TrecRun]
List of ``TrecRun`` objects.
depth : int
Maximum number of results from each input run to consider. Set to ... | 5,303,979 |
def rpca(table: biom.Table,
rank: int=3,
min_sample_count: int=500,
min_feature_count: int=10,
iterations: int=5) -> (
skbio.OrdinationResults,
skbio.DistanceMatrix):
""" Runs RPCA with an rclr preprocessing step"""
# filter sample to min depth
def samp... | 5,303,980 |
def obsweight(obs_id, ra, dec, iq, cc, bg, wv, elev_const, i_wins, band, user_prior, AM, HA, AZ, latitude, prog_comp,
obs_comp, skyiq, skycc, skybg, skywv, winddir, windvel, wra, verbose = False, debug = False):
"""
Calculate observation weights.
Parameters
----------
obs_id : string... | 5,303,981 |
def create_latency_update_runner(
*,
start_after: float = 10,
interval: float = 60 * 5,
target: str = f"http://127.0.0.1:{Config['port']}",
method: str = "GET",
header: dict[str, str] = None,
) -> Thread:
"""
Creates a thread which automatically updates the latency displayed on statuspag... | 5,303,982 |
def check_for_finished_jobs(input_dirs):
""" Checks each experiment directory for a stdout.txt file and a opt_acts_0.npy action file.
Returns a list of experiment directories that are missing either of these.
"""
finished_jobs, failed_jobs = [], []
for exp_dir in input_dirs:
for job_dir ... | 5,303,983 |
def comp_periodicity(self):
"""Compute the periodicity factor of the lamination
Parameters
----------
self : LamSlotWind
A LamSlotWind object
Returns
-------
per_a : int
Number of spatial periodicities of the lamination
is_antiper_a : bool
True if an spatial ant... | 5,303,984 |
def _attack(params):
"""
Test the target URL with requests.
Intended for use with multiprocessing.
"""
print 'Bee %i is joining the swarm.' % params['i']
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if params['gnuplot_... | 5,303,985 |
def get_ncbi_genetic_testing_registry(ncbi_ftp_login=None):
"""Download data about the Genetic Testing Registry from NCBI
These report when testing is available for a gene, referencing genes by
NCBI Gene ID.
"""
if ncbi_ftp_login:
ncbi_ftp = ncbi_ftp_login
else:
ncbi_ftp = FTP('... | 5,303,986 |
def extract_entity_ids(hass, service):
"""
Helper method to extract a list of entity ids from a service call.
Will convert group entity ids to the entity ids it represents.
"""
entity_ids = []
if service.data and ATTR_ENTITY_ID in service.data:
group = get_component('group')
# ... | 5,303,987 |
def submit_batch(batches):
"""Submit transaction batches using default client URL"""
batch_list = create_batch_list(batches)
client = RestClient(sawtooth_rest_host())
return client.send_batches(batch_list) | 5,303,988 |
def tp53():
"""Create a TP53 fixture."""
params = {
'concept_id': 'ensembl:ENSG00000141510',
'symbol': 'TP53',
'label': 'tumor protein p53',
'previous_symbols': [],
'aliases': [],
'xrefs': ['hgnc:11998'],
'symbol_status': None,
'location_annotation... | 5,303,989 |
def get_example_test(*args, **kwargs):
"""Get a function that calls ``tested_func`` with fake wrapper and trigger.
.. deprecated:: 7.1
This is now part of the Sopel pytest plugin at
:mod:`sopel.tests.pytest_plugin`.
"""
from sopel.tests import pytest_plugin
return pytest_plugin.ge... | 5,303,990 |
def _epoch_ctrl(eva=None, stage="game"):
"""
:param eva:
:param stage: must be one of "game", "confirm", "retrain"
:return:
"""
if stage == "game":
cur_epoch = NAS_CONFIG['eva']['search_epoch']
elif stage == "confirm":
cur_epoch = NAS_CONFIG['eva']['confirm_epoch']... | 5,303,991 |
def _renamed_class_loader(module_name, class_name):
"""Return a class object for class class_name, loaded from module_name.
The trick here is we look in _CLASS_RENAME_MAP before doing
the loading. So even if the class has moved to a different module
since when this pickled object was created, we can s... | 5,303,992 |
def list_namespaced_applications(
kube_client: KubeClient, namespace: str, application_types: Sequence[Any]
) -> Sequence[Application]:
"""
List all applications in the namespace of the types from application_types.
Only applications with complete set of labels are included (See is_valid_application()).... | 5,303,993 |
def _docker_container_init_args_defaults(zz, orig_zz):
"""Copy orig_zz values into zz if not already set"""
zz['name'] = orig_zz['name'] + '.init'
for key, orig_v in orig_zz.iteritems():
if not (key in _DOCKER_FLAG_PAIRS or key in zz):
zz[key] = orig_v | 5,303,994 |
def _train_step(model: _FlaxPenguinModel, optimizer: flax.optim.OptimizerDef,
inputs: _InputBatch, labels: _LabelBatch):
"""Train for a single step, given a batch of inputs and labels."""
def loss_fn(params):
logits = model.apply({'params': params}, inputs)
loss = _categorical_cross_entropy... | 5,303,995 |
def dsubmit(*a, args=(), kwargs=None, rtn="", **kw):
"""Returns a distributed submission context manager, DSubmitter(),
with a new executor instance.
Parameters
----------
args : Sequence of str, optional
A tuple of argument names for DSubmitter.
kwargs : Mapping of str to values or lis... | 5,303,996 |
def get_folder(cfg, experiment, check = False):
"""Returns the experiment folder. Creates it if necessary."""
folder = get_raw_folder(cfg)
utils.checkFolder(folder)
# add experiment subfolder
folder = os.path.join(folder, get_name('exp', experiment))
if check:
utils.checkFolder(folder)
... | 5,303,997 |
def isNumber(n):
"""retorna true si 'n' es un numero"""
return all(n[i] in "0123456789" for i in range(len(n))) | 5,303,998 |
def import_data():
"""Import data
Parameters
----------
none
Returns
-------
df_listings: DataFrame
df_prices: DataFrame
df: DataFrame
"""
# Import listings data
url_listings = "http://data.insideairbnb.com/italy/emilia-romagna/bologna/2021-12-17/data/listings.... | 5,303,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.