content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def split_SAM(samFile, n):
""" Given a sam file, separate the header line from the remaining entries,
record which chromosomes are present in the reads, and split the reads
into n chunks.
"""
header = []
chroms = set()
transcript_lines = []
with open(samFile, 'r') as f:
... | b79eadaf183b32ac2e75424a5698068e14bcba4a | 3,612,300 |
def count_set_bits(number):
""" Returns the number of set bits in number """
count = 0
while number:
count += number & 1
number >>= 1
return count | b6326b77d6fb14ff31712571837396fcf2e2b0c0 | 3,612,301 |
def generate_trace(npts, dt, o):
"""
This populates the trace
"""
tr = obspy.Trace()
tr.stats.network = 'IL'
tr.stats.station = 'UIC'
tr.stats.channel = 'SES'
tr.stats.starttime = o - 30
tr.stats.sampling_rate = 1/dt
tr.stats.delta = dt
tr.stats.npts = npts
... | d18e42086ed78a83d97a64bfc6c1384e9573e72c | 3,612,302 |
def gaussian_2d(size, x0=0, y0=0, sigma_x=1, sigma_y=1, peak=1, dtype=np.float64):
"""
Returns a 2d Gaussian in a square 2d numpy array.
Default is a centered disc of spread=peak=1.
:param size: The height and width of returned array (pixels)
:param x0: x coordinate of center (pixels)
:param y... | 92905132e847b215b800f226e1d8390140b95ddc | 3,612,303 |
import os
def get_user_from_cache(user_id):
"""Get User from cache."""
logger.info("Searching user in cache files.")
try:
db_cache_file_path = USER_CACHE_DIR + "/" + user_id + ".json"
if os.path.isfile(db_cache_file_path):
logger.info("Found user in cache with id %s", user_id)... | 5f1b5e250c6c4916eb91551914bd70c535f37500 | 3,612,304 |
def FunConstantFold(fun: ir.Fun, allow_conv_conversion) -> int:
"""Relies solely on the ins.operand_def info"""
return ir.FunGenericRewriteWithBbl(fun, _InsConstantFold,
allow_conv_conversion=allow_conv_conversion) | 41b0d4799b6f93eff35139ddbf6a3cf7e0aef08c | 3,612,305 |
def linear_ramp(t, t0=0.0, dt=1.0, y0=0.0, dy=1.0):
"""Linear Ramp Function
This function describes the linear transition between two constant values.
Parameter
---------
t : np.ndarray
Time variable
t0 : float
Start time of the ramp
dt : float
Transition length
... | f1e3fe98651b434ff60e77a4740559fadd539d56 | 3,612,306 |
def add_flow_draft(client: SymphonyClient, name: str) -> FlowDraft:
"""This function add flow draft
:param name: Name of the flow draft
:type name: str
:raises:
* FailedOperationException: Internal symphony error
:return: FlowDraft object
:rtype: :class:`~psym.common.data_class.FlowDr... | 6910b1512140c6b6b5f4c870525f0fd641baee3b | 3,612,307 |
def hazard_ratio(y_true, x, model_coefs, threshold):
"""Hazard ratio can be interpreted as the chance of an event occurring
in the group A divided by the chance of the event occurring in the group B
Parameters
----------
y_true : pandas.DataFrame
DataFrame with annotation of samples. Two co... | 57a67249d33474ec5bf84007c707122da07558c7 | 3,612,308 |
def check_par():
"""Return two intervals that give different results for parallel resistors.
>>> r1, r2 = check_par()
>>> x = par1(r1, r2)
>>> y = par2(r1, r2)
>>> lower_bound(x) != lower_bound(y) or upper_bound(x) != upper_bound(y)
True
"""
r1 = interval(1, 1) # Replace this line!
... | 8872dc7aab982473790efb9eaf0f7f8b82043b5e | 3,612,309 |
def ri2rr(data):
"""
Append imaginary data to end of real data, returning a real array.
"""
s = list(data.shape)
half = int(s[-1])
s[-1] = half * 2
n = np.empty(s, data.real.dtype)
n[..., :half] = data.real
n[..., half:] = data.imag
return n | fd4679b788cb7cfa0d73500d04adbca9b6277258 | 3,612,310 |
import json
import shutil
def init_project(project_id,
project_name=None,
project_description=None,
project_authors=None):
"""Initialize the necessary files specific to the web app."""
if not project_id and not isinstance(project_id, str) \
and l... | 58c59589cf54d37a9720588c2b9c692943ef8d4b | 3,612,311 |
import os
def create_certificate(path=None, text=False, csr=None, timeout=120, **kwargs):
"""
Create a certificate by asking the master to sign a certificate signing
request (CSR) or create a CSR on-the-fly.
path:
Path to write certificate to. Either ``path`` or ``text`` must be
speci... | 070e99ef903b336da673c3922c0487ae7bab1582 | 3,612,312 |
def is_segmental(a_char: str) -> bool:
"""
Whether a character is one that is used in the
International Phonetic Alphabet to represent something
that is not a diacritic, and can stand on its own.
This means characters that can represent a
consonant or vowel.
"""
return elem_w(strict_segmentals)(a_char) | dabb7c353cd61d228a0e586ffbee950652d2ffc9 | 3,612,313 |
def merge(arr1: Array, arr2: Array) -> Array:
"""
:param arr1, arr2: Two sorted arrays (descending order)
"""
if len(arr1) == 0: return arr2
if len(arr2) == 0: return arr1
resArr = Array(arr1.type)
it1, it2 = iter(arr1), iter(arr2)
tmp1, tmp2 = map(next, [it1, it2])
while True:
... | a2465b18e3eba9e079580173e419089a8482f875 | 3,612,314 |
def _get_storage_service(storage_service_id):
"""Return Storage Service with ID or None.
Unlike elsewhere in our application, here we do not fall back to
a different StorageService if the user-supplied ID is invalid to
prevent inaccurate information from being returned.
:param storage_service_id: ... | 2dbd9a71767479df5807e3d077d6d52598cc45cf | 3,612,315 |
from typing import List
import binascii
import logging
def sign_tx(hw_session: HWSessionBase, rt_data: AppRuntimeData, utxos_to_spend: List[wallet_common.UtxoType],
tx_outputs: List[wallet_common.TxOutputType], tx_fee):
"""
Creates a signed transaction.
:param hw_session:
:param utxos_to_s... | fde892413fe5d75970f2684f12d43a22a7fc593e | 3,612,316 |
import sys
def format_error_and_line():
"""Return a brief description of the current exception as a string."""
exception_type, value, tb = sys.exc_info()
return format_error_and_line_from_info(exception_type, value, tb) | 57369b6b92dfea3a5435a385ef97a4749dd342f9 | 3,612,317 |
def phases_from_complex(wts, continuous=False, do_detrend=False):
"""Calculates phases from 1d or 2d wavelet/hilbert arrays, dim0 is time"""
if len(wts.shape) == 1:
#1d
phasen = n.arctan2(wts.imag,wts.real)
if not (continuous or do_detrend):
return phasen
else:
... | ef0dc62e5f9212db6b01b1c753c3e2a3c63bd80e | 3,612,318 |
import time
def create_shared_link(folder_id):
"""
Creates an Internet accessible shared link of folder given its identifier.
:param folder_id: Folder identifier.
:return: Shared link if the creation was successful, None otherwise.
"""
box_client = Client(JWTAuth.from_settings_file(BOX_CONFIG_... | 7bebeba7e1243741c4799d9bff7e387fca0785e1 | 3,612,319 |
def lstr(filepath: str) -> str:
"""Alias for lstring"""
return lstring(filepath) | 86eb2a378078de2c566269904be30a69a95023c1 | 3,612,320 |
def movingaverage(inputs, pvalues, dbcur):
"""
inputs: #sensor0, #sensor1, #number
outputs : value
"""
n = inputs["#number"].getvalue()
v = inputs["#sensor1"].getvalue()
if pvalues is None or len(pvalues) == 0:
# first time
values = [v, deque([v] * n)]
else:
q =... | 6b00d33aa1544f18fd93cda84c7ddcbc88368a3f | 3,612,321 |
def pjax(template_names, request, default="pjax_base.html"):
"""
Returns template name for request.
:param request: Django request or boolean value
:param template_names: Base theme name or comma-separated names of base and
pjax templates.
Examples::
{% extends "base.html"|pjax:requ... | e74b1c76abfc68999c316021e6b70f6210125a2a | 3,612,322 |
import functools
def opt(arg, help=None, type=None, abbrev=None, choices=None, metavar=None):
"""
Decorator for annotating optional arguments
"""
abbrev = abbrev or arg[0]
return functools.partial(
_annotate, arg, (help, 'option', abbrev, type, choices, metavar)) | a16fc8ebb2aa7d4baeb1047904abf65181acdb13 | 3,612,323 |
def wrap_scikit_classifier(scikit_class):
"""Wrap a sklearn classifier as a BaseNode subclass.
The wrapper maps these node methods to their sklearn equivalents:
- _stop_training -> fit
- _execute -> predict
"""
newaxis = numpy.newaxis
# create a wrapper class for a sklearn classifier
... | 70b71f1cf7f3bc250a77e12f19b183f17fc6e680 | 3,612,324 |
import os
def get_arkouda_numlocales():
"""
Returns a default number of locales to use. 2 if Arkouda has multilocale
support, 1 otherwise. Can be overridden with ARKOUDA_NUMLOCALES.
:return: number of locales
:rtype: int
"""
if is_multilocale_arkouda():
return int(os.getenv('A... | bf62a9d8f70972a7deb4b8924db2015c4c880314 | 3,612,325 |
def for_each_client_jit(client_init: ClientInit, client_step: ClientStep,
client_final: ClientFinal) -> ForEachClient:
"""Creates a for each client function backed by `jax.jit`."""
client_init_jit = jax.jit(client_init)
client_step_jit = jax.jit(client_step)
client_final_jit = jax.jit(cl... | ffac17b20b389f7819e6d6224e39f866a702ff5e | 3,612,326 |
import re
def normalize_buffer(input_buffer):
"""Clear color from input_buffer and special characters.
:param str input_buffer: input buffer string from device
:return: str
"""
# \033[1;32;40m
# \033[ - Escape code
# 1 - style
# 32 - text color
# 40 - Background colour
... | a5922a2df22c58f7f6c4c4bf3ade7bf47a22eb7d | 3,612,327 |
def make_header(ob_size):
"""Make the log header.
This needs to be done dynamically because the observations used as input
to the NN may differ.
"""
entries = []
entries.append("t")
for i in range(ob_size):
entries.append("ob{}".format(i))
for i in range(4):
entries.app... | 82aa8359dad2e78f8d161a1811a7d71b2e496b49 | 3,612,328 |
def reconstruct_3D(*arg):
"""
Reconstruct full size image from a cropped image
Parameters
----------
arg[0] : string
The path and image file name of the original image.
arg[1] : string
The path and image file name of the segmented image.
arg[2]: ndarray
Coordenates of th... | 9cc5ef68fcd4fa11da3a877a2ed6ab23e42a46a4 | 3,612,329 |
def rowslice(table, *sliceargs):
"""
Choose a subsequence of data rows. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 5],
... ['d', 7],
... ['f', 42]]
... | 5da57bd651e6093dda783d1ade9dde1a55ecf2a4 | 3,612,330 |
def evaluate_g8( mu, kappa, nu, sigma, s8 ):
"""
Evaluate the eighth constraint equation and also return the jacobian
:param float mu: The value of the modulus mu
:param float kappa: The value of the modulus kappa
:param float nu: The value of the modulus nu
:param float sigma: The value of the... | d1be8deb9f38dae55082a341e2501044d7b2aef7 | 3,612,331 |
import os
def listroot():
"""Return list of filenames contained in root directory."""
return os.listdir('/') | eb189ce50e834b2359ba207a2ef7606a93002109 | 3,612,332 |
def normalize_company_id_length(business_id):
"""
Normalize given Company ID to 8-digits format.
Example:
========
>>> company_id = "27074358"
>>> normalize_company_id_length(company_id) == "27074358"
True
>>> company_id = "2707435"
>>> normalize_company_id_leng... | 894d455a684e5d8b490af55577e4c22c27020875 | 3,612,333 |
def create_cnn_model() -> tf.keras.Model:
"""Returns a sequential keras CNN Model."""
return tf.keras.Sequential(
[
tf.keras.layers.Conv2D(
16,
8,
strides=2,
padding="same",
activation="relu",
inp... | f4d0850fd4a600cd17252775975e40cad1a8b814 | 3,612,334 |
import math
def calculateXYZByPCAMethod(df, clusterNumber=20, threshold=0.5):
"""
- copy given matrix
- remove all rows/columns where all values are below given
- apply spectral analysis for colouring --> colour
- apply PCA dimension reduction --> x,y,z
- add x,y,z and colour and return matr... | 005ffb405f911e8f8a2a98a63a6c882d170c7c25 | 3,612,335 |
from typing import Callable
from typing import Any
def task(
fn: Callable, **task_init_kwargs: Any
) -> "prefect.tasks.core.function.FunctionTask":
"""
A decorator for creating Tasks from functions.
Args:
- fn (Callable): the decorated function
- **task_init_kwargs (Any): keyword argu... | 52215df1b18612ca9f67a05e5084dc18cf8ff314 | 3,612,336 |
def load_data(messages_filepath, categories_filepath):
"""
Load Messages data and Categories data, and merge then into unique dataframe.
Arguments:
messages_filepath -> Path to the CSV file containing messages
categories_filepath -> Path to the CSV file containing ca... | 9c0fdd93a8c1a1b1a807e75f40337e5195e847c2 | 3,612,337 |
import string
def format_filename(s):
"""
Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``,... | ce2e2d7ae801390251d2d7de760780099d68b81e | 3,612,338 |
def get_credentials() -> MySQLConnection:
"""
A helper function used to get the credentials for the server, simplifying
the process.
"""
# Try to get the credentials for the server.
credentials = []
try:
with open("sensitive/database_credentials", 'rt') as key:
for item i... | 8496ffba3487ec01636e9e18674c5556a78c8826 | 3,612,339 |
import os
def getGraphStructure(xml_file, graph_type="morphology"):
"""Traverse the given xml file as a tree by pre-order and return the graph structure as a parents list"""
def preorder(b, parent_idx=-1):
self_idx = len(parents)
parents.append(parent_idx)
if "body" not in b:
... | 8629d771ef2a403422813eb43b668b0790d5fbb3 | 3,612,340 |
import typing
def load_star(file_name: str) -> pd.DataFrame:
"""
Load a star file.
Arguments:
file_name - Path to the star file
Returns:
Pandas dataframe containing the star file
"""
header_names: typing.List[str]
import_names: typing.List[str]
skip_index: int
star_data: ... | deae28ec048c73829c1adf77d97bff37cca9ed92 | 3,612,341 |
def approve_draft(request, draft_pk):
"""Approves current draft
:param request: mostly for user
:param draft_pk: Unique id for current draft
:return: DraftRegistrationApproval obj
"""
draft = get_draft_or_error(draft_pk)
user = request.user.osf_user
draft.approve(user)
return redire... | bdf0d54250f516aa8343579994285790856c081a | 3,612,342 |
from sys import flags
import six
def _check_perms(obj_name, obj_type, new_perms, cur_perms, access_mode, ret):
"""
Helper function used by ``check_perms`` for checking and setting Grant and
Deny permissions.
Args:
obj_name (str):
The name or full path to the object
obj_t... | 7dc7b687f86fc6c56859ebb57c2b7364f7091dc5 | 3,612,343 |
from pathlib import Path
from typing import Dict
from typing import Any
from typing import Optional
def update_dvc_config(
path: Path,
config: Dict[str, Any],
workflow: Optional[str] = None,
verbose: bool = False,
silent: bool = False,
force: bool = False,
) -> bool:
"""Re-run the DVC comm... | 73f76d8ebce2be40e44c9e54cc8679ee4946c7ce | 3,612,344 |
def IsRuntype_RealTrade():
"""运行模式: 是否实盘交易"""
run_type = Environment.get_instance().config.base.run_type
return run_type == RUN_TYPE.LIVE_TRADING | 16dd39dc5a3bd2d45e020ed056cc1631eff17005 | 3,612,345 |
def load_model(opts):
"""
Load models (here we refer to them as data) from load_path
"""
load_data = {}
load_datas = []
path = opts.load_path if opts.load_path is not None else []
if path is not None:
print(" [*] Loading data from {}".format(path))
load_data = torch_load_cpu... | 6fd806358fbd4a60bfba693c46d19b3b36d938ac | 3,612,346 |
import numpy
def hi_lo(data_series, current_max, current_min):
"""Determine the new highest and lowest value."""
try:
highest = numpy.max(data_series)
except:
highest = max(data_series)
if highest > current_max:
new_max = highest
else:
new_max = current_ma... | 63bca68d4af2e50b1c27b5095261c575b35c75d8 | 3,612,347 |
def ChangeBackslashToSlashInPatch(diff_text):
"""Formats file paths in the given patch text to Unix-style paths."""
if not diff_text:
return None
diff_lines = diff_text.split('\n')
for i in range(len(diff_lines)):
line = diff_lines[i]
if line.startswith('--- ') or line.startswith('+++ '):
diff... | 88dce5e16fb400ef2aa1c16950e45491baa5c961 | 3,612,348 |
def parse_line(text: str) -> str:
"""Parses one line into a word."""
text = text.rstrip()
if text[0] == "+":
return text[1:]
if text[0] == "@" or text[0] == "!" or text[0] == "$":
w = text.split("\t")[1]
if "#" in w:
return w.split("#")[0].rstrip()
else:
... | 44e8bd0defc071438aea15002d3e3c6838e61bfb | 3,612,349 |
from typing import Tuple
from typing import Sequence
def map_gauss_coef_pares(
node_coef_pares: Tuple[float, float], seg_a: float, seg_b: float
) -> Sequence[Tuple[float, float]]:
"""
Linearly maps node_coef_pares on [seg_a, seg_b] to [-1, 1],
Given the pares of nodes and coefficient finds the approx... | 226e95eea61c9534fd7b548eea7e4294e2ceb7de | 3,612,350 |
from typing import Union
def vpt(candles: np.ndarray, source_type: str = "close", sequential: bool = False) -> Union[float, np.ndarray]:
"""
Volume Price Trend (VPT)
:param candles: np.ndarray
:param source_type: str - default: "close"
:param sequential: bool - default=False
:return: float |... | 7889b6f54485afd29fc4b9b0d5df5e73838dfcbf | 3,612,351 |
import locale
def get_shell_lc() -> str:
"""取得當前shell的語言代碼。
Returns:
str: 當前shell的語言代碼。
"""
loc = locale.getdefaultlocale()
lc = loc[0]
return lc | 1ea0f09ede398fa1be09cec78d7704dd0db2385c | 3,612,352 |
def wilder_ma(series: nda.NdType, periods: int = 14, warm_periods: tp.Union[int, None] = None):
"""
Wilder's Moving Average
"""
if warm_periods is None:
warm_periods = periods
return ema(series, periods * 2 - 1, warm_periods) | dcbf4b4baac0955a4718a746f119dfb82edf9f9c | 3,612,353 |
def dict_to_cidr(obj):
"""
Take an dict of a Network object and return a cidr-formatted string.
:param obj:
Dict of an Network object
"""
return '%s/%s' % (obj['network_address'], obj['prefix_length']) | c915c16f28b42322c2f63743cdc43a58b964ba27 | 3,612,354 |
def replace_tuple(tuple_obj, replace_obj, replace_index):
"""Create a new tuple with a new object at index"""
if len(tuple_obj) - 1 <= replace_index:
return tuple_obj[:replace_index] + (replace_obj,)
else:
return tuple_obj[:replace_index] + (replace_obj,) + tuple_obj[replace_index+1:] | 28c32ab516eddd7feb90e6b62221f56e8106a2f5 | 3,612,355 |
from typing import Dict
def validate(business: Business, annual_report: Dict) -> Error:
"""Validate the annual report JSON."""
if not business or not annual_report:
return Error(HTTPStatus.BAD_REQUEST, [{'error': _('A valid business and filing are required.')}])
err = validate_ar_year(business=bu... | 792a7943b49947fe80640ecfcca0d0cbe3981b50 | 3,612,356 |
def _timedelta_str_to_schedule_time(time_value: str) -> str:
"""Convert time string to schedule start/end time to hexadecimale.
Args:
data: time to convert. e.g. "21:00".
Return:
Hexadecimal representation of time_value argument.
Raises:
aioswitcher.erros.EncodingError: when failed ... | db61c6f054f83dc0cb5e988ab562387e71b408aa | 3,612,357 |
def submit_WMS(job, infileList):
""" Submit the job locally or to the WMS
"""
dirac = Dirac()
job.setInputData(infileList)
job.setJobGroup('SimpleCtapipe-test')
res = dirac.submit(job)
Script.gLogger.notice('Submission Result: ', res)
return res | 92e6c1a607549a5e3c90720b0934502f49aaf45d | 3,612,358 |
import os
def FindBinary( binary, user_options ):
"""Find the path to the Gocode/Godef binary.
If 'gocode_binary_path' or 'godef_binary_path'
in the options is blank, use the version installed
with YCM, if it exists.
If the 'gocode_binary_path' or 'godef_binary_path' is
specified, use it as an absolute ... | 65b1962d249748b7ab3f39cf62aecc909aa59a7b | 3,612,359 |
import csv
import os
def process_way_chunk(nodes_dict, csv_way_nodes, build_way_csv_writer, build_areas_csv_writer):
"""
Process a chunk of nodes loaded in-memory. Associated then with ways and write lines and polygons to a csv file.
:param nodes_dict: A chunk of nodes loaded in memory.
:param csv_way... | 577d14a404bc9aa85e69c0c388a78ec60ea8e91f | 3,612,360 |
def get_attachment(msg, file_filter=default_attach_filter):
"""
获取邮件里的附件
:param msg:
:param file_filter:
:return:
"""
attachments = []
for part in msg.walk():
if part.get_content_maintype() == 'multipart': continue
if part.get_content_maintype() == 'text': continue
... | 65642e533651efc1990b8713210d0d23a00dea7a | 3,612,361 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Tensorflow Faster R-CNN demo')
parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16 res101]',
choices=NETS.keys(), default='res101')
parser.add_argu... | 9e1edb3835e75935bf1ddcc4cbb538b42efeb099 | 3,612,362 |
def search_specific(name_or_address):
"""
Allows for direct searches through the URL (not the same as the API)
"""
user = http_auth.username()
answer = {}
answer[name_or_address] = str(searcher.query(name_or_address)).split(' ', 1)[1]
return render_template('search_results.html', title='Sear... | 7ec884a84bca5a0ee2f479a9c0ae254b4e4e9fc7 | 3,612,363 |
def find_unused_port(addr="localhost", start=53589, track=True):
"""Find an unused port starting at `start` port
If track=False the returned port will not be marked as in-use and the code
will rely entirely on the ability to connect to addr:port as detection
mechanism. Note this may cause problems if p... | 508eb9907732ef049053d30cd872e4d18d554a48 | 3,612,364 |
def create_GBM(s0, mu, sigma):
"""
Generates a price following a Geometric Brownian Motion process based on the input of the arguments:
- s0: Asset inital price.
- mu: Interest rate expressed annual terms.
- sigma: Volatility expressed annual terms.
"""
sp = s0
# Generate stock value for the current s... | 12d0b9dd754e460a9da2385e151bf157255b780e | 3,612,365 |
def partial_to_query_filter(partial: Expression, model: Model, **kwargs):
"""
Convert a partial expression to a django query ``Q`` object.
Example expression structure::
Expression(And, [
Expression(Isa, [
Variable('_this'),
Pattern(test_app::Post, {})])... | 9b7503509c98d777c4177b8d98463749481821eb | 3,612,366 |
def closer_than(x1, y1, x2, y2, limitsq):
"""
Helper function to determine whether the square of the distance
between points (x1,y1) and (x2,y2) is less than or equal to limitsq.
The squares of the distances are compared to save computation time.
:Parameters:
x1: float
X ... | ae27e9432bd52c46834b085fa55d8a27523fd806 | 3,612,367 |
from pathlib import Path
import os
def stroll(
roots='.',
topdown=True,
onerror=None,
followlinks=False,
include=None,
exclude=dotfile,
directories=False,
relative=False,
with_root=None,
sort=True,
suffix=None,
separator=FILE_SEPARATOR,
ignore_missing_roots=False,
)... | f9f0ce301bc3efb65f80ef42ef49861d91cc5aa9 | 3,612,368 |
from typing import List
from typing import Dict
import json
def get_cloudrun_revisions(cloudrun: Resource, project_id: str) -> List[Dict]:
"""
Returns a list of Cloud Run Revisions for a given project.
:type cloudrun: Resource
:param cloudrun: The cloudrun resource created by googleapicli... | 8160cfad77ee86c2f070261c2cf55ae7a1ac02b9 | 3,612,369 |
import re
def do_rss_latest(parser, token):
"""
A template tag to grab the latest articles from a given feed.
The first argument is the category.
The second argument is the number of items to retrieve.
The third argument (after 'as') is the variable to store the result in.
"""
try:
... | 9029cd5e1b79630712260cc45a31737e9e6959a4 | 3,612,370 |
import torch
def random_sequence(batch_size, seq_size, seq_length, random_state=None):
"""
Args:
batch_size: Number of different sequences of the same size.
seq_size: Number of amino acids that are posible at each residue.
seq_length: Length of each sequence.
Returns:
Gen... | e7b95cffd104c43c0e4fd37b6d311612a8f04616 | 3,612,371 |
def center_crop_images(images, crop_resolution: int):
"""
Crops the center of the images
Args:
images: shape: (B, H, W, 3), H should be equal to W
crop_resolution: target resolution for the crop
Returns:
cropped images which has the shape: (B, crop_resolution, crop_resolution, 3... | 3831dde49fba737f24706c5c19c380bf7d9f9222 | 3,612,372 |
def EER(roc):
"""
Obtain the EER for one fold
"""
far, frr = roc['far'].values, roc['frr'].values
def perp(a):
b = np.empty_like(a)
b[0] = -a[1]
b[1] = a[0]
return b
# line segment a given by endpoints a1, a2
# line segment b given by endpoints b1, b2
de... | 92fe6f93f9c1f4f2e21c86974f6aee39277117e0 | 3,612,373 |
from grudge.trace_pair import interior_trace_pair
from grudge.dof_desc import as_dofdesc
from mirgecom.operators import div_operator
def test_lazy_op_divergence(op_test_data, order):
"""Test divergence operation in lazy context."""
eager_actx, lazy_actx, get_discr = op_test_data
discr = get_discr(order)
... | 3bd79b61992c2f575caa1accaeba55c311230655 | 3,612,374 |
from typing import List
from re import VERBOSE
import subprocess
def run_shell_command(arguments: List[str]) -> str:
"""Executes a shell command."""
if VERBOSE:
print(" ".join(arguments))
try:
output = subprocess.check_output(arguments).decode().strip()
except subprocess.CalledProcessE... | c0059f2b3223fde82a29ea135e82140ffe49d6df | 3,612,375 |
def get_file_name(patch):
"""Return the name of the file to which the patch should be written"""
file_name = None
for line in patch:
if line.startswith('Patch-Filename: '):
file_name = line[len('Patch-Filename: '):]
break
# If no patch-filename header, munge the subject.
if not file_name:
... | 5511b4e4d5f8ada3db17e3236c846b5af2d2303a | 3,612,376 |
def generate_n_random_symbols(n):
"""Returns `n` random upper case ASCII symbols
Args:
number_of_symbols (int): Number of symbols required
Raises:
ValueError: If n is greater than 26 and less than 0
"""
if n in range(27):
upper_case_ascii_characters = [chr(i) for i in range... | 0d0ebf747617717fbaff8b8d1baec7eee540d1dc | 3,612,377 |
def GetActiveEditorDocument():
"""Returns the active editor document and view, or (None,None) if no
active document or its not an editor document.
"""
view = GetActiveView()
if view is None or isinstance(view, TreeView):
return (None, None)
doc = view.GetDocument()
if hasattr(doc, "MarkerAdd"): # Is it an Edit... | 2cdc8367f5234d15c9074175d5db6ca53dfe05ab | 3,612,378 |
def _load_hess_inv(nrows, method, card):
"""loads inverse power"""
alpha_omega_default = None
LJ_default = None
if method == 'INV':
alpha_omega_default = 0.0
LJ_default = 1.0
alphaAjs = []
alphaBjs = []
omegaAjs = []
omegaBjs = []
#mblkszs = []
#iblkszs = []
... | 3b7bdc3974aef1453a6415b92c8e16fe79885848 | 3,612,379 |
def default_exception_serializer(exception):
"""
The default exception serializer for user exceptions in eval.
"""
return '%s: %s' % (type(exception).__name__, str(exception)) | c630ddb9ec6ffc5381c11c4b06c277e4e55910de | 3,612,380 |
def rload(path):
"""Load a dict of data from an R dump format file.
"""
with open(path, 'r') as fd:
lines = fd.readlines()
data = {}
for line in lines:
lhs, rhs = [item.strip() for item in line.split('<-')]
if rhs.startswith('structure'):
vals, dim = rhs.replace('... | d55b7ca6fdfd40c26d079ec0045862940cdbaa0c | 3,612,381 |
def _read_locs(filepath, chs, egi_info):
"""Read channel locations."""
fname = op.join(filepath, 'coordinates.xml')
if not op.exists(fname):
return chs
numbers = np.array(egi_info['numbers'])
coordinates = parse(fname)
sensors = coordinates.getElementsByTagName('sensor')
for sensor i... | 8345cf9777ed6e74a88f8c865fb98ed159b38d11 | 3,612,382 |
def link_edges(strong_edges, weak_edges):
""" Find weak edges connected to strong edges and link them.
Iterate over each pixel in strong_edges and perform breadth first
search across the connected pixels in weak_edges to link them.
Here we consider a pixel (a, b) is connected to a pixel (c, d)
if (... | 785ece94808fe405f8faa539803ee2e88474a393 | 3,612,383 |
def heading(angle):
"""
Computes cardinal direction based on heading/orientation. Assumes
robot heading is parallel to cartesian axes and 0 heading is south.
Args:
angle (float): Angle of yaw orientation
Returns:
(str): Cardinal direction
"""
if -5*np.pi/9 <= angle <= -4*np.pi/... | 4d13afbd65d8f5d0b5ab3e352023ebc13d9efeac | 3,612,384 |
import time
import os
def generate_root(name):
"""Generate a root path.
Args:
name (str): Name of the experiment.
Returns:
str: Root path.
"""
now = time.strftime("%Y-%m-%d_%H-%M-%S")
return os.path.join("_experiments", f"{now}_{slugify.slugify(name)}") | a5056c507bd2dc08d8d95e1f1681e2886540bc8c | 3,612,385 |
import copy
def remove_candidates(orders, candidates_to_remove):
"""
Remove a set of candidates from a list representing a preference order.
"""
projection = []
for c_vote in orders:
temp_vote = copy.copy(c_vote)
for c_remove in candidates_to_remove:
temp_vote.remove(c_remove)
projection... | bd0b98acefacaf9891b4ab7109d01d187f1de85a | 3,612,386 |
import time
def timethis(func):
"""Report execution time of function."""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, f"took {end-start:3.2f}s")
return result
return wrappe... | bac11d68378d2251c31abcf864f560b0d5f7a666 | 3,612,387 |
import random
def dummytable(numrows=100,
fields=(('foo', partial(random.randint, 0, 100)),
('bar', partial(random.choice, ('apples', 'pears',
'bananas', 'oranges'))),
('baz', random.random)),
... | b38a1f76bd44390000a4e1f47fed42ab27fd0b50 | 3,612,388 |
def scores_plot(scores, plot_num, threashold, title = ""):
"""Plotting the scores over episodes for different networks
Params
======
scores (list of dict): Containing at least 'scores', 'fc1_units', and 'fc2_units' for plotting
plot_num (int): dimensionality of plot (is N for an NxN plo... | 25e05520881ad1a84b1fd77c6c431ab9956a07a4 | 3,612,389 |
def rank(values, axis=0, method='average', na_option='keep',
ascending=True):
"""
"""
if values.ndim == 1:
f, values = _get_data_algo(values, _rank1d_functions)
ranks = f(values, ties_method=method, ascending=ascending)
elif values.ndim == 2:
f, values = _get_data_algo(... | 46854f0a067f3fc8342266ded9bc2a82cbe5651e | 3,612,390 |
def one_move(pos=start, step=1):
"""
Make one move from the given position `pos`.
"""
board[pos[0]][pos[1]] = step
if step == cnt:
fmt = "{{:{}d}}".format(ceil(log10(rows*cols))+1)*cols
for i in range(rows):
print(fmt.format(*board[i]))
return True
step += 1
... | 8fc2dd7c1b0191ee8b896961020d87d300c6eab6 | 3,612,391 |
import re
def _get_mainfunc_from_js(js):
""" Return main signature decryption function from javascript as dict. """
dbg("Scanning js for main function.")
m = re.search(r'\w\.sig\|\|([$\w]+)\(\w+\.\w+\)', js)
funcname = m.group(1)
dbg("Found main function: %s", funcname)
function = _extract_fun... | 42ad48777bfd045397ada7e353b10b3c9569d868 | 3,612,392 |
def dissociate(op, args):
""" Given an associative operator, return a flattened list result """
result = []
def collect(subargs):
for arg in subargs:
if arg.func == op:
collect(arg.args)
else:
result.append(arg)
collect(args)
return r... | 1b517738d5c27cd27f308483673e3f5c5fb40bbc | 3,612,393 |
from pgxnclient.zip import ZipArchive
from pgxnclient.tar import TarArchive
def from_file(filename):
"""Return an `Archive` instance to handle the file *filename*"""
for cls in (ZipArchive, TarArchive):
a = cls(filename)
if a.can_open():
return a
raise PgxnClientException(
... | 519d92fdc780f4b40ead75896d433703162f897d | 3,612,394 |
def deserialize_population_frame(frame, inplace=False):
"""Deserializes a population `pd.DataFrame` from plain text.
Args:
frame: A `pd.DataFrame` produced by `serialize_population_frame`.
inplace: Whether to deserialize `frame` inplace instead of creating a copy.
Returns:
A `pd.DataFrame` with dese... | ad8fecd593cb918f0bbf0c43ef876059e865cc2e | 3,612,395 |
import torch
def latent_kl(prior_mean, posterior_mean):
"""
:param prior_mean:
:param posterior_mean:
:return:
"""
kl = 0.5 * torch.pow(prior_mean - posterior_mean, 2)
kl = torch.sum(kl, dim=[1, 2, 3])
kl = torch.mean(kl)
return kl | 2785902d758c45a4ad8be4f38b88e8cfb5bbc6ce | 3,612,396 |
from sys import argv
def handle_args():
"""Reads the commandline args and adjusts initial values of globals values to match
:return: False if there was an error with the args, or True if args processed ok.
"""
global resize_output, resize_output_width, resize_output_height, min_score_percent, object_... | e80f19b9213601e69fb364fafea23fa8c7eb3904 | 3,612,397 |
def query_index(index, query):
"""Returns search results for your given query"""
es = get_elastic_client()
if not es:
return []
search = es.search(
index=index,
body={
"query": {
"multi_match": {
"query": query,
... | 731036ff858e55d5b5d1d5af80a548fbd858efd1 | 3,612,398 |
def get_db_dir():
"""
Just return the default dir listed above
:return: the default location for the sqllite database
"""
return defaultdir | 1d5bb8ac177e65abb2788e686d2db30bec70bbd8 | 3,612,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.