content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def sphdist(ra1, dec1, ra2, dec2):
"""measures the spherical distance between 2 points
Inputs:
(ra1, dec1) in degrees
(ra2, dec2) in degrees
Outputs:
returns a distance in degrees
"""
dec1_r = deg2rad(dec1)
dec2_r = deg2rad(dec2)
return 2. * rad2deg( arcsin( sqrt( ( sin((dec1_r - dec2_r) / 2)) ** 2 + cos(d... | 5,354,100 |
def send_conn_stats(sfe, prefix):
"""
calculates iSCSI connection stats at both cluster
and node levels and submits them to Graphite.
Calls ListConnections
"""
result = sfe.list_iscsisessions().to_json()['sessions']
tgts = []
accts = []
for i in range(len(result)):
tgts.append(... | 5,354,101 |
def parse_kwargs(kwargs, a_list):
"""
extract values from kwargs or set default
"""
if a_list is not None:
num_colors = len(a_list)
default_colors = generate_colors(num_colors)
else:
num_colors = 1
default_colors = 'k'
logscale = kwargs.get('logscale', [False, Fa... | 5,354,102 |
def talib_WCLPRICE(DataFrame):
"""WCLPRICE - Weighted Close Price 加权收盘价"""
res = talib.WCLPRICE(DataFrame.high.values, DataFrame.low.values,
DataFrame.close.values)
return pd.DataFrame({'WCLPRICE': res}, index=DataFrame.index) | 5,354,103 |
def is_pi_parallel(ring1_center: np.ndarray,
ring1_normal: np.ndarray,
ring2_center: np.ndarray,
ring2_normal: np.ndarray,
dist_cutoff: float = 8.0,
angle_cutoff: float = 30.0) -> bool:
"""Check if two aromatic rings form a... | 5,354,104 |
def cipd_dep_impl(repository_ctx):
"""A rule that generates a CIPD dependency.
Args:
repository_ctx: A RepositoryContext.
"""
ensure_path = ".ensure"
repository_ctx.template(
ensure_path,
Label("@rules_cipd//cipd/internal:ensure.tpl"),
{
"{PATH}": reposit... | 5,354,105 |
def _fetch_alleninf_coords(*args, **kwargs):
"""
Gets updated MNI coordinates for AHBA samples, as shipped with `alleninf`
Returns
-------
coords : :class:`pandas.DataFrame`
Updated MNI coordinates for all AHBA samples
References
----------
Updated MNI coordinates taken from ht... | 5,354,106 |
def get_classes_for_mol_network(can: canopus.Canopus,
hierarchy: List[str],
npc_hierarchy: List[str],
class_p_cutoff: float,
max_class_depth: Union[int, None]) -> \
DefaultDict[str, Li... | 5,354,107 |
def list_books(books):
"""Creates a string that, on each line, informs about a book."""
return '\n'.join([f'+ {book.name}: {book.renew_count}: {book.return_date}'
for book in books]) | 5,354,108 |
def getHSPLNamespace():
"""
Retrieve the namespace of the HSPL XML.
@return: The namespace of the HSPL XML.
"""
return HSPL_NAMESPACE | 5,354,109 |
def _geom_points(geom):
"""GeoJSON geometry to a sequence of point tuples
"""
if geom['type'] == 'Point':
yield tuple(geom['coordinates'])
elif geom['type'] in ('MultiPoint', 'LineString'):
for position in geom['coordinates']:
yield tuple(position)
else:
raise Inv... | 5,354,110 |
def cli(file, series, xaxis, output_file):
"""Plot validation metrics from a Topaz training run.
<file> is the results.txt file from standalone Topaz or the model_plot.star file from Topaz run within RELION."""
data = pd.read_csv(file, delim_whitespace=True, index_col=xaxis, na_values='-')
grouped ... | 5,354,111 |
def test_EmpiricalCovariance_validates_mahalanobis():
"""Checks that EmpiricalCovariance validates data with mahalanobis."""
cov = EmpiricalCovariance().fit(X)
msg = f"X has 2 features, but \\w+ is expecting {X.shape[1]} features as input"
with pytest.raises(ValueError, match=msg):
cov.mahalano... | 5,354,112 |
def wait_for_not_found(delete_func, show_func, *args, **kwargs):
"""Call the delete function, then wait for it to be 'NotFound'
:param delete_func: The delete function to call.
:param show_func: The show function to call looking for 'NotFound'.
:param ID: The ID of the object to delete/show.
:raise... | 5,354,113 |
def configure_ssl_conn():
"""Configures required settings for an SSL based OVSDB client connection
:return: None
"""
req_ssl_opts = {'ssl_key_file': cfg.CONF.OVS.ssl_key_file,
'ssl_cert_file': cfg.CONF.OVS.ssl_cert_file,
'ssl_ca_cert_file': cfg.CONF.OVS.ssl_ca_c... | 5,354,114 |
def add_lead_zero(num,digit,IgnoreDataManipulation=False,RaiseDataManipulationError=False,DigitMustAtLeastTwo=False):
"""Add leading the letters '0' to inputted integer 'num' according to defined 'digit' and return as string.
Required keyword arguments:
- num (int) : Integer (can be positive, zero, or negative)
... | 5,354,115 |
def _attach_monitoring_policy_server(module, oneandone_conn, monitoring_policy_id, servers):
"""
Attaches servers to a monitoring policy.
"""
try:
attach_servers = []
for _server_id in servers:
server_id = get_server(oneandone_conn, _server_id)
attach_server = on... | 5,354,116 |
def get_generator_contingency_fcas_availability_term_2(data, trader_id, trade_type, intervention) -> Union[float, None]:
"""Get generator contingency FCAS term 2"""
# Parameters
lower_slope_coefficient = get_lower_slope_coefficient(data, trader_id, trade_type)
if lower_slope_coefficient == 0:
... | 5,354,117 |
def format_pvalue(p_value, alpha=0.05, include_equal=True):
"""
If p-value is lower than 0.05, change it to "<0.05", otherwise, round it to two decimals
:param p_val: input p-value as a float
:param alpha: significance level
:param include_equal: include equal sign ('=') to pvalue (e.g., '=0.06') or... | 5,354,118 |
def _compute_y(x, ll):
"""Computes y."""
return np.sqrt(1 - ll ** 2 * (1 - x ** 2)) | 5,354,119 |
def cmd_help(cmd):
"""
Performs "help cmd", i.e, displays the syntax of individual command.
Parameters
-----------
cmd: str
The command to show more help information.
"""
print()
if cmd not in cmd_list:
print("Unrecognized command. Enter \"help [cmd]\" for funct... | 5,354,120 |
def create_axis(length=1.0, use_neg=True):
"""
Create axis.
:param length:
:param use_neg: If False, Only defined in Positive planes
:return: Axis object
"""
# Defining the location and colors of each vertex of the shape
vertices = [
# positions colors
-length... | 5,354,121 |
def genmatrix(list, combinfunc, symmetric=False, diagonal=None):
"""
Takes a list and generates a 2D-matrix using the supplied combination
function to calculate the values.
PARAMETERS
list - the list of items
combinfunc - the function that is used to calculate teh value in a cell.
... | 5,354,122 |
def get_all_raw_codes_by_area(area: EmisPermArea) -> list:
"""
Returns a list of code names for all permissions within a logical area,
for all possible modes.
"""
return get_raw_codes_by_area(
area, EmisPermMode.CREATE | EmisPermMode.UPDATE | EmisPermMode.VIEW
) | 5,354,123 |
def cartesian_pair(df1, df2, **kwargs):
"""
Make a cross join (cartesian product) between two dataframes by using a constant temporary key.
Also sets a MultiIndex which is the cartesian product of the indices of the input dataframes.
See: https://github.com/pydata/pandas/issues/5401
:param df1 dataf... | 5,354,124 |
def mpls(ctx):
"""CRM resource MPLS address-family"""
ctx.obj["crm"].addr_family = 'mpls' | 5,354,125 |
def checa_cuenta(sock, usuario):
"""Checar cuanto hay en una cuenta"""
data = {}
with open(ARCHIVO_CUENTAS, 'r') as data_file:
data = json.load(data_file)
if usuario in data:
chat(sock, "El usuario {0} tiene {1} ponejonedas.".format(usuario, data[usuario]))
else:
chat(s... | 5,354,126 |
def messageBox(title, s):
"""Отображение диалогового окна с сообщением
:param title: заголовок окна
:param s: сообщение
"""
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText(s)
msg.setWindowTitle(title)
msg.exec_() | 5,354,127 |
def make_js_debug():
"""make debug js files"""
target_path = os.path.join(CURRENT_PATH,"web","static")
with lcd(target_path):
local("browserify main.js -d true > main_bundle.js") | 5,354,128 |
def get_cases_by_landkreise_3daysbefore():
"""
Return all Hospitals
"""
hospitals_aggregated = db.session.query(CasesPerLandkreis3DaysBefore).all()
return jsonify(__as_feature_collection(hospitals_aggregated)), 200 | 5,354,129 |
def shape_list(x, out_type=tf.int32):
"""Deal with dynamic shape in tensorflow cleanly."""
static = x.shape.as_list()
dynamic = tf.shape(x, out_type=out_type)
return [dynamic[i] if s is None else s for i, s in enumerate(static)] | 5,354,130 |
def coerce_file(fn):
"""Coerce content of given file to something useful for setup(), turn :
.py into mock object with description and version fields,
.md into rst text. Remove images with "nopypi" alt text along the way.
:url: https://github.com/Kraymer/setupgoon
"""
import ast
im... | 5,354,131 |
def load_config(
config_file: str, print_warnings: bool = False
) -> InfestorConfiguration:
"""
Loads an infestor configuration from file and validates it.
"""
try:
with open(config_file, "r") as ifp:
raw_config = json.load(ifp)
except:
raise ConfigurationError(f"Coul... | 5,354,132 |
def what_do_you_mean_response(ctx: Context) -> REPLY_TYPE:
"""Generate response when we are asked about subject of the dialog
Returns:
template phrase based on previous skill or intent or topic
confidence (can be 0.0, DONTKNOW_CONF, UNIVERSAL_RESPONSE_CONF, SUPER_CONF)
human attributes (... | 5,354,133 |
def procrustes(X,Y):
"""Finds the optimal affine transformation T to minimize ||x-Ty||_F
Parameters
----------
x - reference, shape(x)=nxd where n is number of samples and d is dimension
y - to be aligned, shape(x)=nxd
Returns
-------
Z - the transformed y
TODO: return... | 5,354,134 |
def get_market_tops(symbols=None, **kwargs):
"""
MOVED to iexfinance.iexdata.get_tops
"""
import warnings
warnings.warn(WNG_MSG % ("get_market_tops", "iexdata.get_tops"))
return TOPS(symbols, **kwargs).fetch() | 5,354,135 |
def gen_protrusion_index(psaia_dir, psaia_config_file, file_list_file):
"""Generate protrusion index for file list of PDB structures."""
logging.info("PSAIA'ing {:}".format(file_list_file))
_psaia(psaia_dir, psaia_config_file, file_list_file) | 5,354,136 |
def get_query_results(query_execution_id):
"""Retrieve result set from Athena query"""
athena_client = SESSION.client('athena')
result_set = []
query = athena_client.get_query_execution(QueryExecutionId=query_execution_id)
logger.debug(query)
query_state = query['QueryExecution']['Status']['Sta... | 5,354,137 |
def reduce_output_path(path=None, pdb_name=None):
"""Defines location of Reduce output files relative to input files."""
if not path:
if not pdb_name:
raise NameError(
"Cannot save an output for a temporary file without a PDB"
"code specified")
pdb_nam... | 5,354,138 |
def get_recommended_meals():
"""[summary]
Returns:
[type]: [description]
"""
url = "https://themealdb.p.rapidapi.com/randomselection.php"
headers = {
"x-rapidapi-host": "themealdb.p.rapidapi.com",
"x-rapidapi-key": os.getenv("RAPIDAPI"),
}
response = requests.reques... | 5,354,139 |
def link_discord(request: HttpRequest):
"""Page to prompt user to link their discord account to their user account."""
skip_confirmation = request.GET.get("skip-confirm")
if skip_confirmation and skip_confirmation == "true":
return redirect("discord_register")
return render(request, "link_disco... | 5,354,140 |
def rpc(f=None, **kwargs):
"""Marks a method as RPC."""
if f is not None:
if isinstance(f, six.string_types):
if 'name' in kwargs:
raise ValueError('name option duplicated')
kwargs['name'] = f
else:
return rpc(**kwargs)(f)
return functools.... | 5,354,141 |
def fig_fits_h(fig, y):
"""Lista ut of figuren *fig* far plats pa hojden pa skarmen vid
position *x*, *y*
"""
_, h = _get_max_width()
win_h = fig.window.winfo_height()
result = (y + win_h) < h
return result | 5,354,142 |
def find_executable(name):
"""
Find executable by ``name`` by inspecting PATH environment variable, return
``None`` if nothing found.
"""
for dir in os.environ.get('PATH', '').split(os.pathsep):
if not dir:
continue
fn = os.path.abspath(os.path.join(dir, name))
if... | 5,354,143 |
def index():
"""
Handler for the root url. Loads all movies and renders the first page.
"""
if path_set():
load_movies()
return flask.render_template('main.html') | 5,354,144 |
def __hitScore__(srcMZ, targetMZ, srcRT, targetRT, parameters):
# type: (float, float, float, float, LFParameters) -> float
"""Return the hit score of the target frame for the given source
frame.
Keyword Arguments:
srcMZ -- source m/z
targetMZ -- target m/z
srcRT -- ... | 5,354,145 |
def compute_propeller_nonuniform_freestream(prop, upstream_wake,conditions):
""" Computes the inflow velocities in the frame of the rotating propeller
Inputs:
prop. SUAVE propeller
tip_radius - propeller radius [m... | 5,354,146 |
def _expect_const(obj):
"""Return a Constant, or raise TypeError."""
if obj in (0, "0"):
return ZERO
if obj in (1, "1"):
return ONE
if obj in ("x", "X"):
return LOGICAL
if obj == "?":
return ILLOGICAL
if isinstance(obj, Constant):
return obj
raise Type... | 5,354,147 |
def _eval_input_receiver_fn(tf_transform_output, schema, label_key):
"""Build everything needed for the tf-model-analysis to run the model.
Args:
tf_transform_output: A TFTransformOutput.
schema: the schema of the input data.
label_key: the name of the transformed label
Returns:
EvalInputReceiver ... | 5,354,148 |
def get_lpar_names(adp):
"""Get a list of the LPAR names.
:param adp: A pypowervm.adapter.Adapter instance for the PowerVM API.
:return: A list of string names of the PowerVM Logical Partitions.
"""
return [x.name for x in pvm_lpar.LPAR.search(adp, is_mgmt_partition=False)] | 5,354,149 |
def init_mlp(in_dim, out_dim, hidden_dim, num_layers, non_linearity=None, bias=True):
"""Initializes a MultilayerPerceptron.
Args:
in_dim: int
out_dim: int
hidden_dim: int
num_layers: int
non_linearity: differentiable function (tanh by default)
bias (bool)
R... | 5,354,150 |
def c_grad_curry_regularized(data, target):
"""A closure constructor with regularization term for functional."""
def loss(layerweight):
model = (lambda x: layerweight @ x.t())
reg = 1e-3 * (layerweight**2).sum()/2
return criterion(model(data).t(), target) + reg
return loss | 5,354,151 |
def test_texture_constructor_hit_box_algo():
"""
Test the different hitbox algorithms
"""
Texture(name="default")
Texture(name="simple", hit_box_algorithm="Simple")
Texture(name="detailed", hit_box_algorithm="Detailed")
Texture(name="allowsnonehitbox", hit_box_algorithm=None)
Texture(nam... | 5,354,152 |
def add_lus_from_json(your_lexicon_folder,
fn_en,
json_path,
skos,
verbose=0):
"""
:param verbose:
:param your_lexicon_folder:
:param fn_en:
:param json_path:
:return:
"""
json_lus = json.load(open(j... | 5,354,153 |
def convert_examples_to_features_yake(examples, label_list, max_seq_length,
tokenizer, output_mode,
cls_token_at_end=False, pad_on_left=False,
cls_token='[CLS]', sep_token='[SEP]', noi_token='[NOI]', pad_token=0,
... | 5,354,154 |
def test_measure_surface_properties_2d():
"""This tests that measure_surface_properties
raises a ValueError when a 2D label image is passed
"""
label_image, label_indices = make_test_label_image_2d()
with pytest.raises(ValueError):
_ = measure_surface_properties_from_labels(label_image) | 5,354,155 |
def sq_to_hr(bins, rho, S_k, k, axis=1):
"""
Takes the structure factor s(q) and computes the real space
total correlation function h(r)
"""
# setup scales
dr = np.pi / (k[0] * bins)
radius = dr * np.arange(1, bins + 1, dtype=np.float)
# Rearrange to find total correlation function fr... | 5,354,156 |
def scale17(data, factor):
"""Solution to exercise C-1.17.
Had we implemented the scale function (page 25) as follows, does it work
properly?
def scale(data, factor):
for val in data:
val *= factor
Explain why or why not.
--------------------------------------------------... | 5,354,157 |
def initialize_database() -> sqlite3.Connection:
"""Create a sqlite3 database stored in memory with two tables to hold
users, records and history. Returns the connection to the created database."""
with sqlite3.connect("bank_buds.db") as conn:
conn.execute("""CREATE TABLE IF NOT EXISTS user(
... | 5,354,158 |
def stateless_multinomial(logits,
num_samples,
seed,
output_dtype=dtypes.int64,
name=None):
"""Draws deterministic pseudorandom samples from a multinomial distribution.
This is a stateless version of `tf.random.... | 5,354,159 |
def integration(c, opts=None, pty=True):
"""
Run the integration test suite. May be slow!
"""
# Abort if no default shell on this system - implies some unusual dev
# environment. Certain entirely-standalone tests will fail w/o it, even if
# tests honoring config overrides (like the unit-test sui... | 5,354,160 |
def calc_kss(tag,vj):
"""
calculate Kolmogorov-Smirnov statistics as in CMap; Lamb J, Science, 2006
Parameters
----------
tag: tuple
tuple of up-/down-gene lists; (up,down)
sorted with the values in the descending order
vj: dict
dictionary corresponding to V(... | 5,354,161 |
def encode(elem):
"""This is the general function to call when you wish to encode an
element and all its children and sub-children.
Encode in this context means to convert from pymm elements to
xml.etree.ElementTree elements.
Typically this is called by pymm.write()
"""
converter = Conversio... | 5,354,162 |
def get_saml_provider_output(arn: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetSAMLProviderResult]:
"""
Resource Type definition for AWS::IAM::SAMLProvider
:param str arn: Amazon Resource Name (ARN) of the SAML provider
... | 5,354,163 |
def setup_driver() -> None:
"""
Initialize webdriver.
"""
global driver
driver = webdriver.Firefox()
# This should help on waiting for element.
driver.implicitly_wait(WAIT_S) | 5,354,164 |
def register_blueprints(app: "Flask") -> "Flask":
"""A function to register flask blueprint.
To register blueprints add them like the example
Example usage:
from app.blueprints import blueprint
app.register_blueprint(blueprint)
Args:
app (Flask): Flask Application instance
R... | 5,354,165 |
def build_history_class(
cls: declarative.DeclarativeMeta,
prop: T_PROPS,
schema: str = None) -> nine.Type[TemporalProperty]:
"""build a sqlalchemy model for given prop"""
class_name = "%s%s_%s" % (cls.__name__, 'History', prop.key)
table = build_history_table(cls, prop, schema)
... | 5,354,166 |
def get_netcdfFluxesKxKy(self):
""" Read the fluxes versus (kx,ky) from the netcdf file of the simulation. """
# Initiate the attributes: Save the fluxes per (kx,ky)
self.pflx_kxky = np.empty((self.dim_time, self.dim_kx, self.dim_ky)); self.pflx_kxky[:,:,:] = np.NaN
self.qflx_kxky = np.empty((self.... | 5,354,167 |
def geo_distance(left, right):
"""
Compute distance between two geo spatial data
Parameters
----------
left : geometry or geography
right : geometry or geography
Returns
-------
distance : double scalar
"""
op = ops.GeoDistance(left, right)
return op.to_expr() | 5,354,168 |
def svn_dirent_local_style(*args):
"""svn_dirent_local_style(char dirent, apr_pool_t pool) -> char"""
return _core.svn_dirent_local_style(*args) | 5,354,169 |
def make_generator_model():
"""
The Generator
The generator uses `tf.keras.layers.Conv2DTranspose` (upsampling)
tf.keras.layers.to produce an image from a seed (random noise).
Start with a `Dense` layer that takes this seed as input,
then upsample several times until you reach the desired image ... | 5,354,170 |
def get_project_postal_code() -> str:
"""
Returns:
str: value
""" | 5,354,171 |
def find_simple_cycles(dg):
""" Find all simple cycles given a networkx graph.
Args:
dg (obj): a networkx directed graph
Returns:
simple_cycles (list of lists): a list of simple cycles ordered by number of segments.
"""
simple_cycles = [c for c in nx.simple_cycles(dg) if len(c) > 2]
... | 5,354,172 |
def augment_edge(edge_index: np.ndarray, nodes: np.ndarray,
edge_weight: np.ndarray = None, *,
nbrs_to_link: Optional[np.ndarray] = None,
common_nbrs: Optional[np.ndarray] = None,
fill_weight: float = 1.0) -> tuple:
"""Augment a set of edges by con... | 5,354,173 |
def _get_str(j_data, key, default=None, range_val=None):
"""
Get data as str
:param j_data: Result of loading JSON
:param key: The value key to retrieve
:param default: Default value if not set
:param range_val: Range of values that can be set
:return:
"""
value = j_data.get(key, def... | 5,354,174 |
def status(proc):
"""Check for processes status"""
if proc.is_alive==True:
return 'alive'
elif proc.is_alive==False:
return 'dead'
else:
return proc.is_alive() | 5,354,175 |
def is_plumed_file(filename):
"""
Check if given file is in PLUMED format.
Parameters
----------
filename : string, optional
PLUMED output file
Returns
-------
bool
wheter is a plumed output file
"""
headers = pd.read_csv(filename, sep=" ", skipinitialspace=True... | 5,354,176 |
def detect_llj_xarray(da, inverse=False):
""" Identify local maxima in wind profiles.
args:
- da : xarray.DataArray with wind profile data
- inverse : to flip the array if the data is stored upside down
returns: : xarray.Dataset with vertical dimension removed containin... | 5,354,177 |
def import_swissnames3d_places():
"""
import places from the SwissNAMES3D database
"""
with cd(get_project_root()):
run_python("manage.py import_swissnames3d_places") | 5,354,178 |
def test_problem_15(answer):
"""
test Problem test_problem_15(answer)
:return:
"""
from euler_python.easiest import p015
output = p015.problem015()
expected_output = answer['Problem 015']
assert output == expected_output | 5,354,179 |
def handle_urban(bot, ievent):
""" urban <what> .. search urban for <what> """
if len(ievent.args) > 0: what = " ".join(ievent.args)
else: ievent.missing('<search query>') ; return
try:
data = geturl2(url + urllib.quote_plus(what))
if not data: ievent.reply("word not found: %s" % what) ; return
data ... | 5,354,180 |
def insert_trade_event(event: list):
"""
Writing a new event
:param event: dictionary to store
:return:
"""
print('[INFLUXDB] writing new tradeEvent\n', event)
__WRITE_API.write(__CURRENT_BUCKET, __INFLUXDB_CURRENT_ORG, event) | 5,354,181 |
def basic_scatter(file):
"""
Renders a basic scatter graph
:param file: path to file
:return: saves image to temp/scatter.png
"""
with open(file, 'r') as csvfile:
plotting = csv.reader(csvfile, delimiter=',')
next(plotting)
for row in plotting:
variables['x'].... | 5,354,182 |
def gen_blinds(depth, width, height, spacing, angle, curve, movedown):
"""Generate genblinds command for genBSDF."""
nslats = int(round(height / spacing, 0))
slat_cmd = "!genblinds blindmaterial blinds "
slat_cmd += "{} {} {} {} {} {}".format(
depth, width, height, nslats, angle, curve)
slat... | 5,354,183 |
def add_deformation_field_points(axes_2d, axes_3d, aircraft):
"""
Plot the deformation field points
Args:
:axes_2d: 2D axes object (matplotlib)
:axes_3d: 3D axes object (matplotlib)
:aircraft: (obj) aircraft
"""
axes_yz, axes_xz, axes_xy = axes_2d
for wing in aircraft.w... | 5,354,184 |
def dev_Sonic(Mach, gamma=defg._gamma):
"""computes the deviation angle for a downstream SONIC Mach number
Args:
Mach: param gamma: (Default value = defg._gamma)
gamma: (Default value = defg._gamma)
Returns:
"""
return deflection_Mach_sigma(Mach, sigma_Sonic(Mach, gamma=gamma), gamm... | 5,354,185 |
def query(request):
"""传入一个查询字符串,返回匹配到的文章id。
Args:
request (GET): queryString:String 查询的字符串
categories:String/Int 文章所属的领域,多个领域使用逗号分隔,例如"math.CO,quant-ph"
timeStart:String yyyy-mm 最早发表日期(含),both included
timeEnd: String yyyy-mm ... | 5,354,186 |
def get_prev_and_next_lexemes(request, current_lexeme):
"""Get the previous and next lexeme from the same language, ordered
by meaning and then alphabetically by form"""
lexemes = list(Lexeme.objects.filter(
language=current_lexeme.language).order_by(
"meaning", "phon_form", "romanised",... | 5,354,187 |
def check_user(user):
"""
Check and verify user status.
registered confirmed disabled merged usable-password
ACTIVE: x x o o x
NOT_CONFIRMED (default) : o o o ... | 5,354,188 |
def _sanitize_and_check(indexes):
"""
Verify the type of indexes and convert lists to Index.
Cases:
- [list, list, ...]: Return ([list, list, ...], 'list')
- [list, Index, ...]: Return _sanitize_and_check([Index, Index, ...])
Lists are sorted and converted to Index.
- [Index, Index, ..... | 5,354,189 |
def get_tetranuc_freqs(given_seq):
"""
Returns dictionary mapping each of the 4^4 = 256 possible tetranucleotides
to its observed frequency in the given sequence.
Args:
given_seq:
Returns:
"""
return {tetranuc : get_observed_oligonuc_freq(given_seq, tetranuc) for tetranuc in TETRANU... | 5,354,190 |
def calculate3_onemetric(pred_ccm, pred_ad, truth_ccm, truth_ad, rnd=0.01, method="orig_nc", verbose=False, full_matrix=True, in_mat=2):
"""Calculate the score for subchallenge 3 using the given metric
:param pred_ccm: predicted co-clustering matrix
:param pred_ad: predicted ancestor-descendant matrix
... | 5,354,191 |
def _prv_keyinfo_from_wif(
wif: String, network: Optional[str] = None, compressed: Optional[bool] = None
) -> PrvkeyInfo:
"""Return private key tuple(int, compressed, network) from a WIF.
WIF is always compressed and includes network information:
here the 'network, compressed' input parameters are pass... | 5,354,192 |
def network_opf(network,snapshots=None):
"""Optimal power flow for snapshots."""
raise NotImplementedError("Non-linear optimal power flow not supported yet") | 5,354,193 |
def dp_split(words: Sequence[str], line_limit: int = 80) -> List[List[str]]:
"""
TODO
:param words:
:param line_limit:
:return:
"""
pass | 5,354,194 |
def r2_on_off():
"""Switch on/off relay 2"""
r2_cmd_packet = b'\x04\x14\x02\x00\x00\xe6\x0f'
ser_relay.write(r2_cmd_packet) | 5,354,195 |
def build_cmake_defines(args, dirs, env_vars, stage):
"""
Generate cmake defines
:param args: The args variable generated by parse_parameters
:param dirs: An instance of the Directories class with the paths to use
:param env_vars: An instance of the EnvVars class with the compilers/linker to use
... | 5,354,196 |
def server() -> None:
"""Старт сервера"""
class PredictionServicer(predictions_pb2_grpc.PredictionServicer):
def PredictIris(self, request, context):
response = predictions_pb2.PredictResponse()
response.iris_type = predictions.predict_iris(request.sepal_length,
... | 5,354,197 |
def wasLastResponseHTTPError():
"""
Returns True if the last web request resulted in an erroneous HTTP code (like 500)
"""
threadData = getCurrentThreadData()
return threadData.lastHTTPError and threadData.lastHTTPError[0] == threadData.lastRequestUID | 5,354,198 |
async def update_rates(
user_id: str = None,
client_id: str = None,
new_amount: str = None,
session: Session = Depends(get_session),
):
"""Update a rate."""
statement = (
select(Rate)
.where(Rate.user_id == user_id)
.where(Rate.client_id == client_id)
.where(Rate.... | 5,354,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.