content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_categories(categories_file):
""" Group categories by image
"""
# map each category id to its name
id_to_category = {}
for category in categories_file['categories']:
id_to_category[category['id']] = category['name']
image_categories = {}
for category in categories_file['annot... | 40,200 |
def get_profit_forecast(code: str,
getter: Callable[[str], pd.DataFrame] = rdb.get_profit_forecast):
""" 获取分析师的盈利预期
"""
today = datetime.datetime.now().strftime('%Y-%m-%d')
return getter(today).loc[code].to_dict() | 40,201 |
def checkpoint_wrapper(module: nn.Module, offload_to_cpu: bool = False) -> nn.Module:
"""
A friendlier wrapper for performing activation checkpointing.
Compared to the PyTorch version, this version:
- wraps an nn.Module, so that all subsequent calls will use checkpointing
- handles keyword argument... | 40,202 |
def get_L_star_CS_d_t_i(L_CS_d_t_i, Q_star_trs_prt_d_t_i, region):
"""(9-2)(9-2)(9-3)
Args:
L_CS_t_i: 日付dの時刻tにおける暖冷房区画iの1時間当たりの冷房顕熱負荷(MJ/h)
Q_star_trs_prt_d_t_i: 日付dの時刻tにおける暖冷房区画iの1時間当たりの熱損失を含む負荷バランス時の非居室への熱移動(MJ/h)
region: 地域区分
L_CS_d_t_i: returns: 日付dの時刻tにおける暖冷房区画iの1時間当たりの熱損失を含む負荷バランス... | 40,203 |
def getactivetlsciphers(ctx):
"""You can use the GetActiveTlsCiphers method to get a list of the TLS ciphers that are currently accepted on the cluster."""
cli_utils.establish_connection(ctx)
ctx.logger.info(""": """+""";"""+"")
try:
_GetActiveTlsCiphersResult = ctx.element.ge... | 40,204 |
def delete(isamAppliance, name, check_mode=False, force=False):
"""
Delete an Authentication Mechanism
"""
ret_obj = search(isamAppliance, name, check_mode=check_mode, force=force)
mech_id = ret_obj['data']
if mech_id == {}:
logger.info("Authentication Mechanism {0} not found, skipping ... | 40,205 |
def point_to_line_cluster_distance(point, line_cluster):
"""
Distance between a single point and a cluster of lines
"""
return val_point_to_line_cluster_distance(point.value, np.array([l.value for l in line_cluster])) | 40,206 |
def str_time_prop(start, end, date_format, prop):
"""Get a time at a proportion of a range of two formatted times.
start and end should be strings specifying times formated in the
given format (strftime-style), giving an interval [start, end].
prop specifies how a proportion of the interval to be taken... | 40,207 |
def depart_todoext_node(self, node):
"""
depart_todoext_node,
see https://github.com/sphinx-doc/sphinx/blob/master/sphinx/writers/html.py
"""
self.depart_admonition(node) | 40,208 |
def read_table(filepath_or_buffer: Literal["2014-01-02.csv"], skiprows: List[int]):
"""
usage.dask: 1
"""
... | 40,209 |
def parse_fields(flds):
"""Parse Data Dictionary XML Fields
Arguments:
flds -- XML document element for fields
"""
fields_dict = dict()
for elem in flds:
elem_tag = str(elem.tag).strip()
if elem_tag.lower() != FIELD_TAG.lower():
raise ValueError(elem_tag + " elem... | 40,210 |
def analyse_json_data(input_file_path):
"""
:type input_file_path: str
:rtype: InputData
:raise FileNotFoundError
"""
data = InputData()
try:
with open(input_file_path, 'r') as input_file:
json_data = json.load(input_file)
except FileNotFoundError as e:
raise... | 40,211 |
def process_datastore_tweets(project, dataset, pipeline_options):
"""Creates a pipeline that reads tweets from Cloud Datastore from the last
N days. The pipeline finds the top most-used words, the top most-tweeted
URLs, ranks word co-occurrences by an 'interestingness' metric (similar to
on tf* idf).
"""
u... | 40,212 |
def unpack_uid(uid):
"""
Convert packed PFile UID to standard DICOM UID.
Parameters
----------
uid : str
packed PFile UID as a string
Returns
-------
uid : str
unpacked PFile UID as string
"""
return ''.join([str(i-1) if i < 11 else '.' for pair in [(ord(c) >> 4... | 40,213 |
def command(name=None):
"""A decorator to register a subcommand with the global `Subcommands` instance.
"""
def decorator(f):
_commands.append((name, f))
return f
return decorator | 40,214 |
def rm(connection: Connection, path: str):
"""Remove a file or directory."""
connection.transport.remove(path)
click.secho(f"Removed {path}", fg="green") | 40,215 |
def main_pipeline():
"""
Runs pipeline to calculate customer churn at bank
input:
None
output:
None
"""
data = import_data()
data = prepare_data(data)
_, categorical_cols, numeric_cols = classify_columns(data)
perform_eda(data, categorical_cols, numeric_cols)
... | 40,216 |
def test_004_check_call(execute, exec_result, subprocess_logger) -> None:
"""Test exit code validator."""
runner = exec_helpers.Subprocess()
if exec_result.exit_code == exec_helpers.ExitCodes.EX_OK:
assert runner.check_call(command, stdin=exec_result.stdin) == exec_result
else:
with pyte... | 40,217 |
def agse_convert(invec, swdata, insys='gse'):
"""Convert between GSE and aberrated GSE
Using common definiton, e.g., Schwartz 1998
(S.J. Schwartz, "Shock and Discontinuity Normals, Mach Numbers, and Related Parameters",
In: Analysis Methods for Multi-Spacecraft Data, Eds.: G. Paschmann and P. Daly,
... | 40,218 |
def copy_to_hdfs(local_path, relative_hdfs_path, overwrite=False, project=None):
"""
Copies a path from local filesystem to HDFS project (recursively) using relative path in $CWD to a path in hdfs (hdfs_path)
For example, if you execute:
>>> copy_to_hdfs("data.tfrecords", "/Resources", project="demo")... | 40,219 |
def parse_geom_text_output(out_lines, input_dict=None):
"""
Parse output of .geom file
:param out_lines: a list of lines from the readline function
:param input_dict: not in use at the moment
:return parsed_data: key, value of the trajectories of cell, atoms,
force etc
"""
import numpy... | 40,220 |
def evalKnapsackBalanced(individual):
"""
Variant of the original weight-value knapsack problem with added third object being minimizing weight difference between items.
"""
weight, value = evalKnapsack(individual)
balance = 0.0
for a,b in zip(individual, list(individual)[1:]):
balance +... | 40,221 |
def clean_shutdown_when_killed(signum, *args):
"""Close all connections cleanly and log shutdown
This function will be called when SIGTERM is received from OS
or if the program is killed by "kill" command. It then raises
KeyboardInterrupt to close all resources and log the shutdown.
"""
logging.... | 40,222 |
def test_get_all_groups(test_cloud_manager):
"""
Test that getting all groups return the ID from the API response and that
the API is called with the correct values
"""
# Setup #
group_id = "153"
response = {
"kind": "admin#directory#groups",
"etag": "",
"groups": [
... | 40,223 |
def read_links(ls):
"""Returns list of objects with source and target"""
return list(map(lambda el: {"source": el, "target": os.readlink(el)}, ls)) | 40,224 |
def complexify_module(lines_in):
"""
Complexify a module by separating its derived types, functions, and subroutines
and passing them through a line complexification function.
Parameters
----------
lines_in : list of string
List of strings source code for one module to be complexified
... | 40,225 |
def utc_right_now():
"""
Returns a datetime object reflecting the time in UTC as of when this function was called.
"""
return datetime.datetime.now(tz=pytz.utc).replace(tzinfo=None) | 40,226 |
def process_img_border(img_array, polygon_pts, border=6):
"""Process Raw Data into
Args:
img_array (numpy array): numpy representation of image.
polygon_pts (array): corners of the building polygon.
Returns:
numpy array: .
"""
heigh... | 40,227 |
def async_flow_poll(destination: Text, batch_id: Text) -> Dict[Text, Any]:
"""Repeatedly checks on the status of the batch, and returns
the result after the processing has been completed.
Args:
destination (Text): This is the destination parsed
batch_id (Text):
Returns:
Dict[Te... | 40,228 |
def test_smp_query():
"""Test smp_query"""
urns = ('urn:oasis:names:tc:ebcore:partyid-type:iso6523:0088::'
'kellytestsmp',
'urn:oasis:names:tc:ebcore:partyid-type:iso6523:0088::'
'kelly2021',
'urn:oasis:names:tc:ebcore:partyid-type:iso6523:0088::'
'kel... | 40,229 |
def get_connection(arn: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetConnectionResult:
"""
Provides details about CodeStar Connection.
## Example Usage
```python
import pulumi
i... | 40,230 |
def generate_samples(n_samples, func, *args, **kwargs):
"""Call a function a bunch of times and count the results.
Args:
n_samples: Number of time to call the function.
func: The function results are counted from.
*args
**args: The arguments to pass to func.
Returns:
... | 40,231 |
def default(typ, default=None, frm=None):
""" optional value """
def _internal(val):
if typ(val) is Consts.Fail:
return default
else:
return val
return u_condition_checker(frm, _internal) | 40,232 |
def fltflag(*args):
"""fltflag() -> flags_t"""
return _idaapi.fltflag(*args) | 40,233 |
def make_histogram(measure_file, measure):
"""
Generates Histogram Image of intensities for a given input
nifti file.
Parameters
----------
measure_file : string
path to input nifti file
measure : string
Name of the measure label in the plot
Returns
--... | 40,234 |
def get_mopac_deltaH0(lines):
"""
Return delta H in kcal/mol from mopac output.
#>>> s = io.read_file('test/input.out')
#>>> print(get_mopac_deltaH(s))
-13.02534
"""
if isinstance(lines, str):
lines = lines.splitlines()
keyword = 'FINAL HEAT OF FORMATION'
n = io.get_line_numb... | 40,235 |
def create():
""" Creates database tables from sqlalchemy models and import samples """
from app.database import db_session as db, Base, engine
from utils.db import populate_from_samples
import app.models
Base.metadata.create_all(engine) | 40,236 |
def abstract(f):
"""
make method abstract.
class Foo(object):
@abstract
def bar(self):
pass
foo = Foo()
foo.bar() # NotImplementedError: can't invoke abstract method 'bar'
"""
@wraps(f)
def wrapper(*args, **kwargs):
msg = "can't invoke abstract m... | 40,237 |
def cli(queue, to_queue, limit, dryrun):
"""
Redrives all the messages from the given sqs queue to the destination
"""
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s - %(message)s",
stream=sys.stdout,
)
_log = logging.getLogger(__name__)
... | 40,238 |
def capitalize_1(string):
"""
Capitalizes a string using a combination of the upper and lower methods.
:author: jrg94
:param string: any string
:return: a string with the first character capitalized and the rest lowercased
"""
return string[0].upper() + string[1:].lower() | 40,239 |
def edit_current_stock(current_stock_id, current_stock_data):
"""
修改信息
:param current_stock_id:
:param current_stock_data:
:return: Number of affected rows (Example: 0/1)
:except:
"""
return db_instance.edit(STCurrentStock, current_stock_id, current_stock_data) | 40,240 |
def fit_via_yule_walker(x, order, acf_method="mle", demean=True):
"""
Estimate AR(p) parameters of a sequence x using the Yule-Walker equation.
Parameters
----------
x : 1d numpy array
order : integer
The order of the autoregressive process.
acf_method : {'unbiased', 'mle'}, optiona... | 40,241 |
def parse_challenge(verify_mfa, challenge_result):
"""Parse the challenge response.
:param mfa_result: response from MFA challenge status request
:return challenge status: status of MFA challenge
:return challenge reason: additional info about challenge status
"""
challenge_reason = None
i... | 40,242 |
def simple_function(stuff):
"""
Just a simple function to show documentation features
:param stuff:
:return:
""" | 40,243 |
def beta_create_Bookstore_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This function was
generated o... | 40,244 |
def domain_parser_yml_to_json(path_to_domain_yml, path_to_domain_json):
"""
Chatbot Domain Parser, will parse 'domain.yml' file to json object and write to file
:param path_to_domain_yml: Complete path to YML domain file
:param path_to_domain_json: Complete path to file where Json Object will be written... | 40,245 |
def get_url_and_token(string):
""" extract url and token from API format """
try:
[token, api] = string.split(":", 1)
[_, _, addr, _, port, proto] = api.split("/", 5)
url = f"{proto}://{addr}:{port}/rpc/v0"
except Exception:
raise ValueError(f"malformed API string : {string}"... | 40,246 |
def get_user(UserName=None):
"""
Retrieves information about the specified IAM user, including the user's creation date, path, unique ID, and ARN.
If you do not specify a user name, IAM determines the user name implicitly based on the AWS access key ID used to sign the request to this API.
See also: AWS... | 40,247 |
def checkZone(false, usrdata):
""" Check the cloudflare zone record for entries to remove """
# Call api
request = [('a', 'rec_load_all')]
json_data = callAPI(request, usrdata)
# Dicts and Lists for later
falserecs = {}
names = {}
recs = []
falsedata = {}
recdata = {}
# Par... | 40,248 |
def read_temp(buffer: io.BytesIO, offset: int = None) -> float:
"""Retrieve temperature [C] value (2 bytes) from buffer"""
if offset:
buffer.seek(offset)
value = int.from_bytes(buffer.read(2), byteorder="big", signed=True)
return float(value) / 10 | 40,249 |
def convert_netaddr(netaddr: str) -> str:
"""
Converts network address from hex_ip:hex_port format to ip:port
e,g: 573B1FAC:BE46 to 172.31.59.87:48710
"""
try:
if check_netaddr_pattern(netaddr):
addr, port = netaddr.split(':')
addr = convert_addr(addr)
po... | 40,250 |
def derive_prehashes_from_events(events, join_by=DEFAULT_JOIN_BY):
"""
Compute a normalized form (pre-hash string) for each event.
This is the main functionality of the hash generator.
"""
events = copy.deepcopy(events) # do not change parameter!
global JOIN_BY
join_by = join_by.replace(r... | 40,251 |
def local_css(file_name: str) -> None:
"""Loads a local .css file into streamlit."""
with open(file_name) as f:
st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True) | 40,252 |
def make_bsa_2d(betas, theta=3., dmax=5., ths=0, thq=0.5, smin=0,
method='simple',verbose = 0):
"""
Function for performing bayesian structural analysis
on a set of images.
Parameters
----------
betas, array of shape (nsubj, dimx, dimy) the data used
Note that... | 40,253 |
def train_surrogate_on_task(task_id: typing.Union[int, str],
hyperparameter_names: typing.List[str],
setup_data: pd.DataFrame,
evaluation_measure: str,
normalize: bool,
n_estimator... | 40,254 |
def build_label_dict(acts, use_loaded_files=True, verbose=True, doMean=False):
"""
Builds a dictionary of labels to points in local format
Gives out a dictionary and a list of found labels
acts: activation table object
use_loaded_files: whether to assume one file per label (current default)
This... | 40,255 |
def test_hhs_hospital_dataset_non_default_start_date():
"""Tests HHSHopsitalStateDataset imports adult_icu_beds_capacity
correctly for a state with a non-default start date (Alaska) verifying
that data prior to its start date (2020-10-06) is dropped."""
variable = ccd_helpers.ScraperVariable(
va... | 40,256 |
def do_tenant_user_list(client, args):
""" List users in a keystone tenant """
t = client.tenants.get(args.id)
ulist = client.tenants.list_users(t['id'])
utils.print_list(ulist, client.users.columns) | 40,257 |
def test_program_record(client):
"""Test that a request for program record results in 200"""
user = UserFactory.create()
enrollment = ProgramEnrollmentFactory.create(user=user)
client.force_login(user)
resp = client.get(reverse("grade_records", kwargs=dict(enrollment_id=enrollment.id)))
assert r... | 40,258 |
def handle_materials(context, model, materials):
"""
"""
for m in model.Materials:
matname = material_name(m)
if matname not in materials:
blmat = utils.get_iddata(context.blend_data.materials, None, m.Name, None)
blmat.use_nodes = True
refl = m.Reflectivi... | 40,259 |
def test_dag_preserves_superrep(dimension, conversion):
"""
Checks that dag() preserves superrep.
"""
qobj = conversion(qutip.rand_super_bcsz(dimension))
assert qobj.superrep == qobj.dag().superrep | 40,260 |
def fibonacci(n: int) -> int:
"""
Iteratively compute fibonacci of n
"""
if n==0: return 0
if n==1: return 1
fp2 = 0
fp1 = 1
for _ in range(1,n):
f = fp1 + fp2
fp2 = fp1
fp1 = f
return f | 40,261 |
def create_spec_list_file():
"""
Generate Extension Meta data file
"""
import sys
sys.path.append("../")
import json
with open("{}_v{}.json".format(EXTENSION_ID, EXTENSION_VERSION), 'w') as f:
data = get_spec_registry_data()
json.dump(data, f, indent=2) | 40,262 |
def do_make_label_group(
text: List[str], **kwargs: Dict[str, Any]
) -> Tuple[int, List[RAMSTKLabel]]:
"""Make and place a group of labels.
The width of each label is set using a natural request. This ensures the
label doesn't cut off letters. The maximum size of the labels is
determined and used... | 40,263 |
def get_minibatch(roidb, num_classes):
"""Given a roidb, construct a minibatch sampled from it."""
num_images = len(roidb)
# Sample random scales to use for each image in this batch
random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),
size=num_images)
as... | 40,264 |
def write_to_file(tpm_values, gene_names, outputfile):
"""
:param tpm_values: tpm table
:param gene_names: two columns with gene ID and gene name
:param outputfile: path for output file
:return: None
"""
with open(outputfile, "w") as file:
for i in range(len(tpm_values)):
... | 40,265 |
def _variable_with_weight_decay(name, shape, stddev, wd, index):
"""Helper to create an initialized Variable with weight decay.
Note that the Variable is initialized with a truncated normal distribution.
A weight decay is added only if one is specified.
Args:
name: name of the variable
shape: list of i... | 40,266 |
def safe_makedirs(path):
"""Make directories without throwing if a directory exists."""
try:
os.makedirs(path)
except OSError as err:
if err.errno != errno.EEXIST: # suppress(PYC90)
raise err | 40,267 |
def plot_line_line_y1_y2(
y1: pd.Series,
y2: pd.Series,
*,
figsize: Optional[Tuple[float, float]] = None,
smoothing: Optional[str] = None,
number_knots: Optional[int] = None,
marker1: Optional[str] = '.',
marker2: Optional[str] = '.',
markersize1: Optional[int] = 8,
markersize2: ... | 40,268 |
def make_admin_versionable(cls):
"""Make Admin class versionable"""
class AdminVersionable(AdminVersionableMixIn, cls):
pass
return AdminVersionable | 40,269 |
def _get_temp_folder_linux():
"""Get the temp folder on a Linux system.
This method may also be used by unknown operating systems.
"""
# On Linux, we prefer to use "$XDG_RUNTIME_DIR", since it is dedicated
# to this kind of purpose. If it's not available, Porthole will create
# a new temporary... | 40,270 |
def enable_traceback_syntax_highlight(enable):
"""Enable/disable syntax highlighted stacktraces when using asynq's exception handler."""
global _use_syntax_highlighting
_use_syntax_highlighting = enable | 40,271 |
def generate_model (d):
"""Returns a set of (random) d+1 linear model coefficients."""
return np.random.rand (d+1, 1) | 40,272 |
def handle_error(ex, hed_info=None, title=None, return_as_str=True):
"""Handles an error by returning a dictionary or simple string
Parameters
----------
ex: Exception
The exception raised.
hed_info: dict
A dictionary of information.
title: str
A title to be in... | 40,273 |
def read(filename, ffmpeg_bin="ffmpeg", debug=False):
"""
Read an audio file into python using FFMPEG. The syntax
is similar to `scipy.io.wavfile.read`.
Note: only supports signed 16 bit audio
Parameters
----------
filename: str
The audio filename
ffmpeg_bin: str, optional
... | 40,274 |
def get_parent_epic(issue):
"""Get the parent epic of `issue`.
Different boards have different meta data formats.
"""
return (
# DEV board
getattr(ticket.fields, JIRA_FIELD_EPIC_LINK, None)
# BS board
or getattr(getattr(ticket.fields, 'parent', None), 'key', None)
) | 40,275 |
def template_GranularFormLayout(request):
"""
${form()|n}
<h2>Form</h2>
<h3>Normal Form</h3>
<pre>
${form()}
</pre>
<h4>Form Header, metadata, actions and Footer</h4>
<pre>
${form.header()}
<hr />
${form.metadata()}
<hr />
${form.actions()}
<hr />
${form.footer()}
</pre>
<h4>First Name</h4>
<pre>
${form['firs... | 40,276 |
def shortcuts_backup_path(directory, user, timestamp_format="%Y%m%d%H%M%S"):
"""
Returns the path for a shortcuts.vdf backup file.
This path is in the designated backup directory, and includes a timestamp
before the extension to allow many backups to exist at once.
"""
assert (directory is not ... | 40,277 |
def filter_by_date_range(tasks, start_date, end_date):
"""
>>> tasks = []
>>> add_task(tasks, '1', 'Do my homework', '2016-04-30', 'normal', ['school'])
>>> add_task(tasks, '2', 'Do your homework', '2016-05-10', 'normal', ['work'])
>>> filter_by_date_range(tasks, '2016-04-20', '2016-05-01') == [{'id... | 40,278 |
def get_elements(driver,
selector,
text='',
selector_type=By.CSS_SELECTOR,
timeout=DEFAULT_TIMEOUT,
must_be_visible=True):
"""
Pauses execution until one or more elements matching the selector is visible.
:param driver: we... | 40,279 |
def test_layout_root(testapp):
"""Test get response from layout view."""
response = testapp.get('/', status=200)
html = response.html
assert 'SpaceRocks' in html.find("title").text | 40,280 |
def get_date_from_folder(file_str):
"""
get datetime from file folder of .et3, .erd, i.e.,
'DATA2015-01-29-16-57-30/', '2020-10-11-03-48-52/'
"""
f = file_str.strip()
f = f[:-1] # remove trailing '/'
f = f.replace("DATA", "")
# replace the 3rd occurrence of '-'
w = [m.start() for m ... | 40,281 |
def translate_api2db(namespace, alias):
"""
>>> translate_api2db("ga4gh", "SQ.1234")
[('VMC', 'GS_1234')]
"""
if namespace.lower() == "refseq":
return [("NCBI", alias)]
if namespace == "ensembl":
return [("Ensembl", alias)]
if namespace == "lrg":
return [("LRG", ali... | 40,282 |
def process_timestep_data(data, outfile, writenode):
"""write data for the entire timestep to outfile
Args:
data (list): list of all data, with each entry containing [nodeID, xdisp, ydisp, zdisp]
outfile (obj): output file object
writenode (Boolean): Boolean if the node IDs should be wr... | 40,283 |
def register_view(request):
"""Renders the register page."""
if request.method == 'GET':
# Get signup form to display
form = SignUpForm()
return render(request, 'myroot/registration/register.html',
{'form': form,
'title': "Register | ... | 40,284 |
def make_environment():
"""Creates an OpenAI Gym environment."""
# Load the gym environment.
environment = fakes.ContinuousEnvironment(
action_dim=1, observation_dim=2, episode_length=10
)
return environment | 40,285 |
def device_get(context, device_id):
"""get a device according to specify device_id"""
return IMPL.device_get(context, device_id) | 40,286 |
def convolve_gaussian_2d(image, gaussian_kernel_1d):
"""Convolve 2d gaussian."""
result = scipy.ndimage.filters.correlate1d(
image, gaussian_kernel_1d, axis=0)
result = scipy.ndimage.filters.correlate1d(
result, gaussian_kernel_1d, axis=1)
return result | 40,287 |
def refresh_viewer(viewer, pdf_path,
tm_bundle_support=getenv('TM_BUNDLE_SUPPORT')):
"""Tell the specified PDF viewer to refresh the PDF output.
If the viewer does not support refreshing PDFs (e.g. “Preview”) then this
command will do nothing. This command will return a non-zero value if... | 40,288 |
def getLineagesFromChangeo(changeodb, print_summary):
"""subsets the changeo_db output by bracer by only those cells which are within lineages (non singletons)"""
df = changeodb
_df = df[df.CLONE != "None"] # get rid of unassigned cells (no BCR reconstructed)
_df = (df.CLONE.value_counts() > 1) #find cl... | 40,289 |
def pop():
""" Clear the current execution environment for whatever parallel mechanism is used. """
with _lock:
ident = identifier()
envs = _current_envs.get(ident)
if envs:
env = envs.pop()
env.deactivate()
if _current_envs[ident]:
c... | 40,290 |
def _run_cnvkit_cancer(items, background, access_file):
"""Run CNVkit on a tumor/normal pair.
"""
paired = vcfutils.get_paired_bams([x["align_bam"] for x in items], items)
work_dir = _sv_workdir(items[0])
ckout = _run_cnvkit_shared(items[0], [paired.tumor_bam], [paired.normal_bam],
... | 40,291 |
def create_metadata(config_file: object, edition: int, final_layers: tuple) -> None:
""" Takes in some user data, along with the layers of the image
and create a metadata json for the image. The json object
can be stored and used by third-party marketplaces.
"""
token_prefix = config_file['token_pre... | 40,292 |
def meanAdjustELE(site_residuals, azSpacing=0.5,zenSpacing=0.5):
"""
PWL piece-wise-linear interpolation fit of phase residuals
cdata -> compressed data
"""
tdata = res.reject_absVal(site_residuals,100.)
del site_residuals
data = res.reject_outliers_elevation(tdata,5,0.5)
del tdata
... | 40,293 |
def update_running_avg(new, current, alpha=1.0):
"""Computes in-place running average
current = alpha*current + (1-alpha)*new
Args:
new (tensor): tensor to add to current average
current (tensor): tensor containing current average. Result will be
saved in place to this tensor.
... | 40,294 |
def rotateImage(input_img, angle):
"""
Rotate the input_img by angle degrees, Rotate center is image center.
:param input_img:np.array, the image to be rotated
:param angle:float, the counterclockwise rotate angle
:return:np.array, the rotated image
"""
radian = angle * math.pi / 180.0
a... | 40,295 |
def get_content_model_prefetch(content_model, content_attr='content'):
""" Returns the fields that should be prefetched, for a relation that
starts with '<content_attr>__'. If the model has MTURK_PREFETCH, then that
is used. Otherwise, some common attributes are tested (photo, shape) and
used if those... | 40,296 |
def dispatch(obj, replacements):
"""make the replacement based on type
:param obj: an obj in which replacements will be made
:type obj: any
:param replacements: the things to replace
:type replacements: tuple of tuples
"""
if isinstance(obj, dict):
obj = {k: dispatch(v, replacements... | 40,297 |
def _decrementDepth():
"""
Manually decrement depth counter.
"""
if timing:
global _currentDepth
_currentDepth -= 1 | 40,298 |
def process(
mode,
infile,
outdir,
genes,
genes_drop,
genes_bed,
igh,
mmrf,
bolli,
lohr,
normals,
mytype):
"""Main function to process myTYPE SNV and indel output"""
## IMPORTING DATA
variants = import_variants(i... | 40,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.