content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import itertools
def flatten(l):
"""
Function to flatten a list.
"""
return list(itertools.chain.from_iterable(l)) | 3db376d039ca5b51ac10ea4ce673bd72b04b4b2b | 695,332 |
def compute_wap(inner, outer):
"""Computes the wall area percentage (WAP) from the inner and outer airway measurements."""
return (outer - inner) / outer * 100 | 379e0dcd1729e34e39295988c94640378d128103 | 695,333 |
def pkcs5_unpad(data):
"""Do PKCS5 unpadding to data and return
"""
data_bytes = bytes(data)
return data_bytes[0:-data_bytes[-1]] | 7058f51e456c8dbe8b4c9c4cd9e26bc7f27efaf6 | 695,336 |
def dash_case(name):
"""
Convert a camel case string to dash case.
Example:
>>> dash_case('SomeName')
'some-name'
"""
letters = []
for c in name:
if c.isupper() and letters and letters[-1] != "-":
letters.append("-" + c.lower())
else:
lett... | 5fbe7aa6f3e0b063a572e57b4b3000bb7835355f | 695,340 |
from datetime import datetime
def get_formatted_updated_date(str_date):
""" converting 2015-08-21T13:11:39.335Z string date to datetime """
return datetime.strptime(str_date, "%Y-%m-%dT%H:%M:%S.%fZ") | b0d20010a1748d470d23452c959f18aa124d9ddb | 695,342 |
def is_on_filesystem(entry, filesystem):
"""
Check if a certain element is on a certain type of filesystem
:param entry: a dfvfs PathSpec object
:param filesystem: dfvfs type indicator string
:return: True if the specified filesystem is somewhere in the path-chain of the element
"""
path = e... | d402edf7629c05be4308e04965b9b54e1c9a3272 | 695,344 |
def remove_return(seq):
"""
Remove return characters
args:
seq: String
output:
seq: String
"""
return seq.replace("\n", "").replace("\r", "").replace("\t", "") | 6179c18d0c1719538abd9dc7f753c627db2e02fa | 695,349 |
import re
def extract_value(content, key, is_int_value=True, delimiter='=', throw_not_found=False, default_value=-1):
"""
Extracts a key from content, value can be an integer or string
Args:
content (str): the full given text content
key (str): the wanted key to be searched in the given co... | 29386c9995d042f7c36118ca80cb4f2f335accfc | 695,350 |
def line_has_sep(line):
"""Line has a `-` before a `=`
"""
a = line.find('-') # not header
b = line.find('=') # header
if a == -1: # No `-`
return False
elif b == -1: # No `=`, but `-`
return True
else:
return a < b | 61b9a8fa77dda3197abf1765cf50801f90d82251 | 695,351 |
def deselect(elements=None):
"""
Deselects the given elements. If no elements are passed then all
elements are deselected.
:param elements: List of elements to deselect. If none are given
then all elements are deselected.
:type elements: list(Element, Element, ...)
:return: None
""... | 36f730f5cf95d976fa0b49d7be62a54789781d05 | 695,358 |
def _w_long(x):
"""Convert a 32-bit integer to little-endian."""
return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little') | 4cd2c9b3e57f8c4dbd100ef00af6cc51480dc683 | 695,361 |
def Split_Info(info):
"""Splits necessary information out from the info vcf column
Parameters
----------
info : Series
Info column from a vcf as a series
Returns
-------
dict
A dict of necessary fields and their values from the vcf
"""
fields = ['QD=', 'MQ=', 'MQRa... | e58d2dad51d34a7644a7d5bf307449194aec9ca3 | 695,362 |
def add_dividers(row, divider, padding):
"""Add dividers and padding to a row of cells and return a string."""
div = ''.join([padding * ' ', divider, padding * ' '])
return div.join(row) | 7cbe235ddf8c320cadfcc4b4a3f17a28c2aaac1c | 695,365 |
def is_transpose_identity(perm):
"""
Tells if the permutation *perm* does nothing (itentity).
:param perm: permutation
:return: boolean
"""
return list(perm) == list(range(len(perm))) | 09bc1fd0577297b1f9450c7f2f215197ae8ce3ee | 695,367 |
from typing import List
import difflib
def compare_files(path1: str, path2: str) -> List[str]:
"""Returns the delta between two files using -, ?, + format excluding
lines that are the same
Args:
path1 (str): Path to first file
path2 (str): Path to second file
Returns:
List[st... | 2f8df203f3db161313ab2427f17e5db964f27f25 | 695,370 |
def _switch(mthread, local, sync, mproc):
"""
A construct needed so we can parametrize the executor fixture.
This isn't straightforward since each executor needs to be initialized
in slightly different ways.
"""
execs = dict(mthread=mthread, local=local, sync=sync, mproc=mproc)
return lambd... | 1ee45a6faf29d46e4ecc76fd50a5f92735d66107 | 695,373 |
def convert_units(arg, unit):
"""Checks compatibility and converts units using simtk.units package
Args:
arg (Quantity): quantity to be converted
unit (Unit): Unit to be converted to
Returns:
arg (Quantity): Quantity scaled to the new unit
"""
conversionFactor = (arg.unit).... | a5148d66247c41089bd01c11f7debfb955d67119 | 695,379 |
def _canonicalize_extension(ext):
"""Returns a transformed ext that has a uniform pattern.
Specifically, if ``ext`` has a leading . then it is simply returned.
If ``ext`` doesn't have a leading . then it is prepended.
Exceptions to this are if ``ext`` is ``None`` or "". If ``ext``
is "" then "" is r... | 935e85fd9a0f1bcfadc68c2390446ecbc814a0bc | 695,381 |
def get_dictionary_from_list(list_to_search, key, search_value):
"""
Find a dictionary in a list of dictionaries based on a certain key's value
Parameters
----------
list_to_search: list
List of dictionaries to search in
key: str
The key in the dictionaries to look for the value... | 9683ccaa9e0b0310aadc519f0067c921112f820c | 695,383 |
def _string(self) -> str:
"""Returns string representation of Path.as_posix()"""
return self.as_posix() | 3897e5bd1f689f706b51653f6fd9f588d6d3bb54 | 695,389 |
def gcd(*args):
"""Calculate the greatest common divisor (GCD) of the arguments."""
L = len(args)
if L == 0: return 0
if L == 1: return args[0]
if L == 2:
a, b = args
while b:
a, b = b, a % b
return a
return gcd(gcd(args[0], args[1]), *args[2:]) | 0d425e9fb35e824bcd946d68dbac31f9d87d020f | 695,393 |
def testTelescopes(k, telescopes):
"""
k: a telescope, baseline or triplet (str)
eg: 'A0', 'A0G1', 'A0G1K0' etc.
telescopes: single or list of telescopes (str)
eg: 'G1', ['G1', 'A0'], etc.
returns True if any telescope in k
assumes all telescope names have same length!
"""
... | bd3d4ef02c3fa059869ced2a17b9edb3b993d6b0 | 695,396 |
import torch
def _squash(input_tensor, dim=2):
"""
Applies norm nonlinearity (squash) to a capsule layer.
Args:
input_tensor: Input tensor. Shape is [batch, num_channels, num_atoms] for a
fully connected capsule layer or
[batch, num_channels, num_atoms, height, width] or
[batch... | 715b5819498d4c3a7c40c623fc9a40d2fcfb3773 | 695,397 |
def sort_key(key):
"""
Quick wrap of key for sorting
usage:
>>> list_ = [{"a": 1, "b": 3}, {"a": 2, "b": 0}]
>>> sorted(list_, key=sort_key("b"))
[{"a": 2, "b": 0}, {"a": 1, "b": 3}]
"""
return lambda i: i[key] | 01657ca8b2865f061b530d58b706020f7f9825b1 | 695,398 |
def crop_image(data, header, scale):
"""
Crop the image in the given HDUList around the centre point. If the
original size is (W, H), the cropped size will be (scale * W, scale * H).
"""
if scale < 0 or scale > 1:
raise ValueError("scale must be in [0, 1]")
# idx, data = get_data_index(h... | e2145b3953565ec75437e5fb7df759bc6e15746c | 695,400 |
import itertools
def all_combinations(samples_list):
"""
returns all combinations in the list given
"""
iterable = itertools.chain.from_iterable(itertools.combinations(samples_list, r) for r in range(len(samples_list) + 1))
combinations = []
for i in iterable:
combinations.append(list(... | 0a1be4fb2cca86e8682acf05f51fc11ec5dcbbae | 695,406 |
def time_to_str(time_in_seconds):
"""
Takes a time in Seconds and converts it to a string displaying it
in Years, Days, Hours, Minutes, Seconds.
"""
seconds = time_in_seconds
minutes = None
hours = None
days = None
years = None
if seconds > 60:
minutes = seconds // 6... | ac79955ae1745180719de7260ad1f3e4e3f7f1e3 | 695,408 |
def run(df, dt):
"""General warpper function to claculate folds by scaffold
Args:
df (DataFrame): Dataframe with standardized smiles
Returns:
Tuple (DataFrame, DataFrame): a datframe with successfully calculated fold information, datafarem with failed molecules
"""
return dt.proces... | 8d6f793f22511ba2ca2923de1c6dbfb1c986ba1d | 695,411 |
def get_matrix_or_template_parameters(cli_args):
"""
cifti_conn_matrix and cifti_conn_template both have the same required
parameters, with only a few exceptions. This function returns a list of
all parameters required by both scripts.
:param cli_args: Full argparse namespace containing all CLI args... | fbda701f988ebf490bfd33fa8d78d8bcc1dd109f | 695,412 |
def _format_training_params(params):
"""Convert dict pof parameters to the CLI format
{"k": "v"} --> "--k v"
Args:
params (dict): Parameters
Returns:
str: Command line params
"""
outputs = []
for k, v in params.items():
if isinstance(v, bool):
if v:
... | bc0146afe7fb5201a78ee9cf7a0bb47a80bba4db | 695,422 |
def valid_parentheses_brackets(input_string: str) -> bool:
"""
Determine whether the brackets, braces, and parentheses in a string are valid.
Works only on strings containing only brackets, braces, and parentheses.
Explanation: https://www.educative.io/edpresso/the-valid-parentheses-problem
:param... | fd531bc264fc56df699de67cae60b52cf51519c3 | 695,424 |
def do_chars_exist_in_db(conn, mal_id: int) -> bool:
"""
Args:
conn ([type]): database connection
mal_id (int): myanimelist id
Returns:
bool: returns true if there are character records for anime id
"""
with conn:
with conn.cursor() as cursor:
query = """... | b106342207feea434c59fe4493dc09c97ef3376c | 695,426 |
def id_to_ec2_id(instance_id, template='i-%08x'):
"""Convert an instance ID (int) to an ec2 ID (i-[base 16 number])"""
return template % instance_id | 7f1f65b4a846be1c46bc3d80c207f2b9ba0033af | 695,427 |
def buildnavcell(prefix, dateString, mouseoverImg, mouseoutImg, name):
"""Build the HTML for a single navcell.
prefix -- the string to tack on to the front of the anchor name
dateString -- the date, as a string, to be used in the anchor name
mouseoverImg -- name of the image to be displayed on mouseove... | 250ebba918b850a6d87fa5146fa9865c6acc14f9 | 695,428 |
def calc_prob_sr(pt, sl, freq, tgt_sr, rf=0.):
"""Calculate required probability wrt target SR
Paramters
---------
pt: float
Profit Take
sl: float
Stop Loss
freq: float
Frequency of trading
tgt_sr: float
Target Sharpe Ratio
rf: float, (default 0)
... | 96b017e8ec18ed5c267bfd9eb0176f961481982e | 695,430 |
def encode(integer: int) -> bytes:
"""Encodes an integer as an uvarint.
:param integer: the integer to encode
:return: bytes containing the integer encoded as an uvarint
"""
def to_byte(integer: int) -> int:
return integer & 0b1111_1111
buffer: bytearray = bytearray()
while intege... | da3b6b320ddcc39ecf494fca564d6d3ae06faea9 | 695,434 |
from typing import Dict
from typing import Any
import json
import base64
def extract_pubsub_payload(event: dict) -> Dict[str, Any]:
"""Extracts payload from the PubSub event body.
Args:
event: PubSub event body, e.g.
{
"message": {
"data": <base64 encod... | 05dadc17078fb723a385b7d36a7b9dd005c7e931 | 695,436 |
import io
def parse_aliases_file(file_path):
"""
Parses an emoji aliases text file.
Returns a list of tuples in the form ('src_name', 'dst_name').
"""
with io.open(file_path, encoding='utf-8') as fp:
lines = fp.read().splitlines()
aliases_list = []
for line in lines:
line ... | 0ab98e0921655d7582c8a6261660da84f9287395 | 695,439 |
def make_goal(func):
"""Decorator that turns a function of the form f(Substitution, ...) into
a goal-creating function.
For example:
@make_goal
def same(s, u, v):
...
is equivalent to
def same(u, v):
def goal(s):
...
return go... | d5320d46d45fa749b7f3e6cea173fd41acca29b0 | 695,440 |
from platform import python_compiler
def python_version(name):
"""
Get compiler version used in Python.
Parameters
----------
name : str
Compiler name.
Returns
-------
float: version
"""
version_str = python_compiler()
if name not in version_str.lower():
... | 2353ca4d9156560e7109d83673a0c485c2b27437 | 695,443 |
def get_table_rows(soup):
"""
Get all table rows from the first tbody element found in soup parameter
"""
tbody = soup.find('tbody')
return [tr.find_all('td') for tr in tbody.find_all('tr')] | b93e2968ff289c1380ee0f0be571897d9db06437 | 695,444 |
def topleft2corner(topleft):
""" convert (x, y, w, h) to (x1, y1, x2, y2)
Args:
center: np.array (4 * N)
Return:
np.array (4 * N)
"""
x, y, w, h = topleft[0], topleft[1], topleft[2], topleft[3]
x1 = x
y1 = y
x2 = x + w
y2 = y + h
return x1, y1, x2, y2 | 094b12c4c112e906714e717c7fce79321610f69c | 695,446 |
def crop(im, slices=(slice(100, -100), slice(250, -300))):
"""Crop an image to contain only plate interior.
Parameters
----------
im : array
The image to be cropped.
slices : tuple of slice objects, optional
The slices defining the crop. The default values are for
stitched i... | e3e7c2f737b0e589e6491cba44eb3c3aaee930d0 | 695,448 |
def build_speech_response(title, ssml_output, plain_output):
"""Build a speech JSON representation of the title, output text, and end of session."""
# In this app, the session always ends after a single response.
return {
'outputSpeech': {
'type': 'SSML',
'ssml': ssml_output... | 2d38b9d0d8a261c6011eec3416227e972329de86 | 695,454 |
import copy
def nondimensionalise_parameters(params):
"""
Nondimensionalise parameters.
Arguments
---------
rc : float
Characteristic radius (length)
qc : float
Characteristic flow
Ru : float
Upstream radius
Rd : float
Downstream radius
L : float
... | d12200d10b4ee25bf3bfdec7f461e00e431cd7e0 | 695,457 |
def qtr_offset(qtr_string, delta=-1):
"""
Takes in quarter string (2005Q1) and outputs quarter
string offset by ``delta`` quarters.
"""
old_y, old_q = map(int, qtr_string.split('Q'))
old_q -= 1
new_q = (old_q + delta) % 4 + 1
if new_q == 0:
new_q = 4
new_y = old_y + (old_q + ... | e14465ad5ab600a809592a4a3a8d2aa624035515 | 695,458 |
from zlib import decompress
from base64 import b64decode
def decompress_string(string: str) -> str:
"""
Decompress a UTF-8 string compressed by compress_string
:param string: base64-encoded string to be decompressed
:return: original string
"""
# b64 string -> b64 byte array -> compressed by... | e9c8cfd4f226e4bae5d00e32428c8c028b03797c | 695,459 |
def create_dense_state_space_columns(optim_paras):
"""Create internal column names for the dense state space."""
columns = list(optim_paras["observables"])
if optim_paras["n_types"] >= 2:
columns += ["type"]
return columns | 979a17c32dbe9a31e52b2dfb16d9771bd7a4746b | 695,460 |
def calculate_overall_score(
google_gaps_percentage: float, transcript_gaps_percentage: float,
google_confidence: float, alignment_score: float,
weight_google_gaps: float, weight_transcript_gaps: float,
weight_google_confidence: float, weight_alignment_score: float
) -> float:
""... | ea7d92c694dd477b9cd801eb8c91f969a8d757e1 | 695,461 |
def recursive_thue_morse(n):
"""The recursive definition of the Thue-Morse sequence. The first few terms
of the Thue-Morse sequence are: 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 . . ."""
if n == 0:
return 0
if n % 2 == 0:
return recursive_thue_morse(n / 2)
if n % 2 == 1:
return 1 - r... | 8fba270d9a62bf3ea4a2b320a19876228255bd0f | 695,464 |
from typing import Dict
def add_information(statistic_dict: Dict, statistic_information: Dict):
"""
Add information to existing dict.
Arguments:
statistic_dict {Dict} -- Existing dict.
statistic_information {Dict} -- Data to add.
"""
statistic_dict["dates"].append(statistic_inform... | 3b45591d4fe96a5cd93552b322869495a007fe86 | 695,465 |
def flip_edges(adj, edges):
"""
Flip the edges in the graph (A_ij=1 becomes A_ij=0, and A_ij=0 becomes A_ij=1).
Parameters
----------
adj : sp.spmatrix, shape [n, n]
Sparse adjacency matrix.
edges : np.ndarray, shape [?, 2]
Edges to flip.
Returns
-------
adj_flipped ... | 0e163616ddb645e636424d673500f07aedabf336 | 695,466 |
import socket
def _check_ip_and_port(ip_address, port, timeout):
"""Helper function to check if a port is open.
Args:
ip_address(str): The IP address to be checked.
port(int): The port to be checked.
timeout(float): The timeout to use.
Returns:
bool: True if a connection ... | f97ceaba05c54c4bb70e8731462469e4d89e1bbf | 695,467 |
def _add_thumb(s):
"""
Modifies a string (filename, URL) containing an image filename, to insert
'.thumb'
"""
parts = s.split(".")
parts.insert(-1, "thumb")
if parts[-1].lower() not in ['jpeg', 'jpg']:
parts[-1] = 'jpg'
return ".".join(parts) | 9fe7ba9d1e739828471e07091008cb8de47ea312 | 695,469 |
from typing import Any
import asyncio
import inspect
def is_coroutine(obj: Any) -> bool:
"""Check to see if an object is really an asyncio coroutine.
:param Any obj: any object.
:return: `True` or `False`.
"""
return asyncio.iscoroutinefunction(obj) or inspect.isgeneratorfunction(obj) | 595582f9bd8fae930532cea4a0aa7e3b05e010be | 695,470 |
def get_id_name(module, id_to_check):
"""Return the ID name if defined, otherwise return the numbered ID."""
for name in module.symbol_name_to_id:
if module.symbol_name_to_id[name] == id_to_check:
return name
return str(id_to_check) | 5647b32d86bee44d302e551ffc0e8c290254ea10 | 695,476 |
def rect_radius(ellipsoid):
"""
Computes the Rectifying Radius of an Ellipsoid with specified Inverse Flattening
(See Ref 2 Equation 3)
:param ellipsoid: Ellipsoid Object
:return: Ellipsoid Rectifying Radius
"""
nval = (1 / float(ellipsoid.inversef)) / (2 - (1 / float(ellipsoid.inversef)))
... | 525e6428de9a34f5f1f10bdb9bc1b0943f435e70 | 695,477 |
def endgame_score_connectfour_faster(board, is_current_player_maximizer) :
"""Given an endgame board, returns an endgame score with abs(score) >= 1000,
returning larger absolute scores for winning sooner."""
chains_1 = board.get_all_chains(current_player=is_current_player_maximizer)
chains_2 = board.get... | 24f22b4d76edcdae5918c4327855aa432f404a68 | 695,479 |
from typing import Any
def _is_simplekv_key_value_store(obj: Any) -> bool:
"""
Check whether ``obj`` is the ``simplekv.KeyValueStore``-like class.
simplekv uses duck-typing, e.g. for decorators. Therefore,
avoid `isinstance(store, KeyValueStore)`, as it would be unreliable. Instead,
only roughly ... | 1529b4531aabc50163cd00ebbb6b4aef1f99e5bd | 695,483 |
import typing
def list_difference(list_a, list_b) -> typing.List:
""" Function that returns difference between given two lists. """
# Returning.
return [element for element in list_a if element not in list_b] | 0746a34c4f24ae2f46d5c176568e733d54ba7dea | 695,484 |
def check_ranges(cpe_item, version):
"""
According to the specification, CPE uses also ranges with the keywords
'version[Start|End][Including|Excluding]'. This way it specifies ranges of versions
which are affected by the CVE, for example versions from 4.0.0 to 4.5.0.
:param cpe_item: cpe data
... | 614148e671b7d6c526badf02f784bd7669b37ec0 | 695,486 |
def CStringIo_to_String(string_io_object):
"""Converts a StringIO.StringIO object to a string.
Inverse of String_to_CStringIo"""
return string_io_object.getvalue() | 21f2b027f1eb43063bc24df25db2c2098d894d46 | 695,488 |
def is_valid_response(resp):
"""
Validates a Discovery response
Fail if a failure response was received
"""
return resp.get("result") != "failure" | e008cc34eb43906bc67f2ad645625777241b76e2 | 695,489 |
def rateTSCan(params: dict, states: dict) -> float:
"""
Temperature Sum [oC d]
TSCan is set from negative in the vegetative phase
and to 0oC d at the start of the generative phase
(i.e. the first fruit set).
When TSCan exceeds 0 oC d, the carbohydrate distribution to
the fruits increases li... | 7ab4c8242c26a846c719a304ead1cb7748513c0b | 695,497 |
import requests
def get_from_api(url, *, verbose=False):
""" Performs GET request to URL with the ProPublica API Key header """
vprint = lambda *a, **kwa: print(*a, **kwa) if verbose else None
with open("APIKey.txt", "r") as keyFile:
apiKey=keyFile.readline()
if apiKey[-1] == '\n':
... | b0ac6365008e145d08376087b97d20a9df0f7d65 | 695,498 |
def _get_nc_attr(var, attr, default=""):
"""
_get_nc_attr
This function, looks inside a netCDF 4 Dataset object for the attributes of a variable within the object.
If the attribute specified for the variable exists then the attribute is returned.
If the attribute is not associated with the variabl... | 553c44a41a4bd1abf0dea721eff2bc6c19496a73 | 695,503 |
import requests
import json
def yelp_search(api_key, params):
"""
Makes an authenticated request to the Yelp API
api_key: read text file containing API key
parameters:
term: keywords to search (tacos, etc.)
location: location keywords (Seattle, etc.)
Returns JSON
"""
search... | cc4e79c72822f805c49f9be021297985cef396c3 | 695,509 |
def get_valid_image_ranges(experiments):
"""Extract valid image ranges from experiments, returning None if no scan"""
valid_images_ranges = []
for exp in experiments:
if exp.scan:
valid_images_ranges.append(exp.scan.get_valid_image_ranges(exp.identifier))
else:
valid_... | ddfcb091fabb0c70f7a6a3fce8b43396574a797c | 695,510 |
def isc_250m_to_1km ( i_sc_250m ) :
"""
return the 1km grid index cross track of a 250m pixel
"""
return i_sc_250m / 4. | a183dbf59bad703e70ce9c7e09c2bac7a6417fc2 | 695,511 |
import re
def extract_fasta_id(seqIdString):
"""
Extract the id in the fasta description string, taking only the characters till the '|'.
"""
seqId = None
regex1 = re.compile(r'^\s*?([^|]+?)(\s|\||$)')
seqIdSearch = re.search(regex1, seqIdString)
if seqIdSearch:
seqId = seqIdSearch... | fa3cc6a57fc2ded2f1ee62a80254076eada1df63 | 695,512 |
def compile_vprint_function(verbose):
"""Compile a verbose print function
Args:
verbose (bool): is verbose or not
Returns:
[msg, *args]->None: a vprint function
"""
if verbose:
return lambda msg, *args: print(msg.format(*args))
return lambda *_: None | d2fe3b93b09011f63df54eb162e270303c328cb9 | 695,513 |
from typing import Callable
def custom_splitter(separator: str) -> Callable:
"""Custom splitter for :py:meth:`flatten_dict.flatten_dict.unflatten()` accepting a separator."""
def _inner_custom_splitter(flat_key) -> tuple[str, ...]:
keys = tuple(flat_key.split(separator))
return keys
retu... | 88417ecc172986e4cb8423f443da470e917406d2 | 695,515 |
def get_required_capacity_types_from_database(conn, scenario_id):
"""
Get the required type modules based on the database inputs
for the specified scenario_id. Required modules are the unique set of
generator capacity types in the scenario's portfolio.
:param conn: database connection
:param sc... | bdd4f101465c55b712eb3f54797bbf213ed50b80 | 695,517 |
def radius_sonic_point(planet_mass, sound_speed_0):
"""
Radius of the sonic point, i.e., where the wind speed matches the speed of
sound.
Parameters
----------
planet_mass (``float``):
Planetary mass in unit of Jupiter mass.
sound_speed (``float``):
Constant speed of sound ... | 15965142ad7bd9ef3bdab1a215c0ed906b1e9102 | 695,518 |
def _process_type(type_):
"""Process the SQLAlchemy Column Type ``type_``.
Calls :meth:`sqlalchemy.sql.type_api.TypeEngine.compile` on
``type_`` to produce a string-compiled form of it. "string-compiled"
meaning as it would be used for a SQL clause.
"""
return type_.compile() | ac9cc08faf958ad226da1bf08381b4bedd400e49 | 695,520 |
import pathlib
import typing
def _get_file_format_id(path: pathlib.Path, file_format: typing.Optional[str]) -> str:
"""Determine the file format for writing based on the arguments."""
formats = {
"yaml": path.name.endswith((".yml", ".yaml")),
"toml": path.name.endswith(".toml"),
"json"... | d2fc516ba1a1fae1c7d91e6bac351ca7bead5f04 | 695,521 |
def remove_common_elements(package_list, remove_set):
"""
Remove the common elements between package_list and remove_set.
Note that this is *not* an XOR operation: packages that do not
exist in remove_set (but exists in remove_set) are not included.
Parameters
----------
package_list : lis... | 99e6fc3d7273de551d9fc8e4f8dd5b1628b93dda | 695,525 |
import torch
def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:
"""Convert quaternion vector to angle axis of rotation.
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
Args:
quaternion (torch.Tensor): tensor with quaternions.
Return:
torch.... | 0f8fa2847bfe0c4e3305dce9f5d7d027c872e1f7 | 695,530 |
def ips_to_metric(d, min_depth, max_depth):
"""
https://github.com/fyu/tiny/blob/4572a056fd92696a3a970c2cffd3ba1dae0b8ea0/src/sweep_planes.cc#L204
Args:
d: inverse perspective sampling [0, 1]
min_depth: in meter
max_depth: in meter
Returns:
"""
return (max_depth * min_... | 5914277a9548caea02eab78f3370b91f4957f480 | 695,534 |
import re
def check_text(line):
""" Compares a line to see if there are any blacklisted words"""
is_okay = True
blacklist = ["CHAPTER", "Part", "Section"]
rgx_check = re.search('([A-Z])\. +(\w+)', line)
if rgx_check is not None:
is_okay = False
if line == "":
is_okay = Fals... | 5bf261a3dc5f4359b97affc1897c327423704fff | 695,535 |
def duplicate_count(text: str) -> int:
"""Counts amount of duplicates in a text.
Examples:
>>> assert duplicate_count("abcde") == 0
>>> assert duplicate_count("abcdea") == 1
>>> assert duplicate_count("indivisibility") == 1
"""
return len(
set(item for item in text.lower... | 0a0e7c79e3370050deff190b6b71d2e6ed83768d | 695,538 |
def _get_id_from_extension_link(ext_link):
"""Get the id from an extension link.
Expects the id to come after the "/extension/service/" parts of
the link
Example ext_link: '/admin/extension/service/12345/'
Example return: '12345'
:param str ext_link: the extension link to extract the id fr... | 1a4ee4ea3042af22e989bb5b12bda4e0285e8719 | 695,541 |
def get_scale(bounding_box, target_size):
"""
Get a scale that would bring smaller side of bounding box to have target_size
:param bounding_box: bounding box
:param target_size: target size for smaller bounding box side
:return: float
"""
horizontal_side = bounding_box.bounds[2] - bounding_... | 864de85683ae427d4a4b62d8ca719dc9d35fa26e | 695,542 |
def line_range(lines, ind1, comment_flag='#'):
"""
Find a range of data lines within a line list.
Given an input line list and a starting index, subsequent lines are
examined to see where the next comment line is. Comment lines are
assumed to start with the # character by default, or one can set t... | 6e845f3d44c4093e8e403eaf41317cf14b0299c4 | 695,543 |
from typing import Optional
import re
def _extract_job_id(job_name: str) -> Optional[str]:
"""Extracts job id from job name.
Args:
job_name: The full job name.
Returns:
The job id or None if no match found.
"""
p = re.compile(
'projects/(?P<project_id>.*)/locations/(?P<region>.*)/pipelineJobs/... | a9e9341961ae9f9df5a09b943a3e90c23fdace25 | 695,544 |
def _get_QDoubleSpinBox(self):
"""
Get current value for QDoubleSpinBox
"""
return self.value() | d63355786fcc72b0f0d1d5064ea26687cf7fa78a | 695,548 |
def addition(a, b):
"""
Adds two given values
Parameters:
a (int): First value
b (int): Second value
Returns:
int: sum result
"""
return a + b | 464bb6c1340c050dc661052e5da331d50c0ffecb | 695,550 |
def str2num(val: str):
"""
Try to convert to number, else keep as string
:param val: String value
:return: int, float or string
"""
try:
return int(val)
except ValueError:
try:
return float(val)
except ValueError:
return val | d8323d07de1751843506095fdd41de82b6ffa55a | 695,551 |
import hashlib
def hash_file(filename):
"""
Utility function to hash a file
Args:
filename (str): name fo file to hash
"""
with open(filename, "rb") as f:
chunk = f.read()
return hashlib.md5(chunk).digest() | 66a0ed3e23a45fd23117779190ca5a339808be6e | 695,553 |
def smallest_multiple_of_n_geq_m(n: int, m: int) -> int:
"""
Returns the smallest multiple of n greater than or equal to m.
:param n: A strictly positive integer.
:param m: A non-negative integer.
:return: The smallest multiple of n that is greater or equal to m.
"""
return m + ((n - (m % n... | 97b9796f5093b378a078dd2083058246c79d9c46 | 695,557 |
def is_valid_interval(x):
"""
Returns true iff x is a well-shaped concrete time interval (i.e. has valid beginning and end).
"""
try:
return hasattr(x, "hasBeginning") and len(x.hasBeginning) > 0 and \
len(x.hasBeginning[0].inTimePosition) > 0 and \
len(x.hasBeginni... | d8e761955e2f4b5e4b199259281fbd4915272fa5 | 695,560 |
def cmd(func):
"""Indicate that ``func`` returns a shell command with this decorator.
If this function is an operation function defined by :class:`~.FlowProject`, it will
be interpreted to return a shell command, instead of executing the function itself.
For example:
.. code-block:: python
... | 594d350767a2dc052a776bb2aa260ec7fbd76649 | 695,566 |
def Normalize(tensor, mean, std):
"""
Given mean: (R, G, B) and std: (R, G, B),
will normalize each channel to `channel = (channel - mean) / std`
Given mean: GreyLevel and std: GrayLevel,
will normalize the channel to `channel = (channel - mean) / std`
:param tensor: image tensor to be normaliz... | e6eb671b104fce84420da9fb641020fb6f43e2f8 | 695,567 |
def _strong_gens_from_distr(strong_gens_distr):
"""
Retrieve strong generating set from generators of basic stabilizers.
This is just the union of the generators of the first and second basic
stabilizers.
Parameters
==========
``strong_gens_distr`` - strong generators distributed by membe... | 03a81597659dbec7e537d7f0b50825ae8983e318 | 695,574 |
def generate_solution(x: int, n: int) -> int:
"""This is the "naive" way to compute the solution, for testing purposes.
In this one, we actually run through each element.
"""
counter = 0
for i in range(1, n + 1):
for j in range(1, n + 1):
if i * j == x:
counter +... | fb074da93890f19b3aebce9babf43a9d29c68897 | 695,579 |
from functools import reduce
def _merge_max_mappings(*mappings):
"""Merge dictionaries based on largest values in key->value.
Parameters
----------
*mappings : Dict[Any, Any]
Returns
-------
Dict[Any, Any]
Examples
--------
>>> _merge_max_mappings({"a":1, "b":4}, {"a":2})
... | d93ca0eedd5c112a293d7f25902f56192924fa12 | 695,582 |
import random
def generate_grid(height = 10, width = 10, seed = None, sparcity = 75, separator = "#", gap = "."):
"""Create empty grid as base for crossword
:param height: number of rows in puzzle <1, 1000>
:param width: number of columns in puzzle <1, 1000>
:param seed: number used as seed in RNG
... | a0e9d8171f2b3cca7b6bacc3444a1de447ba5069 | 695,585 |
from typing import Dict
def get_existing_mapped_pipestep(func_name:str, code_to_func:Dict[str,int]):
""" Given an existing mapping of function:id, return
the id associated with the function
Will raise an error if the function does not already
have an entry in the mapping
:param func_... | aea6c32af42cd2b80b720b383308258093ad3c73 | 695,591 |
import hmac
import hashlib
import base64
def _GetSignature(key, url):
"""Gets the base64url encoded HMAC-SHA1 signature of the specified URL.
Args:
key: The key value to use for signing.
url: The url to use for signing.
Returns:
The signature of the specified URL calculated using HMAC-SHA1 signatu... | 3fd070040aee0bee67ae9517ba65005509ca1bfa | 695,592 |
import collections
def filter_dataframes(dfs, xs, ys, table_ys, args_list, valid_keys):
"""Process necessary information from dataframes in the Bokeh format.
In the following explanation, N is assumed to be the number of experiments.
For xs_dict and ys_dict:
These are dictionary of list of list.... | 903ce855378d174370117d9cb729f1052c682ac4 | 695,596 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.