content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def qe2xtl(fin, fout=None, title=None):
"""converts a QE input to XTL out file"""
if fout is None:
fout = '{0}.xtl'.format(fin.split('.')[0])
dats = read_qe_in(fin)
print('QE input: {0}\n'.format(fin))
if title: dats.update({'title' : title})
xtl_tmpl = Template('''
TITLE ${title}\n\
CEL... | 5,313,300 |
def response_for_created_event(event, status_code):
"""
Method returning the response when an event has been successfully created.
:param status_code:
:param event: Event
:return: Http Response
"""
return make_response(jsonify({'event' : {
'event_id': event.event_id,
'event_n... | 5,313,301 |
async def initialized(server: GalaxyToolsLanguageServer, params: InitializeParams) -> None:
"""Loads the client configuration after initialization."""
await _load_client_config_async(server)
server.service.set_workspace(server.workspace) | 5,313,302 |
def weightedLeastSquares(X, Y, W):
"""
solve using the normal equations with no manipulation
"""
t0 = time.time()
### check the input
if checkMatrixSizes(X, Y) is False:
return None
### solve it
XTW = numpy.transpose(X)*W
XTWX = numpy.dot(XTW, X)
if numpy.linalg.det(XTWX) == 0:
apDisplay.printWarning("Sin... | 5,313,303 |
def question_first_sentence(database_connection, question):
"""
return the id, answer, and first sentence of questions in a set of categories
"""
c = database_connection.cursor()
command = 'select raw from text where question=%i' % question
c.execute(command)
for ii, in c:
return ii | 5,313,304 |
def encode_scrambled(corpus: Corpus = Corpus(),
annotations: ExportAnnotations = ExportAnnotations("cwb.annotations", is_input=False),
source_annotations: SourceAnnotations = SourceAnnotations("cwb.source_annotations"),
docs: AllDocuments = AllDocuments(),
... | 5,313,305 |
def help_search():
"""Search help guide."""
# Default to rendering english page if locale page not found.
locale = get_locale()
return render_template([
f"invenio_app_rdm/help/search.{locale}.html",
"invenio_app_rdm/help/search.en.html",
]) | 5,313,306 |
def sum_of_vals(vals):
"""
:param vals: an iterable such as list
:return: sum of the values from the iterable
"""
sum = 0
for val in vals:
sum += val
return sum | 5,313,307 |
def predict_all_attrs(
img: tf.Tensor, model_list: List[tf.keras.Model]) -> List[np.int32]:
"""Predicts all attributes for a given image."""
pred_list = []
for model in model_list[:-1]:
pred = np.argmax(model(img))
pred_list.append(pred)
pred = np.round(7. * model_list[-1](img) + 7)[... | 5,313,308 |
def save_info(info,folder_name):
"""saves the information about genename and correspoding SectionDataSetID as csv """
file_path=os.path.join(folder_name,"ABI-genes-datasetid.csv")
f = open(file_path,"w+")
for gene in info:
f.write('\n')
f.write(gene)
for gene_id in info[gene]:
f.write("," + str(gene_id)) | 5,313,309 |
def _txt_header_whitespace_check(gtfsfiles_to_use,
csv_rootpath=os.path.join(
config.settings.data_folder,
'gtfsfeed_text')):
"""
Standardize all text files inside a GTFS feed to remove whitespace
in h... | 5,313,310 |
def main(argv=sys.argv) -> None:
"""Update salaries."""
argparse.ArgumentParser(usage=("pipenv run python fetch_config_values.py"))
options = Options()
options.headless = True
print("Starting Firefox and loading up config.yml")
with webdriver.Firefox(options=options) as driver:
with o... | 5,313,311 |
def recognize_timestamp(line):
"""Handle a timestamp comment line."""
# This is a pukey way to handle this imported constant ...
# I bet there's a better way. Figure it out.
global timestamp_pattern
if re.match(timestamp_pattern, line):
return True
else:
return False | 5,313,312 |
def test_compare_returns_0_w_no_vector(
searcher: SimilaritySearcher, model: Language
) -> None:
"""Checks compare returns 0 when vector does not exist for span/token."""
assert searcher.compare(model("spaczz"), model("python")) == 0 | 5,313,313 |
def admin_email_address_has_approved_domain(email_address):
"""
Check the admin's email address is from a whitelisted domain
:param email_address: string
:return: boolean
"""
return email_address.split('@')[-1] in current_app.config.get('DM_ALLOWED_ADMIN_DOMAINS', []) | 5,313,314 |
def print_json(json_dict=None, _json_is_first=False, _json_is_last=False,
**json_parts):
""" line-wise print of json.dumps(json2ascii(..)) with options and indent+1
can use in two ways:
(1) print_json(some_dict)
(2) print_json(key1=value1, key2=value2, ...)
:param bool _json_is_firs... | 5,313,315 |
def get_replica_context() -> ReplicaContext:
"""If called from a deployment, returns the deployment and replica tag.
A replica tag uniquely identifies a single replica for a Ray Serve
deployment at runtime. Replica tags are of the form
`<deployment_name>#<random letters>`.
Raises:
RayServ... | 5,313,316 |
def printTransactions(account):
"""
The print_transaction function is responsible for presenting transaction details to end user.
:param account: The JSON decoded account and transaction data
:return: Nothing
"""
logging.info('Printing account and transaction data to console.')
printHeader(a... | 5,313,317 |
def write_pickle(var, filepath, use_compression=None):
""" Writes a variable to a pickle on disk.
Parameters
----------
var : object
the variable to write to disk
filepath : str
filepath
use_compression : bool
whether or not the file ws compressed. Default is to use
... | 5,313,318 |
def test_build_googleapi_params():
""" Check correct params are used """
import requests
with patch.object(requests,'get') as mock_get:
mock_get.return_value = mock_response = MagicMock()
mock_response.content = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00'\
b'\x00\x00\x01... | 5,313,319 |
def bash_profile():
"""
Fixes stuff that non-interactive shells don't do automatically.
"""
with prefix('export HOME={}'.format(project_home())), \
prefix('source {}/.bash_profile'.format(project_home())):
yield | 5,313,320 |
def stratify(data, classes, ratios, one_hot=False):
"""Stratifying procedure. Borrowed from https://vict0rs.ch/2018/05/24/sample-multilabel-dataset/
data is a list of lists: a list of labels, for each sample.
Each sample's labels should be ints, if they are one-hot encoded, use one_hot=True
cla... | 5,313,321 |
def handle_request(fun):
"""
Exception treatment for the REST API calls
"""
def wrapper(self, *args, **kwargs):
"""
We raise an exception when
the code on the client side fails
Server side errors are taken care of
through response codes
"""
try:
... | 5,313,322 |
def compDesc(smiles):
"""
:param smiles:
:return:
"""
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import Chem
from rdkit.Chem import Descriptors
descriptors = list(np.array(Descriptors._descList)[:, 0])
calculator = MoleculeDescriptors.MolecularDescriptorCalculat... | 5,313,323 |
def convert_F_units(F, lbda, in_unit='cgs', out_unit='si'):
"""
Function to convert Flux density between [ergs s-1 cm-2 um-1],
[W m-2 um-1] and [Jy].
Parameters
----------
F: float or 1d array
Flux
lbda: float or 1d array
Wavelength of the flux (in um)
in_unit: str, opt... | 5,313,324 |
def test_set_valid_per_pages(clear_sess_params):
"""call to fix_pages returns true for valid ranges"""
assert fix_pages(per_page=15)
assert sess.params["per_page"] == 15
assert sess.params["page"] == 1 | 5,313,325 |
def print_cards():
""" prints the cards of the player """
for i in range(len(p_cards)):
print(i,':',p_cards[i]) | 5,313,326 |
def tiny_maze_search(problem):
"""Return a sequence of moves that solves tiny_maze.
For any other maze, the sequence of moves will be incorrect,
so only use this for tiny_maze.
"""
from game import Directions
s = Directions.SOUTH
w = Directions.WEST
return [s, s, w, s, w, w, s, w] | 5,313,327 |
def export_metadata(isamAppliance, name, filename, check_mode=False, force=False):
"""
Export a federation
"""
ret_obj = search(isamAppliance, name)
fed_id = ret_obj['data']
if fed_id == {}:
from ibmsecurity.appliance.ibmappliance import IBMError
raise IBMError("999", "Cannot exp... | 5,313,328 |
def defocus(elt):
"""Remove focus from a given element."""
get_driver(elt).execute_script("arguments[0].blur()", elt) | 5,313,329 |
def display_unknown_plugins(unknown_plugins):
"""Print an error message when one or more plugins are unknown.
:param list unknown_plugins: list of unknown plugins
"""
# at least one of the plugins does not exist
tools.stderr(utils.get_many_text(
unknown_plugins,
one='No plugin named... | 5,313,330 |
def wkt_of_any(string):
"""Wkt of user input"""
out = osr.GetUserInputAsWKT(string)
if isinstance(out, str):
return out
else:
prj = None
with Env(_osgeo_use_exceptions=False):
gdal_ds = gdal.OpenEx(string, conv.of_of_str('raster'))
if gdal_ds is not None:
... | 5,313,331 |
def getDatial(request):
"""输入文章id,返回文章的metadata。代表用户点击,记录session
Args:
request (GET): arxivID:String,article的ID
Returns:
json: 该article的metadata,调用ORM接口查数据库
"""
try:
ret_dict = {}
arxiv_id = request.GET.get("arxivID")
arxiv_doc = get_arxiv_document_by_id(ar... | 5,313,332 |
def trajectory_overlap(gt_trajs, pred_traj):
"""
Calculate overlap among trajectories
:param gt_trajs:
:param pred_traj:
:param thresh_s:
:return:
"""
max_overlap = 0
max_index = 0
thresh_s = [0.5, 0.7, 0.9]
for t, gt_traj in enumerate(gt_trajs):
top1, top2, top3 = 0,... | 5,313,333 |
def Q_013_1():
""" 13. col1.txtとcol2.txtをマージ
12で作ったcol1.txtとcol2.txtを結合し,
元のファイルの1列目と2列目をタブ区切りで並べたテキストファイルを作成せよ.
"""
with open('data/col1.txt', 'r') as col1_f, \
open('data/col2.txt', 'r') as col2_f, \
open('data/col_merge.txt', 'w') as merge_f:
for line1, line2 in zip(col... | 5,313,334 |
def rename_example_subfolder_files(library_dir):
"""Moves source files in example subfolders to equivalents at root."""
search_path = os.path.join(library_dir, 'examples/*/*', '*.cpp')
for cpp_path in glob.glob(search_path):
cpp_dir = os.path.dirname(cpp_path)
cpp_base = os.path.basename(cpp_path)
new... | 5,313,335 |
def adding_detail(request):
"""Контроллер изменение деталей из расчета"""
calc_id = request.POST.get("calc_id")
crud_details_in_calc(request)
return JsonResponse(current_details_in_calc_and_main_calc_info(calc_id=calc_id)) | 5,313,336 |
def create_futures_list(futures, executor):
"""creates a new FuturesList an initiates its attrs"""
fl = FuturesList(futures)
fl.config = executor.config
fl.executor = executor
return fl | 5,313,337 |
def unittestResultsToXml(*, name='launch_test', test_results={}):
"""
Serialize multiple unittest.TestResult objects into an XML document.
A testSuites element will be the root element of the document.
"""
# The test_suites element is the top level of the XML result.
# launch_test results conta... | 5,313,338 |
def time_sa_to_s(t, clock_freq):
"""
convert from time in samples to time in seconds
"""
return float(t / clock_freq) | 5,313,339 |
def get_raw_containers():
"""
Runs the shell command to get the container all data from Docker.
:returns: The raw information from the `docker ps` command.
:rtype: str
"""
cmds = ["docker", "ps", "-a"]
out = subprocess.Popen(
cmds,
stdout=subprocess.PIPE,
stderr=subp... | 5,313,340 |
def create_service_account(account):
"""
create service account, change password and set permissions
"""
__exec_cmd('sudo adduser %s' % account)
__exec_cmd('sudo passwd %s' % account) | 5,313,341 |
def create_positions(ranges, numpts):
"""Create a sequence of np.prod(nupmts) over the ranges.
Args:
ranges: list of 2-tuples, each tuple being [min, max] of a numerical range.
numpts: list of integers -- the number of equally spaced points
between [min, max] including the ... | 5,313,342 |
def mod(ctx, arg):
"""
"""
action = ctx.copy_last_action()
return action | 5,313,343 |
def kdcompare(r, p, depth):
"""
Returns the branch of searching on a k-d tree
Input
r: root
p: point
depth : starting depth of search
Output
A value of -1 (left branch), or 1 (right)
"""
k = len(p)
dim = depth%k
if p[dim] <= r.point[dim]:
return -1
... | 5,313,344 |
def get_props(paths):
"""Return a hash of hashes of props for PATHS, using the svn client. Convert
each embedded end-of-line to a single LF character."""
# It's not kosher to look inside .svn/ and try to read the internal
# property storage format. Instead, we use 'svn proplist'. After
# all, this is th... | 5,313,345 |
def _calc_centers(graph, X, labelling, method='nearest'):
"""Return the new centers
graph : sparse matrix
Indicates the graph constructed from X
X : ndarray
Original Data
labelling: 1d array
The labelling of the vertices
method : one of 'nearest', 'floyd_warshall', 'eros... | 5,313,346 |
def greaco_latin_square(k, factor_1_labels=None, factor_2_labels=None, seed=None):
""" Creates a k by k Greaco-Latin Square Design
A greaco-latin square is a design comprised of two orthogonal latin
squares. Note, there are no designs for k = 6.
Arguments:
k: the number of treatments.
... | 5,313,347 |
def deep_set(deep_key, dictionary, value, sep=':'):
"""Sets through multiple dictionary levels, splitting
the compound key using the specified separator.
"""
keys = deep_key.split(sep)
last_key = keys.pop()
while keys:
key = keys.pop(0)
if key not in dictionary:
dicti... | 5,313,348 |
def get_poly_clock(params_array,section_str):
"""
Get list with poly from params array and section string.
Clock correction.
Parameters
----------
params_array : list
information from delay model ini file (see lib_ini_files.py).
section_str : str
section of the ini f... | 5,313,349 |
def hash_to_G2(data: bytes) -> G2:
"""Hashes a byte string to an element in G2."""
return G2(_relic.hash_to_G2(data)) | 5,313,350 |
def test_atomic_base64_binary_enumeration_1_nistxml_sv_iv_atomic_base64_binary_enumeration_2_1(mode, save_output, output_format):
"""
Type atomic/base64Binary is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/base64Binary/Schema+Instance/NISTSchema-SV-IV-atomic-bas... | 5,313,351 |
def build_filter_stack(stack, options):
"""Setup and return a filter stack.
Args:
stack: :class:`~sqlparse.filters.FilterStack` instance
options: Dictionary with options validated by validate_options.
"""
# Token filter
if options.get('keyword_case'):
stack.preprocess.a... | 5,313,352 |
def get_nuclear_mgc(data, meta):
"""
Determines the going marginal_cost for this technology
@ In, data, dict, request for data
@ In, meta, dict, state information
@ Out, data, dict, filled data
@ In, meta, dict, state information
"""
return {'reference_price': get_trunc_mgc(trunc, meta, 'nucle... | 5,313,353 |
def efficientnet_b1(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> EfficientNet:
"""
Constructs a EfficientNet B1 architecture from
`"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks" <https://arxiv.org/abs/1905.11946>`_.
Args:
pretrained (bool): If T... | 5,313,354 |
def StepToGeom_MakeParabola2d_Convert(*args):
"""
:param SC:
:type SC: Handle_StepGeom_Parabola &
:param CC:
:type CC: Handle_Geom2d_Parabola &
:rtype: bool
"""
return _StepToGeom.StepToGeom_MakeParabola2d_Convert(*args) | 5,313,355 |
def read_corpus(file_path, source):
""" Read file, where each sentence is dilineated by a `\n`.
@param file_path (str): path to file containing corpus
@param source (str): "tgt" or "src" indicating whether text
is of the source language or target language
"""
data = []
for line in open(f... | 5,313,356 |
async def test_site_move_verifier_do_work_yes_results(config, mocker):
"""Test that _do_work keeps working until the LTA DB has no work."""
logger_mock = mocker.MagicMock()
dwc_mock = mocker.patch("lta.site_move_verifier.SiteMoveVerifier._do_work_claim", new_callable=AsyncMock)
dwc_mock.side_effect = [T... | 5,313,357 |
def del_find(data, ID, cur_id, intlist, num_start):
"""ID - int ID человека, чей лог меняется
cur_id - list id высвеченных данных лога
intList - list номеров, введенных пользователем
return is_change, inter
is_change - bool были ли осуществлены изменения
"""
cur_index = data_ind... | 5,313,358 |
def es(app):
"""Provide elasticsearch access."""
app.config.update(dict(
SEARCH_AUTOINDEX=[],
))
InvenioSearch(app)
with app.app_context():
try:
list(current_search.create())
except RequestError:
list(current_search.delete(ignore=[404]))
li... | 5,313,359 |
def rechunk_to_single_chunk_if_more_than_one_chunk_along_dim(ds, dim):
"""Rechunk an xarray object more than one chunk along dim."""
if dask.is_dask_collection(ds) and dim in ds.chunks:
if isinstance(ds, xr.Dataset):
nchunks = len(ds.chunks[dim])
elif isinstance(ds, xr.DataArray):
... | 5,313,360 |
def publish(ctx, dry_run=True):
"""
Upload built package to pypi
"""
repo_url = "--repository-url https://test.pypi.org/legacy/" if dry_run else ""
ctx.run(f"twine upload --skip-existing {repo_url} dist/*") | 5,313,361 |
def make_config_file(file):
"""Make the default configuration file"""
config = default_config()
with open(file, 'w') as f:
config.write(f) | 5,313,362 |
def update_payin(
db, payin_id, remote_id, status, error,
amount_settled=None, fee=None, intent_id=None, refunded_amount=None,
):
"""Update the status and other attributes of a charge.
Args:
payin_id (int): the ID of the charge in our database
remote_id (str): the ID of the charge in th... | 5,313,363 |
def stack(x, num_block, size, stride, stack_index, block=basic):
""" A stack of num_block blocks. """
for block_index, s in enumerate([stride]+[1]*(num_block-1)):
x = block(x, size, s, stack_index, block_index)
return x | 5,313,364 |
def twist2msg(twist):
"""
Converts a 6x1 twist vector into a geometry_msgs/Twist message
:type twist: numpy.array
:param twist: 6x1 twist matrix
:rtype: geometry_msgs.msg.Twist
:return The ROS Twist message
"""
twist2=np.reshape(twist, (6,))
return Twist(Vector3(twist2[3], twist... | 5,313,365 |
def touch_update_stamp():
"""Touches PIPENV_CACHE_DIR/.pipenv_update_check"""
mkdir_p(PIPENV_CACHE_DIR)
p = os.sep.join((PIPENV_CACHE_DIR, '.pipenv_update_check'))
try:
os.utime(p, None)
except OSError:
with open(p, 'w') as fh:
fh.write('') | 5,313,366 |
def test_cmd_str_with_spaces_in_path():
"""Single command string works with spaces in path."""
cmd = get_cmd('tests/testfiles/cmds/"file with space.sh"',
r'tests\testfiles\cmds\file with space.bat')
context = Context({'a': 'one two',
'd': cmd,
... | 5,313,367 |
def z1FromAngles(wavelength, stt, om, chi, phi):
"""
Calculate the scattering vector z1 from angles
@param wavelength
@param om angle in radians
@param chi angle in radians
@param phi angle in radians
@return The z1 vector
"""
th = stt/2.
z4 = np.array([
(2. * sin(th) * c... | 5,313,368 |
def sparqling(sparql_query, libraries, is_basic = True,
no_sequence = False, progress = True):
"""
the function querys "https://synbiohub.org/" for parts
Parameters
----------
path : STRING
Path to Excel Spreadsheet
sparql_query
libraries
is_basic = True,
no_... | 5,313,369 |
def convert_slide_binary_metadata_to_base64(slide: Slide) -> List[Slide]:
"""
Converts all binary data contained in the slide metadata to base64
"""
if slide.metadata is not None:
for metadata_key, metadata_value in slide.metadata.items():
if is_byte_data(metadata_value):
... | 5,313,370 |
def _has_class(domElement, className):
"""
Helper function to test if the provided element has the provided class
"""
return className in domElement.get_attribute('class').split(" ") | 5,313,371 |
def exponent(Cz, C):
"""Recover z such that C ** z == Cz (or equivalently z = log Cz base C).
For exponent(1, 1), arbitrarily choose to return 3"""
return 3 if (Cz == C == 1) else int(round(log(Cz, C))) | 5,313,372 |
def _remove_markers(sentence: str):
"""
removes the lemma markers from a sentence.
:param sentence: a string
:return: a string
"""
return sentence.replace(START_MARKER_TOKEN, '').replace(END_MARKER_TOKEN, '') | 5,313,373 |
def buildGeneTerritories(infile, outfile):
"""build gene territories from protein coding genes.
The territory of a gene is defined as the region of the
gene extended by a certain radius on either end. If the
gene territories of two genes overlap, they are resolved
at the mid-point between the two a... | 5,313,374 |
def product():
"""
Import the test utils module to be able to:
- Create apigee test product
- Update custom scopes
- Update environments
- Update product paths
- Update custom attributes
- Update proxies to the product
- Update cust... | 5,313,375 |
def role_required(role, api=False):
"""flask view decorator implementing role based authorization; does not redirect to login for api views/routes"""
def _role_required(fnc):
@wraps(fnc)
def decorated_view(*args, **kwargs):
if not current_user.is_authenticated:
if ap... | 5,313,376 |
def record_video_and_stills(seconds_per_video, seconds_between_stills):
"""Records video in chunks and still images until space runs out or another
error occurs.
Warning: the seconds calculation will be off if seconds_per_video is not a
multiple of seconds_between_stills.
"""
if seconds_per_vid... | 5,313,377 |
def dock_ligand(ligand: Tuple[str, str], software: str, receptors: List[str],
center: Tuple[float, float, float],
size: Tuple[int, int, int] = (10, 10, 10), ncpu: int = 1,
path: str = '.', extra: Optional[List[str]] = None,
repeats: int = 1) -> List[List[... | 5,313,378 |
def read_cof_file(cof_file, headerlength=12, as_shc_order=True):
"""Get coefficients from a cof-format file.
Read a .cof file and output the n,m, mixed gh arrays (1D)
gh can then be split into separate g,h arrays with convert_gh
Args:
cof_file (str): full path to the file to read
heade... | 5,313,379 |
def get_mlp_models(level_params_list):
"""Get models based on level params and put them into level_algo_kwargs_list."""
level_algo_kwargs_list = []
for level_params in level_params_list:
model_kwargs = level_params["model_kwargs"]
algo_kwargs = deepcopy(level_params["algo_kwargs"])
... | 5,313,380 |
def format_datestamp(datestamp):
"""Format datestamp to an OAI-PMH compliant format.
Parameters
----------
datestamp: datetime.datetime
A datestamp.
Return
------
str:
Formatted datestamp.
"""
return datestamp.strftime('%Y-%m-%dT%H:%M:%SZ') | 5,313,381 |
def encrypt(targetFile: str,
fernet: Fernet,
destroyOriginal: bool = False) -> None:
"""Encrypt a file."""
unencryptedFullPath: str = os.path.abspath(targetFile)
filename: str = os.path.basename(unencryptedFullPath)
dir: str = os.path.dirname(unencryptedFullPath)
print(f"[ENC... | 5,313,382 |
def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10):
"""
Demmel p 312
"""
p = b.copy()
r = b.copy()
x = np.zeros_like(b)
rdotr = r.dot(r)
fmtstr = "%10i %10.3g %10.3g"
titlestr = "%10s %10s %10s"
if verbose: print titlestr % ("iter", "residual norm", "... | 5,313,383 |
def output_handler(data, context):
"""Post-process TensorFlow Serving output before it is returned to the client.
Args:
data (obj): the TensorFlow serving response
context (Context): an object containing request and configuration details
Returns:
(bytes, string): data to return to ... | 5,313,384 |
def create_pdna_net(gdf_nodes, gdf_edges, predistance=500):
"""
Create pandana network to prepare for calculating the accessibility to destinations
The network is comprised of a set of nodes and edges.
Parameters
----------
gdf_nodes: GeoDataFrame
gdf_edges: GeoDataFrame
predis... | 5,313,385 |
def quality_checks_qids(qids_to_relevant_passageids, qids_to_ranked_candidate_passages):
"""Perform quality checks on the dictionaries
Args:
p_qids_to_relevant_passageids (dict): dictionary of query-passage mapping
Dict as read in with load_reference or load_reference_from_stream
p_qids_to_rank... | 5,313,386 |
def make_jinja_element_parser(name_parsers, content):
"""
`name_parsers` must be a list of tag name parsers. For example,
`name_parsers` can be defined as follow in order to parse `if` statements:
name_parsers = [P.string(n) for n in ['if', 'elif', 'else', 'endif']]
"""
if len(name_parsers... | 5,313,387 |
def output_df(outdict, out_file):
"""
compile all modified dataframes for each transcript into a master dataframe
build the output dataframe from the modified dictionary and write this to a file:
"""
cols = ['#chrom', 'source', 'feature', 'chromStart', 'chromEnd', 'score', 'strand', 'frame', 'transcript_id']
colO... | 5,313,388 |
def encode_base64(data: bytes) -> bytes:
""" Creates a url safe base64 representation of an input string, strips
new lines."""
return base64.urlsafe_b64encode(data).replace(b"\n", b"") | 5,313,389 |
def non_none(iterable: Iterable[Optional[_T]]) -> Iterable[_T]:
"""
Make an iterator which contains all elements from *iterable* which are not *None*.
"""
return (x for x in iterable if x is not None) | 5,313,390 |
def generate_inputs(c2e, x0, dipole_type='B1'):
"""."""
folder = 'x0-' + x0 + 'mm/'
init_rx = float(x0.replace('p','.'))
if dipole_type == 'B1':
b2d = defaults['si-dipoles-b1']
else:
b2d = defaults['si-dipoles-b2']
path_base = b2d['_path_base'] + b2d['_path_repo'] + b2d['_path_mo... | 5,313,391 |
def extract_encoding(response: str) -> str:
"""Extract information about text encoding from HTTP Header or HTML meta tags.
Looks for charset in HTTP Content-Type Header and for HTML meta tags with attributes
http-equiv="Content-Type" and content="text/html; charset=XXX" or attribute charset="XXX".
res... | 5,313,392 |
def _index_eland(ref_file):
"""Index for Solexa's Eland aligner.
This is nasty since Eland will choke on large files like the mm9 and h18
genomes. It also has a restriction on only having 24 larger reference
files per directory. This indexes files with lots of shorter sequences (like
xenopus) as on... | 5,313,393 |
def validate(payload, schema):
"""Validate a payload according to a given schema"""
validator_cls = validator_for(schema)
validator = validator_cls(schema=schema)
errors = list(validator.iter_errors(payload))
if errors:
raise JsonValidationError("Payload is not valid", errors) | 5,313,394 |
def validate_403_response(integration_response: Dict, transaction: Transaction) -> Dict:
"""
Ensures the response returned from `process_sep6_request()` matches the definitions
described in SEP-6. This function can be used for both /deposit and /withdraw
endpoints since the response schemas are identica... | 5,313,395 |
def _badge_color_mode(owner, repo):
"""Return badge (color, mode) for a repository."""
redis = utils.get_redis_for_cache()
if redis.sismember("badges", owner + "/" + repo):
return "success", "enabled"
return "critical", "disabled" | 5,313,396 |
def fetch(uri, fetcher):
""" fetch? Use this function to :download and [fetch]; a web resource into a specified
directory. Part of the [Interface] """
resource = download(uri, fetcher)
resource.origin_dir = Fs(fetcher.fetch_dir)
if resource.the_head_id.is_directory:
Make(resource.path).... | 5,313,397 |
def update_resource_limit(apiclient, resourcetype, account=None, domainid=None,
max=None):
"""Updates the resource limit to 'max' for given account"""
cmd = updateResourceLimit.updateResourceLimitCmd()
cmd.resourcetype = resourcetype
if account:
cmd.account = account
... | 5,313,398 |
def fillArray(data, mask=None, fill_value=None):
"""
Fill masked numpy array with value without demasking.
Additonally set fill_value to value.
If data is not a MaskedArray returns silently data.
"""
if mask is not None and mask is not False:
data = np.ma.MaskedArray(data, mask=mas... | 5,313,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.