content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def init():
"""Init template functionality"""
global LOADER, ENVIRONMENT
LOADER = FileSystemLoader(env["datastore"]["path"])
ENVIRONMENT = Environment(loader=LOADER, line_statement_prefix='#%', line_comment_prefix='##')
env['template']['filters'].update(ENVIRONMENT.filters)
ENVIRONMENT.filters =... | 5,344,500 |
def printWorldMap(location: List[int]):
"""Print the worldmap with the player at the intended location."""
x: int = location[0]
y: int = location[1]
# Place the player icon 'P' in the correct spot.
map: List[str] = worldmap.copy()
row: List[str] = list(map[y])
row[x] = 'P'
map[y] = "".j... | 5,344,501 |
def load_data(database_filepath):
"""
Input:
1. database_filepath: the path of cleaned datasets
Output:
1. X: all messages
2. y: category columns generated by cleaning process
3. category_names: category columns' names
Process:
1. Read-in the datafrmae
2. ... | 5,344,502 |
def click():
"""Save and load cache."""
cache['a'] = 3
assert cache[b'a'] == 3
assert cache[u'a'] == 3
cache[b'b'] = True
assert cache[b'b']
assert cache[u'b'] | 5,344,503 |
def lh_fus(temp):
"""latent heat of fusion
Args:
temp (float or array): temperature [K]
Returns:
float or array: latent heat of fusion
"""
return 3.336e5 + 1.6667e2 * (FREEZE - temp) | 5,344,504 |
def eval_edge_enemies(enemy_ships, star_set):
"""
Evaluates enemies at the top and bottom edge and takes actions appropriately
Args:
enemy_ships (list): The enemy ships
star_set (set): The set of stars
Returns:
boolean: True if all checks pass and False if an enemy reached the ... | 5,344,505 |
def to_eaf(file_path, eaf_obj, pretty=True):
"""
modified function from https://github.com/dopefishh/pympi/blob/master/pympi/Elan.py
Write an Eaf object to file.
:param str file_path: Filepath to write to, - for stdout.
:param pympi.Elan.Eaf eaf_obj: Object to write.
:param bool pretty: Flag to ... | 5,344,506 |
def delete_station(station_id):
"""Delete station from stations
:param station_id:
:return: string
"""
logger.debug(f"Call delete_stations: {station_id}")
# Load old data into structure
stations = load_stations()
# Find index in list of stations
target_index = find_index_in_list_of_d... | 5,344,507 |
def main(data_path: str, saved_model_path: str) -> None:
"""The main training function"""
if saved_model_path:
global embedding_dim, char_embedding_dim, hidden_dim, char_hidden_dim, use_bert_cased, \
use_bert_uncased, use_bert_large
embedding_dim, char_embedding_dim, hidden_dim, char... | 5,344,508 |
def query_for_build_status(service, branch, target, starting_build_id):
"""Query Android Build Service for the status of the 4 builds in the target
branch whose build IDs are >= to the provided build ID"""
try:
print ('Querying Android Build APIs for builds of {} on {} starting at'
' buildID {}'... | 5,344,509 |
def create_pool(
dsn=None,
*,
min_size=10,
max_size=10,
max_queries=50000,
max_inactive_connection_lifetime=300.0,
setup=None,
init=None,
loop=None,
authenticator=None,
**connect_kwargs,
):
"""Create an Asyncpg connection pool through Approzium authentication.
Takes s... | 5,344,510 |
def _get_all_schedule_profile_entries_v1(profile_name, **kwargs):
"""
Perform a GET call to get all entries of a QoS schedule profile
:param profile_name: Alphanumeric name of the schedule profile
:param kwargs:
keyword s: requests.session object with loaded cookie jar
keyword url: URL ... | 5,344,511 |
def loadSource(path):
"""Loads a list of transportReactions. Format:
R("Macgamb_Transp")
R("Madnb_Transp")
R("MalaDb_Transp")..."""
file = open(path, 'r')
sources = [line.strip() for line in file]
file.close()
return sources | 5,344,512 |
def frombin(
__data: Bitcode,
__dtype: SupportedDataType | bytes,
num: int = 1,
*,
encoding: Optional[str] = None,
signed: bool = True,
) -> ValidDataset:
"""converts a string of 0 and 1 back into the original data
Args:
data (BinaryCode): a string of 0 and 1
dtype (Unio... | 5,344,513 |
def check_size():
"""Assumes the problem size has been set by set_size before some operation.
This checks if the size was changed
Size is defined as (PIs, POs, ANDS, FF, max_bmc)
Returns TRUE is size is the same"""
global npi, npo, nands, nff, nmd
#print n_pis(),n_pos(),n_ands(),n_latches()
... | 5,344,514 |
def vrms2dbm(vp):
"""
Converts a scalar or a numpy array from volts RMS to dbm assuming there is an impedence of 50 Ohm
Arguments:
- vp: scalar or numpy array containig values in volt RMS to be converted in dmb
Returns:
- scalar or numpy array containing the result
"""
return ... | 5,344,515 |
def git_commit(message, transaction_id, author, timestamp):
"""Add changes to index and commit them in Git
:param message: git commit message
:param transaction_id: AccuRev transaction ID
:param author: AccuRev transaction author
:param timestamp: timestamp at which the original AccuRev transaction... | 5,344,516 |
def aa_i2c_read (aardvark, slave_addr, flags, data_in):
"""usage: (int return, u08[] data_in) = aa_i2c_read(Aardvark aardvark, u16 slave_addr, AardvarkI2cFlags flags, u08[] data_in)
All arrays can be passed into the API as an ArrayType object or as
a tuple (array, length), where array is an ArrayType o... | 5,344,517 |
def get_log_dir(env=None):
"""
Get directory to use for writing log files. There are multiple
possible locations for this. The ROS_LOG_DIR environment variable
has priority. If that is not set, then ROS_HOME/log is used. If
ROS_HOME is not set, $HOME/.ros/log is used.
@param env: override os.en... | 5,344,518 |
def urbandictionary_search(search):
"""
Searches urbandictionary's API for a given search term.
:param search: The search term str to search for.
:return: definition str or None on no match or error.
"""
if str(search).strip():
urban_api_url = 'http://api.urbandictionary.com/v0/de... | 5,344,519 |
def Performance(ALGORITHM_CONFIG, CELLULAR_MODEL_CONFIG, alog_name):
"""
Performance testing
"""
# Server profile: num_ues=200, APs=16, Scale=200.0, explore_radius=1
loadbalanceRL = interface.Rainman2(SETTINGS)
loadbalanceRL.algorithm_config = ALGORITHM_CONFIG
loadbalanceRL.environment_confi... | 5,344,520 |
def launch(sid):
"""
Launch a scan
Launch the scan specified by the sid.
"""
data = connect('POST', '/scans/{0}/launch'.format(sid))
return data['scan_uuid'] | 5,344,521 |
def transpose_dict(data, data_key):
"""Function: transpose_dict
Description: Transpose specified keys in a list of dictionaries
to specified data types or None.
Arguments:
(input) data -> Initial list of dictionaries.
(input) data_key -> Dictionary of keys and data types.
... | 5,344,522 |
def assert_almost_equal(
actual: numpy.float64, desired: float, decimal: int, err_msg: Literal["test #7"]
):
"""
usage.scipy: 1
"""
... | 5,344,523 |
def aligner_to_symbol(calls):
"""
Assign symbols to different aligners in the input file
Set the attribute of the class instances
return a list of indices for which each aligner is found uniquely and all aligners
sorted by aligners
"""
symbols = ['o', '+', 'x', 'v', '*', 'D', 's', 'p', '8',... | 5,344,524 |
def timestamped_filename(line):
"""Given a line like '.... filename <timestamp>', return filename."""
m = re_timestamped_line.search(line)
if m:
return m.group("filename")
else:
print >> sys.stderr, "Error: could not find filename in:", line
return None | 5,344,525 |
def nfvi_create_subnet(network_uuid, subnet_name, ip_version, subnet_ip,
subnet_prefix, gateway_ip, dhcp_enabled, callback):
"""
Create a subnet
"""
cmd_id = _network_plugin.invoke_plugin('create_subnet', network_uuid,
subnet_name, ip_ver... | 5,344,526 |
def download_mnistf(path):
"""Download fashion MNIST data in gzip format
Arguments
path: path where to cache the dataset locally
"""
## TODO: os.path does not work on GCS storage files.
if not os.path.exists(path):
os.makedirs(path)
for file in MNISTF_FILES:
source_path = os.p... | 5,344,527 |
def convertCRS(powerplants, substations, towers, crs, grid):
"""
:param powerplants:
:param substations:
:param towers:
:param crs:
:return:
"""
substations.to_crs(crs)
# powerplants = powerplants.set_crs(crs)
# powerplants = powerplants.to_crs(crs)
# print(powerplants.crs)
... | 5,344,528 |
def cleanup_old_versions(src, keep_last_versions):
"""Deletes old deployed versions of the function in AWS Lambda.
Won't delete $Latest and any aliased version
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.p... | 5,344,529 |
def get_pathway(page_name, end_pg, max_len, trail, paths):
"""
Finds a list of all paths from a starting wikipedia page to an end page
Assumes page_name is a valid wikipedia article title and end_pg is a valid
Wikipedia Page Object
Args:
page_name: (Str) The name of the current article... | 5,344,530 |
def message(level, sender, text):
"""Print a message using NEST's message system.
Parameters
----------
level :
Level
sender :
Message sender
text : str
Text to be sent in the message
"""
sps(level)
sps(sender)
sps(text)
sr('message') | 5,344,531 |
def clip_to_ndc(point_clip_space, name="clip_to_ndc"):
"""Transforms points from clip to normalized device coordinates (ndc).
Note:
In the following, A1 to An are optional batch dimensions.
Args:
point_clip_space: A tensor of shape `[A1, ..., An, 4]`, where the last
dimension represents points in ... | 5,344,532 |
def augment_docs_with_tracking_info(docs, user):
"""Add attribute to each document with whether the document is tracked
by the user or not."""
tracked = set()
if user and user.is_authenticated:
clist = CommunityList.objects.filter(user=user).first()
if clist:
tracked.update... | 5,344,533 |
def korrektur(wordfile, datei):
"""Patch aus korrigierten Einträgen"""
if not datei:
datei = 'korrektur.todo'
teste_datei(datei)
korrekturen = {}
for line in open(datei, 'r'):
if line.startswith('#'):
continue
# Dekodieren, Zeilenende entfernen
line = li... | 5,344,534 |
def read_number(dtype, prompt='', floor=None, ceil=None, repeat=False):
""" Reads a number within specified bounds. """
while True:
try:
result = dtype(input(prompt))
if floor is not None and result < floor:
raise ValueError(f'Number must be no less than... | 5,344,535 |
def dem_adjust(
da_elevtn: xr.DataArray,
da_flwdir: xr.DataArray,
da_rivmsk: Optional[xr.DataArray] = None,
flwdir: Optional[pyflwdir.FlwdirRaster] = None,
connectivity: int = 4,
river_d8: bool = False,
logger=logger,
) -> xr.DataArray:
"""Returns hydrologically conditioned elevation.
... | 5,344,536 |
def trainModel(label,bestModel,obs,trainSet,testSet,modelgrid,cv,optMetric='auc'):
""" Train a message classification model """
from copy import copy
from numpy import zeros, unique
from itertools import product
pred = zeros(len(obs))
fullpred = zeros((len(obs),len(unique(obs))))
mode... | 5,344,537 |
def vm_deploy(vm, force_stop=False):
"""
Internal API call used for finishing VM deploy;
Actually cleaning the json and starting the VM.
"""
if force_stop: # VM is running without OS -> stop
cmd = 'vmadm stop %s -F >/dev/null 2>/dev/null; vmadm get %s 2>/dev/null' % (vm.uuid, vm.uuid)
e... | 5,344,538 |
def get_cpuinfo():
"""Returns the flags of the processor."""
if sys.platform == 'darwin':
return platforms.osx.get_cpuinfo()
if sys.platform == 'win32':
return platforms.win.get_cpuinfo()
if sys.platform == 'linux2':
return platforms.linux.get_cpuinfo()
return {} | 5,344,539 |
def previous_analytics(request, package, id):
"""
Return a list of previous analytics for the given package.
Only shows analytics which the user can access.
Also limits to the last 100 of them!
"""
context = []
profile = request.user.get_profile()
#TODO: this code block needs to... | 5,344,540 |
def get_monitor_value(image, monitor_key):
"""Return the monitor value from an image using an header key.
:param fabio.fabioimage.FabioImage image: Image containing the header
:param str monitor_key: Key containing the monitor
:return: returns the monitor else returns 1.0
:rtype: float
"""
... | 5,344,541 |
def resources(request):
"""
Page for accessing RMG resources, including papers and presentations
"""
folder = os.path.join(settings.STATIC_ROOT, 'presentations')
files = []
if os.path.isdir(folder):
files = os.listdir(folder)
toRemove = []
for f in files:
if ... | 5,344,542 |
def plot_data(t, r, v, a, j, unit, legenda, ax):
"""Plot kinematics of minimum jerk trajectories."""
try:
import matplotlib.pyplot as plt
except ImportError:
print('matplotlib is not available.')
return
if ax is None:
_, ax = plt.subplots(1, 4, sharex=True, figsize=(10,... | 5,344,543 |
def cmd(ctx, url, key, secret, whitelist=None, **kwargs):
"""Get assets using a saved query."""
client = ctx.obj.start_client(url=url, key=key, secret=secret)
kwargs["report_software_whitelist"] = load_whitelist(whitelist)
p_grp = ctx.parent.command.name
apiobj = getattr(client, p_grp)
with ct... | 5,344,544 |
def _log_histograms(writer: tensorboard.SummaryWriter, model: models.NerfModel,
state: model_utils.TrainState):
"""Log histograms to Tensorboard."""
step = int(state.optimizer.state.step)
params = state.optimizer.target['model']
if 'appearance_encoder' in params:
embeddings = params['app... | 5,344,545 |
def default_thread_index (value, threads):
"""
find index in threads array value
:param value:
:param threads:
:return:
"""
value_index = threads.index(value)
return value_index | 5,344,546 |
def _create_sky_model(sky_file, ra, dec, stokes_i_flux):
"""Create an OSKAR sky model.
Args:
sky_file (string): filename path of the sky model being created.
ra (float list): Right ascension, in degrees, of sources to put in the
sky model.
dec (float list): Declination, in d... | 5,344,547 |
def delay_fast_forward_until_set(event):
"""adds the given event to a set that will delay fast_forwards until they are set (does not need to be removed, as it's a weak ref)"""
_virtual_time_state.acquire()
try:
_fast_forward_delay_events.add(event)
finally:
_virtual_time_state.release() | 5,344,548 |
def new_things(url):
"""Attempts to register new things on the directory
Takes 1 argument:
url - URL containing thing descriptions to register
"""
response = requests.post('{}/things/register_url'.format(settings.THING_DIRECTORY_HOST), headers={
'Authorization': settings.THING_DIRECTORY... | 5,344,549 |
def isID(value):
"""Checks if value looks like a Ulysses ID; i.e. is 22 char long.
Not an exact science; but good enougth to prevent most mistakes.
"""
return len(value) == 22 | 5,344,550 |
def tool_on_path(tool: str) -> str:
"""
Helper function to determine if a given tool is on the user's PATH variable. Wraps around
runspv.tool_on_path().
:param tool: the tool's filename to look for.
:return: the path of the tool, else ToolNotOnPathError if the tool isn't on the PATH.
"""
ret... | 5,344,551 |
def DefineDecode(i, n, invert=False):
"""
Decode the n-bit number i.
@return: 1 if the n-bit input equals i
"""
class _Decode(Circuit):
name = 'Decode_{}_{}'.format(i, n)
IO = ['I', In(Bits[ n ]), 'O', Out(Bit)]
@classmethod
def definition(io):
if n <= ... | 5,344,552 |
def absent(name, database, **client_args):
"""
Ensure that given continuous query is absent.
name
Name of the continuous query to remove.
database
Name of the database that the continuous query was defined on.
"""
ret = {
"name": name,
"changes": {},
"re... | 5,344,553 |
def save_graph(path, G, pos):
"""
Saves a networkx graph in a json file and its nodal layoput for plotting in npz to be loaded
later with `nnc.helpers.graph_helpers.load_graph) method.
:param path: The path to the file
:param G: The `networkx.Graph` object
:param pos: The position dictionary wit... | 5,344,554 |
def get_ads(client, customer_id, new_ad_resource_names):
"""Retrieves a google.ads.google_ads.v4.types.AdGroupAd instance.
Args:
client: A google.ads.google_ads.client.GoogleAdsClient instanc e.
customer_id: (str) Customer ID associated with the account.
new_ad_resource_names: (str) Re... | 5,344,555 |
def corrfact_vapor_rosolem(h, h_ref=None, const=0.0054):
"""Correction factor for vapor correction from absolute humidity (g/m3).
The equation was suggested by Rosolem et al. (2013).
If no reference value for absolute humidity ``h_ref`` is provided,
the average value will be used.
Paramet... | 5,344,556 |
def sine_ease_out(p):
"""Modeled after quarter-cycle of sine wave (different phase)"""
return sin(p * tau) | 5,344,557 |
def _extract_codes_from_element_text(dataset, parent_el_xpath, condition=None): # pylint: disable=invalid-name
"""Extract codes for checking from a Dataset. The codes are being extracted from element text.
Args:
dataset (iati.data.Dataset): The Dataset to check Codelist values within.
parent_e... | 5,344,558 |
def test_gram_intercept_constrained_projection():
"""Constrained projection should error"""
X = jax.random.uniform(random.generate_key(), shape=(5, 10))
XTX = OnlineGram(10)
XTX.update(X)
with pytest.raises(ValueError):
XTX.fit_intercept(projection=1, input_dim=2) | 5,344,559 |
def rotate_im(img, angle, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, value=None):
"""Rotate the image.
Rotate the image such that the rotated image is enclosed inside the tightest
rectangle. The area not occupied by the pixels of the original image is colored
black.
Parame... | 5,344,560 |
def list_modules(curdir=CURDIR, pattern=MOD_FILENAME_RE):
"""List names from {ok,ng}*.py.
"""
return sorted(
m.name.replace('.py', '')
for m in curdir.glob('*.py') if pattern.match(m.name)
) | 5,344,561 |
def save_model_h5py(model, save_path="model_save"):
"""saves a keras model to h5py file (also makes the 'model_save/' directory if it wasn't there before)
:param model: model to save
:param save_path: path where to save model, staring from the directory of the simulation (default "model_save")"""
# directory
if ... | 5,344,562 |
def main(argv=None):
"""Process the job."""
argv = sys.argv[1:] if argv is None else argv
cyclonedx_lint.main(argv) | 5,344,563 |
def encode_set_validator_config_and_reconfigure_script(
validator_account: AccountAddress,
consensus_pubkey: bytes,
validator_network_addresses: bytes,
fullnode_network_addresses: bytes,
) -> Script:
"""# Summary
Updates a validator's configuration, and triggers a reconfiguration of the system t... | 5,344,564 |
def _do_ecf_reference_data_import(
import_method,
widget,
logwidget=None,
specification_items=None,
ecfdate=None,
datecontrol=None,
):
"""Import a new ECF club file.
widget - the manager object for the ecf data import tab
"""
ecffile = widget.datagrid.get_data_source().dbhome
... | 5,344,565 |
def ast_operators(node):
"""Return a set of all operators and calls in the given AST, or return an error if any are invalid."""
if isinstance(node, (ast.Name, ast.Constant)):
return set()
elif isinstance(node, ast.BinOp):
return {type(node.op)} | ast_operators(node.left) | ast_operators(node... | 5,344,566 |
def validate_k(data, k):
"""
Validates that the number of folds is valid.
:param pd.DataFrame data
:param int k
:raises InvalidFoldError: if the number of folds is not supported by the
data
"""
if k > min(data.shape):
raise InvalidFoldError() | 5,344,567 |
async def async_turn_on(hass, entity_id, speed=None):
"""Turn fan on."""
data = {
key: value for key, value in [
(ATTR_ENTITY_ID, entity_id),
(ATTR_SPEED, speed),
] if value is not None
}
await hass.services.async_call(
DOMAIN, SERVICE_TURN_ON, data, bloc... | 5,344,568 |
def dump_json(containers):
"""
Function to output the autoprotocol json instructions
"""
for key in containers:
with open("json\\" + containers[key].barcode + ".json", 'w') as json_file:
json.dump(containers[key].p.as_dict(), json_file, indent=2) | 5,344,569 |
def calibrate_clock(out, tolerance=0.002, dcor=False):
"""\
currently for F2xx only:
recalculate the clock calibration values and write them to the flash.
"""
device = get_msp430_type() >> 8
variables = {}
if device == 0xf2:
# first read the segment form the device, so that only the ... | 5,344,570 |
def print_dtypes(title: str, ds: pd.Series, show_numbers: bool = True) -> None:
""" displays dataframe dtypes (pd.Series) to console output """
method = f"{inspect.currentframe().f_code.co_name}()"
if isinstance(ds, pd.Series):
count = 0
print(f"\n{method} {title}")
for key, val in d... | 5,344,571 |
def emit_trinop(v1, v2, v3, v4, v5):
"""Emit trin op."""
for ii in range(0, flag_copies):
sys.stdout.write(" %s%d = (%s%d - %s%d) ^ "
"(%s%d + %s%d) ;\n" % (v1, ii, v2, ii,
v3, ii, v4, ii,
v5, ii)) | 5,344,572 |
def get_rejection_listings(username):
"""
Get Rejection Listings for a user
Args:
username (str): username for user
"""
activities = models.ListingActivity.objects.for_user(username).filter(
action=models.ListingActivity.REJECTED)
return activities | 5,344,573 |
def quadratic_weighted_kappa(y_true, y_pred):
"""
QWK (Quadratic Weighted Kappa) Score
Args:
y_true:
target array.
y_pred:
predict array. must be a discrete format.
Returns:
QWK score
"""
return cohen_kappa_score(y_true, y_pred, weights='quadrati... | 5,344,574 |
def statistika():
"""Posodobi podatke in preusmeri na statistika.html"""
check_user_id()
data_manager.load_data_from_file()
data_manager.data_for_stats()
return bottle.template("statistika.html", data_manager=data_manager) | 5,344,575 |
def value_iter_run(test_episode_num=1_000_000):
""" Run value iteration algorithm. """
model = ValueIteration(env)
model.value_iteration()
model.test_policy(episode_num=test_episode_num)
model.save_fig(fig_path)
model.save_result(log_path) | 5,344,576 |
def decrement(x):
"""Given a number x, returns x - 1 unless that would be less than
zero, in which case returns 0."""
x -= 1
if x < 0:
return 0
else:
return x | 5,344,577 |
def simple_page(httpserver, browser, simple_page_content):
"""Serve simple html page."""
httpserver.serve_content(
simple_page_content, code=200, headers={'Content-Type': 'text/html'})
browser.visit(httpserver.url) | 5,344,578 |
def get_dagmaf(maf: msa.Maf) -> DAGMaf.DAGMaf:
"""Converts MAF to DagMaf.
Args:
maf: MAF to be converted.
Returns:
DagMaf built from the MAF.
"""
sorted_blocks = sort_mafblocks(maf.filecontent)
dagmafnodes = [
DAGMaf.DAGMafNode(block_id=b.id,
... | 5,344,579 |
def optdat10(area,lpdva,ndvab,nglb):
"""Fornece dados para a otimizacao"""
# Tipo de funcao objetivo: tpobj==1 ---Peso
# tpobj==2 ---Energia
# tpobj==3 ---Máxima tensão
# tpobj==... | 5,344,580 |
def rotvec2quat(vec):
"""
A rotation vector is a 3 dimensional vector which is
co-directional to the axis of rotation and whose
norm gives the angle of rotation (in radians).
Args:
vec (list or np.ndarray): a rotational vector. Its norm
represents the angle of rotation.
Ret... | 5,344,581 |
def print_properties(props):
"""Print a ResourceGroup properties instance."""
if props and props.provisioning_state:
print("\tProperties:")
print("\t\tProvisioning State: {}".format(props.provisioning_state))
print("\n\n") | 5,344,582 |
def generate_pop(pop_size, length):
"""
初始化种群
:param pop_size: 种群容量
:param length: 编码长度
:return bin_population: 二进制编码种群
"""
decim_population = np.random.randint(0, 2**length-1, pop_size)
print(decim_population)
bin_population = [('{:0%sb}'%length).format(x) for x in decim_population]... | 5,344,583 |
def identifyAltIsoformsProteinComp(probeset_gene_db,species,array_type,protein_domain_db,compare_all_features,data_type):
""" This function is used by the module IdentifyAltIsoforms to run 'characterizeProteinLevelExonChanges'"""
global protein_ft_db; protein_ft_db = protein_domain_db; protein_domain_db=[]
... | 5,344,584 |
def prepare_argument_parser():
"""
Set up the argument parser for the different commands.
Return:
Configured ArgumentParser object.
"""
argument_parser = argparse.ArgumentParser(
description='Build source code libraries from modules.')
argument_parser.add_argument(
'-r',
... | 5,344,585 |
def CountClusterSizes(clusterLabels):
""" This function takes the labels produced by spectral clustering (or
other clustering algorithm) and counts the members in each cluster.
This is primarily to see the distribution of cluster sizes over all
windows, particularly to see if there sin... | 5,344,586 |
def solver_problem1(digits_list):
"""input digits and return numbers that 1, 4, 7, 8 occurs"""
cnt = 0
for digits in digits_list:
for d in digits:
if len(d) in [2, 3, 4, 7]:
cnt += 1
return cnt | 5,344,587 |
def spam_dotprods(rhoVecs, povms):
"""SPAM dot products (concatenates POVMS)"""
nEVecs = sum(len(povm) for povm in povms)
ret = _np.empty((len(rhoVecs), nEVecs), 'd')
for i, rhoVec in enumerate(rhoVecs):
j = 0
for povm in povms:
for EVec in povm.values():
ret[... | 5,344,588 |
def is_just_monitoring_error(unique_message):
"""
Return True if the unique_message is an intentional error just for
monitoring (meaning that it contains the one of the
JUST_MONITORING_ERROR_MARKERS somewhere in the exc_text)
"""
if sys.version_info == 2:
exc_text = unicode(unique_messag... | 5,344,589 |
def get_chi_atom_indices():
"""Returns atom indices needed to compute chi angles for all residue types.
Returns:
A tensor of shape [residue_types=21, chis=4, atoms=4]. The residue types are
in the order specified in rc.restypes + unknown residue type
at the end. For chi angles which are not d... | 5,344,590 |
def test_part1() -> None:
"""
Examples for Part 1.
"""
initial = State(0, "...........", ("BA", "CD", "BC", "DA"), 2)
assert (
State.from_input(
"\n".join(
(
"#############",
"#...........#",
"###B#C#B#D#... | 5,344,591 |
def get_all_device_stats():
"""Obtain and return statistics for all attached devices."""
devices = get_devices()
stats = {}
for serial in devices:
model, device_stats = get_device_stats(serial)
if not stats.get(model):
stats[model] = {}
stats[model][serial] = device_stats
return stats | 5,344,592 |
def geojson2shp(in_filename, out_filename, source_epsg, target_epsg, sigevent_url):
"""
Converts GeoJSON into Esri Shapefile.
Arguments:
in_filename -- the input GeoJSON
out_filename -- the output Shapefile
source_epsg -- the EPSG code of source file
target_epsg -- the EPSG c... | 5,344,593 |
def plot_coefs(coefficients, nclasses):
"""
Plot the coefficients for each label
coefficients: output from clf.coef_
nclasses: total number of possible classes
"""
scale = np.max(np.abs(coefficients))
p = plt.figure(figsize=(25, 5))
for i in range(nclasses):
p ... | 5,344,594 |
def timeleft(cli, nick, chan, rest):
"""Returns the time left until the next day/night transition."""
if (chan != nick and var.LAST_TIME and
var.LAST_TIME + timedelta(seconds=var.TIME_RATE_LIMIT) > datetime.now()):
cli.notice(nick, ("This command is rate-limited. Please wait a while "
... | 5,344,595 |
def shade_pixels(shader):
"""Set all pixels using a pixel shader style function
:param pixels: A function which accepts the x and y positions of a pixel and returns values r, g and b
For example, this would be synonymous to clear::
set_pixels(lambda x, y: return 0,0,0)
Or perhaps we want to ... | 5,344,596 |
def infect():
"""Return a function that calls the infect endpoint on app."""
def inner(users, qs):
app.debug = True
with app.test_client() as client:
headers = {'Content-Type': 'application/json'}
data = json.dumps(users)
rv = client.post('/infect?{0}'.format(... | 5,344,597 |
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['description'] = """This plot shows the number of days with a high
temperature at or above a given threshold. You can optionally generate
this plot for the year to date period... | 5,344,598 |
def calc_cost_of_buying(count, price):
"""株を買うのに必要なコストと手数料を計算
"""
subtotal = int(count * price)
fee = calc_fee(subtotal)
return subtotal + fee, fee | 5,344,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.