content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def set_train_val_test_sequence(df, dt_dset, rcpower_dset, test_cut_off,val_cut_off, f = None ):
"""
:param df: DataFrame object
:param dt_dset: - date/time header name, i.e. "Date Time"
:param rcpower_dset: - actual characteristic header name, i.e. "Imbalance"
:param test_cut_off: - value to pass... | 49,800 |
def canonical_url_cleaner(matches):
"""
Given an iterable of URL matches, return an iterable where URLs have been
canonicalized.
"""
for key, match, line, lineno in matches:
if is_filterable(match):
canonical = canonical_url(match)
if TRACE:
logger_deb... | 49,801 |
def orders(request):
"""显示用户的所有订单"""
username = request.user.get_username()
# 获取所有的uesername=用户名的记录,然后将记录按照time逆序排列
all_orders = Order.objects.filter(username=username)
times = all_orders.values('time')
# 获取不同的时间,因为对于不同的用户按照时间分类即可,相同的时间下的肯定是同一单
distinct_times = set()
for distinct_time in... | 49,802 |
def convert_filename(filename):
"""Fix a filename"""
# Try and replace illegal characters
filename = replace_characters(filename)
# Remove remaining illegal characters
filename = remove_characters(filename)
return filename | 49,803 |
def create(
path_or_url: str,
output_dir: Optional[Path] = None,
) -> Path:
"""
Generate a new project from a composition file, local template or remote template.
Args:
path_or_url: The path or url to the composition file or template
output_dir: Where to generate the project
Re... | 49,804 |
def get_camera_index(glTF, name):
"""
Return the camera index in the glTF array.
"""
if glTF.get('cameras') is None:
return -1
index = 0
for camera in glTF['cameras']:
if camera['name'] == name:
return index
index += 1
return -1 | 49,805 |
def copy_collection(source_collection, target_db, temp_dir_path=None,
verbose=True):
"""Copies the contents of the given source collection to that of the
target one.
Arguments
---------
source_collection : pymongo.collection.Collection
The collection whose contents will ... | 49,806 |
def local_se(df, kernel, deg, width):
""" This function is used to calculate the local standard errors, based on
estimation results of a local polynomial regression.
"""
if deg != 1:
print(
"WARNING: function local_se is currently hard-coded for ",
"polynomials of degree... | 49,807 |
def p_bname_grow(p):
"""bname : bname ':' string"""
p[0] = p[1].with_suffix(p[3]) | 49,808 |
def data(get_api_data):
"""Get Weather data.
For testing I used pickle to
"""
import pickle
GET_API_DATA = get_api_data
if GET_API_DATA:
weather_data = WeatherData()
with open('today_weather_data.tmp', 'wb+')as f:
pickle.dump(weather_data, f)
else:
with o... | 49,809 |
def remove_root_pvc(file_system_id):
"""Remove the root persistent volume claim for an EFS file system."""
delete_namespaced_persistent_volume_claim(
"efs-stunnel-{}".format(file_system_id),
namespace,
{}
) | 49,810 |
def test_random_choice_with_negative_probability():
"""
Case: test random choice with negative probability.
Expect: probabilities are not non-negative error message.
"""
infimum = -10_000
supremum = 10_000
number_quantity = abs(infimum) + abs(supremum)
fast_random = FastRandomChoice()
... | 49,811 |
def test_get_counters(squid_check):
"""
Squid can return a trailing newline at the end of its metrics and it would be
treated as a metric line: an error would be raised attempting to parse the line
due to a missing = character.
See https://github.com/DataDog/integrations-core/pull/1643
"""
w... | 49,812 |
def json_format(subtitle, data):
"""
Format json to string
:param subtitle: description to text
:type subtitle: string
:param data: content to format
:type data: dictionary
"""
msg = subtitle+':\n'
for name in data: msg += name+': '+data[name]+'\n'
return msg.strip() | 49,813 |
def definition(ctx):
"""This group allow handling API definition commands from templating and value files"""
pass | 49,814 |
def cloud_build(project,
container,
tag,
async_,
package,
target,
bazel_version,
bazel_toolchains_base_dir,
bucket=None,
tarball=None):
"""Runs the build in the cloud. More i... | 49,815 |
def _nSentencesInWordMap(wtm):
"""Return the number of valid word sequence in wtm"""
result = [0] * len(wtm) + [1]
for i_ in xrange(len(wtm)):
i = len(wtm) - i_ - 1
for j in wtm[i].iterkeys():
result[i] += result[j]
return result[0] | 49,816 |
def datum_entspricht_din5008(eingegebenes_datum=abDatum):
"""
Prüft, ob das übergebene Datum der DIN 5008 entspricht.
Zeitpunkte vor 2000-01-01 werden ignoriert!
Siehe auch https://de.wikipedia.org/wiki/Datumsformat#DIN_5008.
:param eingegebenes_datum: String
:return: Boolian
"""
din500... | 49,817 |
def hflip(img):
# type: (Tensor) -> Tensor
"""Horizontally flip the given the Image Tensor.
Args:
img (Tensor): Image Tensor to be flipped in the form [C, H, W].
Returns:
Tensor: Horizontally flipped image Tensor.
"""
if not _is_tensor_a_torch_image(img):
raise TypeError... | 49,818 |
def gfalternate_gotnogaps(data,label,mode="verbose"):
"""
Returns true if the data series has no gaps, false if there are gaps
"""
return_code = True
if numpy.ma.count_masked(data)==0:
if mode=="verbose":
msg = " No gaps in "+label
logger.info(msg)
return_code... | 49,819 |
def expm_tS_v2(t, S):
"""
Compute expm(t*S) using AlgoPy eigendecomposition and an identity.
t: truncated univariate Taylor polynomial
S: symmetric numpy matrix
"""
# Compute the eigendecomposition using a Taylor-aware eigh.
L, Q = eigh(t * S)
return dot(Q * exp(L), Q.T) | 49,820 |
def command():
"""
Return the tested command.
"""
return module.Command() | 49,821 |
def computeSWC(D, cl_cores, ncl, shortpath):
"""
:param D: 2D dataset of n*d, i.e. n the number of cores (initial clusters) with d dimension
:param cl_cores: cluster label of each cores
:param ncl: the number of clusters
:param shortpath: the shortest path length matrix of core-based graph
... | 49,822 |
def mknewdir(path):
"""Create a new directory if it does not pre-exist,
otherwise, delete it and then re-create it."""
rmpath(path)
#shutil.rmtree(path)
os.makedirs(path) | 49,823 |
def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):
"""Use high precision for cumsum and check that final value matches sum
Parameters
----------
arr : array-like
To be cumulatively summed as flat
axis : int, optional
Axis along which the cumulative sum is computed.
T... | 49,824 |
async def handler(client, user, operation, payload, db):
"""
Handler for accessing *Tech Support* API
:param client: client that sent payload
:type client: websockets.WebSocketCommonProtocol
:param user: user that sent payload
:type user: ecusers.User
:param operation: operation specified i... | 49,825 |
def plot_slices(img_arr, show=True):
"""
Plot each slice of a 3D image, showing one slice at a time (use a and d keys to switch between slices).
:param img_arr: 3D image array to plot.
:param show: Whether or not to show the plot in addition to plotting the image.
:return: None.
"""
# Credi... | 49,826 |
def setup_logging() -> None:
"""Setup logging for Fava."""
logging.basicConfig(level=logging.INFO, format="%(message)s")
logging.getLogger("werkzeug").addFilter(filter_api_changed) | 49,827 |
def read_data_min(server, port, user, pwd, instrument):
"""从mongo中读取分钟数据(含实时)"""
#取数据
client = py_at.MongoDBClient.DBConn(server, port)
client.connect(user, pwd)
db = client.get_database("future_min")
coll = client.get_collection("future_min", instrument)
docs = coll.find()
coll_real = client.get_collection("... | 49,828 |
def main():
"""Print out customized welcome message"""
args = get_args()
word = args.word
side = 'starboard' if args.starboard else 'larboard'
char = word[0].lower()
if word[0].islower():
article = 'an' if char in 'aeiou' else 'a'
else:
article = 'An' if char in 'aeiou' else... | 49,829 |
def test_cray_capmc_set_power_cap(cli_runner):
""" Test `cray capmc set_power_cap` for expected commands"""
runner, cli, _ = cli_runner
result = runner.invoke(cli, ['capmc', 'set_power_cap'])
outputs = [
"cli capmc set_power_cap [OPTIONS] COMMAND [ARGS]...",
"create",
]
for... | 49,830 |
def test_station_setup():
"""
Test station setup
Test that the station is set up correctly by checking the dimensions of the
station produced.
"""
model = set_up_model()
a = model.width == 740
b = model.height == 700
assert a and b | 49,831 |
def _demo(seed=None, out_fc=False, SR=None, corner=[0, 0], angle=0):
"""Generate the grid using the specified or default parameters
"""
corner = corner # [300000.0, 5000000.0]
dx, dy = [1, 1]
cols, rows = [3, 3]
if seed is None:
# seed = rectangle(dx=1, dy=1, cols=3, rows=3)
... | 49,832 |
def measure_bb_tpdm(spatial_dim, variance_bound, program, quantum_resource,
transform=jordan_wigner, label_map=None):
"""
Measure the beta-beta block of the 2-RDM
:param spatial_dim: size of spatial basis function
:param variance_bound: variance bound for measurement. Right now thi... | 49,833 |
def singlepass(fn):
"""
Will take the mean of the iterations if needed.
Args:
fn (Callable): Heuristic function.
Returns:
fn : Array -> Array
"""
@_wraps(fn)
def wrapper(self, probabilities):
if probabilities.ndim >= 3:
# Expected shape : [n_sample, n_... | 49,834 |
def remove_dihedral(mol, a, b, c, d):
"""
utils.remove_dihedral
Remove a specific dihedral in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c: Atom index removing a specific dihedral (int)
Returns:
boolean
"""
if not hasattr(mol, 'dihedrals'):
... | 49,835 |
def load_mo(elem):
"""
This loads the managed object into the current name space
Args:
elem (str): element
Returns:
MangedObject
"""
import inspect
mo_class_id = elem.tag
mo_class = load_class(mo_class_id)
mo_class_params = inspect.getargspec(mo_class.__init__)[0... | 49,836 |
def partialdot(mpa1, mpa2, start_at, axes=(-1, 0)):
"""Partial dot product of two MPAs of inequal length.
The shorter MPA will start on site ``start_at``. Local dot products
will be carried out on all sites of the shorter MPA. Other sites
will remain unmodified.
mpa1 and mpa2 can also have equal l... | 49,837 |
def thresh_ious(gt_dists, pred_dists, thresh):
"""
Computes the contact intersection over union for a given threshold
"""
gt_contacts = gt_dists <= thresh
pred_contacts = pred_dists <= thresh
inter = (gt_contacts * pred_contacts).sum(1).float()
union = union = (gt_contacts | pred_contacts).s... | 49,838 |
def encode_sentences(sentences, tokenizer, language, mode):
"""对句子进行编码
@param sentences: 要编码的句子列表
@param tokenizer: 使用的字典
@param language: 语言
@param mode: 模式
@return: 编码好的句子列表,最大句子长度
"""
if language == 'zh':
return _encode_sentences_keras(sentences, tokenizer)
elif language =... | 49,839 |
def test_airflow_config_file(File):
"""
Tests about airflow configuration
"""
config_file = File('/var/lib/airflow/airflow/airflow.cfg')
assert config_file.exists is True
assert config_file.is_file is True
assert config_file.user == 'airflow'
assert config_file.group == 'airflow'
as... | 49,840 |
def calc_scores(line_executions=LINE_EXECUTIONS, prior=PRIOR):
"""Return 'fault' score for each line, given prior and observations."""
return {
line: float(
execution_counts.negative_cases + prior.negative_cases
) / (
execution_counts.positive_cases + prior.positive_cases... | 49,841 |
def freeze(sess, output_file_path, output_node_names):
"""Freeze and shrink the graph based on a session and the output node names."""
with TemporaryDirectory() as temp_dir_name:
checkpoint_path = os.path.join(temp_dir_name, 'model.ckpt')
tf.train.Saver().save(sess, checkpoint_path)
fre... | 49,842 |
def symmetric_variable_summaries(var, metrics=None):
"""
Set summaries for a symmetric variable, e.g., the output of tanh.
Args:
var: tensorflow variable.
metrics: set a list of metrics for evaluation. Support: mean, stddev, max, min, histogram.
Default: mean, stddev.
Returns:
summaries: a li... | 49,843 |
def normalize_parameters(raw_parameters, minvals, maxvals):
"""takes in a list of parameters and does simple min/max normalization according to min/max values
INPUTS
raw_parameters: length n, containing parameters for a star
minvals: length n, minimum parameter values
maxvals: length n, max paramete... | 49,844 |
def read_users(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
current_user: models.User = Depends(deps.get_current_active_superuser)
) -> Any:
"""
Retrieve users.
"""
users = crud.user.get_multi(db, skip=skip, limit=limit)
return users | 49,845 |
def euler(a, b, c):
"""
Calculate a three dimensional rotation matrix from the euler angles.
@param a: alpha, angle between the x-axis and the line of nodes
@param b: beta, angle between the z axis of the different coordinate systems
@param c: gamma, angle between the line of nodes and the X-axis
... | 49,846 |
def restart_control():
"""Restarts the contrail control services."""
execute("restart_control_node", env.host_string) | 49,847 |
def guardar_imagen_cv2(img_path, filtro, filtro_name="", output_dir=""):
"""
img_path: directorio de la imagen
filtro: funcion para aplicar filtro
file_path: directorio donde guardaremos las imagen
"""
try:
imagen_preprocesada = aplicar_preproceso(img_path, filtro)
except:
pr... | 49,848 |
def create_begin_files(params):
"""Create initial files for HADDOCK3 run."""
run_dir = params['run_dir']
data_dir = run_dir / 'data'
begin_dir = run_dir / 'begin'
run_dir.mkdir()
begin_dir.mkdir()
data_dir.mkdir()
copy_files_to_dir(params['molecules'], data_dir)
copy_molecules_to_b... | 49,849 |
def dump_sender_receiver_with_noise(agent_1: torch.nn.Module,
agent_2: torch.nn.Module,
dataset: 'torch.utils.data.DataLoader',
noise_prob: float,
max_len:int,
... | 49,850 |
def split_list(xs, at):
"""Split a list into sublists by a specific item value
E.g split_list(['a', 'b', '.', 'c', '.', 'd') = [['a', 'b'], ['c'], ['d']
Parameters
----------
x
A list
at
The item value to split by
Returns
-------
List[List]
A list of sublists split... | 49,851 |
def load_pex(path_to_pex, include_deps=True):
"""Loads pex file and its dependencies to the current python path"""
abs_path_to_pex = os.path.abspath(path_to_pex)
Log.debug("Add a pex to the path: %s" % abs_path_to_pex)
if abs_path_to_pex not in sys.path:
sys.path.insert(0, os.path.dirname(abs_path_to_pex))
... | 49,852 |
def do(the_state_machine, pre_context_sm, BeginOfLinePreContextF, BeginOfStreamPreContextF):
"""Sets up a pre-condition to the given state machine. This process
is entirely different from any concatenation or parallelization
of state machines. Here, the state machine representing the pre-
condi... | 49,853 |
def connect_db():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# cre... | 49,854 |
def Sexp(x,G,N):
"""
Stochastic exponentiation function
Note: G should be such that G<<N
Parameters
----------
x: Stochastic bit-stream
G: Positive integer
N: Integer specifying the number of states
Returns
-------
A stochastic bit-stream approximating exp(-2Gx)
""... | 49,855 |
def truncate(s: str, length: int = DEFAULT_CURTAIL) -> str:
"""
Truncate a string and add an ellipsis (three dots) to the end if it was too long
:param s: string to possibly truncate
:param length: length to truncate the string to
"""
if len(s) > length:
s = s[: length - 1] + '…'
re... | 49,856 |
def amp_kd_calc(amph_sites_ff, element):
"""
aem_calc calculates the partition coefficient for a specified trace element
that is in equilibrium with a given amphibole composition according to
Humphreys et al., 2019.
supported elements = ['Rb','Sr','Pb','Zr','Nb','La','Ce','Nd','Sm',
'Eu','Gd','Dy','... | 49,857 |
def _compute_errors_and_split(p, bezier, u):
"""Compute the maximum and rms error between a set of points and a bezier curve"""
dists = np.linalg.norm(bezier.xy(u)-p,axis=1)
i = np.argmax(dists)
rms = np.sqrt(np.mean(dists**2))
if i==0:
return 0.0, rms, len(p)//2
elif i==len(p)-1:
return 0.0, rms, len(p)//2
... | 49,858 |
def rebin_flux(target_wavelength, source_wavelength, source_flux):
"""Rebin a flux onto a new wavelength grid."""
targetwl = target_wavelength
originalwl = source_wavelength
originaldata = source_flux[1:-1]
# The following is copy-pasted from the original fluxcal.py
originalbinlimits = ( origina... | 49,859 |
def rate_match(residue, bead, match):
"""
A helper function which rates how well ``match`` describes the isomorphism
between ``residue`` and ``bead`` based on the number of matching atomnames.
Parameters
----------
residue : networkx.Graph
A graph. Required node attributes:
... | 49,860 |
async def wahlen(event: hikari.InteractionCreateEvent):
"""
wird getriggert wenn jemand eine person waehlt
:param ctx:
:return:
"""
e = event
if not isinstance(e.interaction, hikari.ComponentInteraction): return
i: hikari.ComponentInteraction = e.interaction
guild = i.get_guild()
... | 49,861 |
def isNotEmptyString(input:str):
"""
this function check a string is not empty.
:param input:str: given string
"""
if isNotNone(input):
tmp = input.lstrip(' ')
return isStr(input) and (len(tmp) > 0)
else:
return False | 49,862 |
def show_queue(event_id):
"""
Pokazuje listę osób chętnych do rezerwacji wydarzenia (kolejka). Działa
tylko dla właściciela wydarzenia.
:type event_id: int
:param event_id: id wydarzenia
"""
try:
with conn:
with conn.cursor() as cur:
cur.execute("""select... | 49,863 |
def _load_contact_template(user_email, email_details):
"""
Loads the email contents and returns the template for contact us
"""
##Email Template Init###
email_template = EmailMessage(
subject=email_details['subject'],
from_email="Questr <hello@questr.co>",
to=["Questr <hello@... | 49,864 |
def create_index(files, include_metadata=False, multi_run=False):
"""creates the index from list of files, by crawling over each file"""
ecpps = None
ecpps = run_func_on_files(ElChemPathParser, files, multi_run=multi_run)
ecds = None
if include_metadata:
ecds = run_func_on_files(
... | 49,865 |
def save_partnership_contact_form(request):
""" Saves the requests coming from the Partnership Contact form on the
home page """
if request.method == 'POST':
form = PartnershipRequestForm(request.POST)
if form.is_valid():
form.save()
send_partnership_request_email(req... | 49,866 |
def check_and_format_value(v):
"""
Formats all Pythonic boolean value into XML ones
"""
booleans = {'True': 'true', 'False': 'false'}
clean = strip(v)
if clean in booleans:
return booleans.get(clean)
return clean | 49,867 |
def name_exists(name, id=-1):
"""Check if category name exists in db.
Arguments: name as String, optional id as Integer
Public categories are not allowed to appear more than once. Private
categories can be duplicates.
"""
try:
c = db_session.query(Category).filter(Category.name==name,\
... | 49,868 |
def perimeter_nd(img_np, largest_only=False):
"""Get perimeter of image subtracting eroded image from given image.
Args:
img_np (:obj:`np.ndarray`): Numpy array of arbitrary dimensions.
largest_only (bool): True to retain only the largest connected
component, typically the outer... | 49,869 |
def get_storing_type():
"""Return the storing type of the data file.
One of the following integers:
0 --> ST_ALWAYS_FAST
1 --> ST_ALWAYS_SLOW
2 --> ST_FAST_ON_TRIGGER
3 --> ST_FAST_ON_TRIGGER_SLOW_OTH
A STORING_TYPE dict is provided by this module.
Wraps:
int DWGetStoringType... | 49,870 |
def transactions(api_url : str, network_id : NetworkIdentifier, operator : Optional[Operator] = "and",
max_block : Optional[int] = None, offset : Optional[int] = None, limit : Optional[int] = None,
transaction_id : Optional[TransactionIdentifier] = None, account_id : Optional[AccountId... | 49,871 |
def _normalize_3dinputs(x, y, z):
"""Allow for a variety of different input types, but convert them all to componentwise
numpy arrays that the functions in this module assume."""
# Handle different forms in input arguments
x = np.atleast_2d(x) # Assure a numpy array for componentwise or array versions... | 49,872 |
def hexdiff(x,y):
"""Show differences between 2 binary strings"""
x=any2b(x)[::-1]
y=any2b(y)[::-1]
SUBST=1
INSERT=1
d={}
d[-1,-1] = 0,(-1,-1)
for j in range(len(y)):
d[-1,j] = d[-1,j-1][0]+INSERT, (-1,j-1)
for i in range(len(x)):
d[i,-1] = d[i-1,-1][0]+INSERT, (i-1,-... | 49,873 |
def get_grid_point_from_address(address, D_diag):
"""Return GR grid-point indices of grid addresses.
Parameters
----------
address : array_like
Grid address.
shape=(3, ) or (n, 3), dtype='int_'
D_diag : array_like
This corresponds to mesh numbers. More precisely, this gives
... | 49,874 |
def _generate_interpreted_layer(diagnostic_layer):
"""Generate interpreted layer from diagnostic test band
Parameters
----------
diagnostic_layer: numpy.ndarray
Diagnostic test band
Returns
-------
interpreted_layer : numpy.ndarray
Interpreted la... | 49,875 |
def update_setup(config_filepath):
"""Update default settings with user settings and check they are valid.
Load settings from configuration file at ``config_filepath``, and check that
parameter choices are valid. Non-specified settings are filled in with
defaults.
"""
from textwrap import dede... | 49,876 |
def parse_gml(lines, relabel=True):
"""Parse GML graph from a string or iterable.
Parameters
----------
lines : string or iterable
Data in GML format.
relabel : bool, optional
If True use the GML node label attribute for node names otherwise use
the node id.
Return... | 49,877 |
def get_evaluations(filename):
"""Return a list of all evaluations within an ENDF file.
Parameters
----------
filename : str
Path to ENDF-6 formatted file
Returns
-------
list
A list of :class:`openmc.data.endf.Evaluation` instances.
"""
evaluations = []
with o... | 49,878 |
def svm_ova():
"""Multiclass (One-vs-All) Linear Support Vector Machine."""
return CClassifierMulticlassOVA(CClassifierSVM) | 49,879 |
def save_report(report):
"""Receive a metric report and log in mlflow experiment
Args:
report (dict): Dictionary of calculated metrics
"""
mlflow.log_metric('Accuracy', report['accuracy'])
mlflow.log_metric('Precision - Macro Avg',
report['macro avg']['precision'])
... | 49,880 |
def parse(filename):
""" Dict of Data """
to_return = {}
f = open(filename,'r')
for line in f.readlines():
m = re.match(parse_regex, line)
result = m.groups()
if result[0] == '+':
to_return[result[1]] = True
else:
to_return[result[1]] = False
... | 49,881 |
def __move_dhcpd_file():
"""
to move local dhcpd file
"""
print" "
logger.info("moveDhcpdFile function")
file_path_local = "conf/pxe_cluster/dhcpd.conf"
if os.path.exists(file_path_local):
logger.info(file_path_local + " file exists")
if os.path.exists("/etc/dhcp/dhcpd.conf... | 49,882 |
def test_integer_field_with_non_integer(value: Any) -> None:
"""Test `IntegerField` descriptor with float value."""
DescriptorMock.value = validation.IntegerField(required=True)
with pytest.raises(ValueError) as exc_info:
DescriptorMock(value)
assert "<class 'int'> was expected" in str(exc_info.... | 49,883 |
def get_Theta_wtr_d(region, Theta_ex_prd_Ave_d):
"""日平均給水温度 (℃) (12)
Args:
region(int): 省エネルギー地域区分
Theta_ex_prd_Ave_d(ndarray): 期間平均外気温度 (℃)
Returns:
ndarray: 日平均給水温度 (℃)
"""
# 日平均給水温度を求める際の会期係数
a_wtr, b_wtr = get_table_7()[region - 1]
# 日平均給水温度 (12)
Theta_wtr_d = ... | 49,884 |
def get_FAAM_flights_df():
"""
Retrieve DataFrame of FAAM BAe146 flights
"""
# Flights to use...
DataRoot = get_local_folder('DataRoot')
folder = '/{}/FAAM/core_faam_NetCDFs/'.format(DataRoot)
filename = 'FAAM_BAe146_Biomass_burning_and_ACISIS_flights_tabulated.csv'
df = pd.read_csv(fold... | 49,885 |
def get_facebook_customisations(token, aiid):
"""load customisations for the page"""
return fetch_api(
'/ai/{aiid}/facebook/custom',
token=token,
aiid=aiid,
timeout=config.API_FACEBOOK_TIMEOUT
) | 49,886 |
def get_matrices(training_set_path):
"""Return three Keras HDF5Matrix instances for the input, ground-truth
density map and ground-truth segmentation mask in a compact TrainingSet
"""
if os.path.isfile(training_set_path):
X = HDF5Matrix(training_set_path, 'input/input')
y = HDF5Matrix(t... | 49,887 |
def display_total(message):
"""
Receives the input time period and displays the transaction summary for the corresponding time period.
:param message: telebot.types.Message object representing the message object
:type: object
:return: None
"""
dateFormat = "%m/%d/%Y"
try:
chat_i... | 49,888 |
def plot_profile_base(
x, y, err, label_x, label_y, annotate, categorical, scale_x, scale_y
):
"""Make a scatter plot of eval metric `y` vs training config param `x`"""
f, ax = plt.subplots()
if scale_y is not None:
ax.set_yscale(scale_y)
if scale_x is not None:
ax.set_xscale(scale... | 49,889 |
def train_one_step(
train_batch_i,
bvae_model,
genmo_optimizer,
infnet_optimizer,
prior_optimizer,
grad_variable_dict,
grad_sq_variable_dict):
"""Train Discrete VAE for 1 step."""
metrics = {}
input_batch = process_batch_input(train_batch_i)
(genmo_grads, prior_grads, infnet_grads, ... | 49,890 |
def provide_virtualenv(ve_target, no_site=True, interpreter=None):
"""Provide virtualenv"""
args = ['--distribute']
if no_site:
args.append('--no-site')
if interpreter is not None:
args.append('--python={0}'.format(interpreter))
if not os.path.exists(ve_target):
subprocess.ca... | 49,891 |
def test_update_indicator_occurrences():
"""
Given:
- indicator: Indicator fetched from Bitcoin Abuse service.
- address_to_count_dict: Dict of Bitcoin addresses to count of occurrences.
When:
- Update_indicator_occurrences is being called.
Then:
- Assert that 'address_to... | 49,892 |
def make_stepped_schedule(steps):
"""
Helper to generate a schedule function to perform step-wise changes of a given optimizer hyper-parameter.
:param steps: List of tuples (start_epoch, value);
start_epochs should be increasing, starting at 0. E.g.
momentum_sche... | 49,893 |
def get_head_path(phrase):
"""Yield phrases all the way down to the right-most item (the head).
This method ignores modifications of head modifiers.
For instance, if an adverb modifies an adjective that
modifies a head, that adverb will not fall inside the
path of the head item and will there... | 49,894 |
def sepfirnd(input,filters,axes,output=None,mode='reflect',cval=0.0,origin=0):
"""Apply multiple 1d filters to input using scipy.ndimage.filters.convolve1d
input : array_like
filters : sequence of array_like
Sequence of filters to apply along axes. If length 1, will apply the same filter to all axes... | 49,895 |
def retry(func, maxcnt, interval, msg):
""" retry timeout function """
retry_cnt = 0
rc = False
try:
while not rc:
retry_cnt += 1
rc = func()
flush_str = '.' * retry_cnt
print '\rCheck %s status (timeout: %d secs) %s' % (msg, maxcnt * interval, flu... | 49,896 |
def ProcessOptions():
"""Process and validate command line arguments and options"""
MiscUtil.PrintInfo("Processing options...")
# Validate options...
ValidateOptions()
OptionsInfo["Addhydrogens"] = True if re.match("^Yes$", Options["--addHydrogens"], re.I) else False
OptionsInfo["Inf... | 49,897 |
def daily_treasury(request):
"""
Get daily treasury. Data is from https://fiscaldata.treasury.gov/datasets/daily-treasury-statement/operating-cash-balance
"""
pd.options.display.float_format = '{:.2f}'.format
daily_treasury_stats = pd.read_sql_query("SELECT * FROM daily_treasury", conn)
daily_tr... | 49,898 |
def list_representations():
"""list available server-side objects"""
try:
response = get_bus().list_representations()
return JsonResponse({'type': 'list', 'list': response})
except Exception as exception:
message, status = handle_exception(exception)
return JsonResponse({'mes... | 49,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.