content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def addactual():
"""Add actual spendings"""
if request.method == "POST":
allPayments = []
# Current user that is logged-in saved in variable
userId = session["user_id"]
month = request.form.get("month")
housing = request.form.get("housing")
housing = float(housin... | ccf7d9c362aa1f250959dce51032e43b00ffe412 | 22,900 |
def parse_move(line):
""" Parse steps from a move string """
text = line.split()
if len(text) == 0:
raise ValueError("No steps in move given to parse. %s" % (repr(line)))
steps = []
for step in text:
from_ix = alg_to_index(step[1:3])
if len(step) > 3:
if step[3] ... | 660374a82c19da61df3e0f8468f09c5df7d3be5e | 22,901 |
import os
def get_conf_path(run_id):
"""
Generate path for storing/loading configuration file
:param run_id (str): run ID to be used
:return: full file path for storing/loading config file
"""
return os.path.join('conf', run_id + '.ini') | 6d701be83e52b8294bf45366944543be8b205e9d | 22,902 |
def get_tensor_name(node_name, output_slot):
"""Get tensor name given node name and output slot index.
Args:
node_name: Name of the node that outputs the tensor, as a string.
output_slot: Output slot index of the tensor, as an integer.
Returns:
Name of the tensor, as a string.
"""
return "%s:%d"... | d563a3e4be696fc1109aa7a60fb4dd140ec65431 | 22,903 |
def EstimateMarriageSurvival(resp):
"""Estimates the survival curve.
resp: DataFrame of respondents
returns: pair of HazardFunction, SurvivalFunction
"""
# NOTE: Filling missing values would be better than dropping them.
complete = resp[resp.evrmarry == 1].agemarry.dropna()
ongoing = resp[... | 06f7d307662a70ef4c77073e4202f69ec68ee9e4 | 22,904 |
def get_cowell_data():
"""
Gets Cowell data.
:return: Data and headers.
"""
n = 10000
Y = np.random.normal(0, 1, n)
X = np.random.normal(Y, 1, n)
Z = np.random.normal(X, 1, n)
D = np.vstack([Y, X, Z]).T
return D, ['Y', 'X', 'Z'] | bd2084b889e8e9068d11b0f49c1d00226bfc6a1f | 22,905 |
def is_str_str_tuple(t):
"""Is this object a tuple of two strings?"""
return (isinstance(t, tuple) and len(t) == 2
and isinstance(t[0], basestring)
and isinstance(t[1], basestring)) | e568821ee2d7a3926744b93eaf11356744ca4538 | 22,906 |
def g(dist, aq):
"""
Compute function g (Lemma 5) for a given full parent isntantiation.
Parameters
----------
dists: list ints
Counts of the child variable for a given full parent instantiation.
aq: float
Equivalent sample size divided by the produc... | 505f5c0857f97579bcb1be9e812a90c31ecf4e5e | 22,907 |
import tqdm
import os
def save_2D_animation(embeddings, target_optimizers, emb_space_sizes,
total_train_losses, total_test_losses,
n_bins=100, cmap_name='jet', **plotting_kwargs):
"""Utility function for visualizing the changes in weights over time in
UMAP space. Th... | 8f76501419b6699a07e76dc5679d7ab2e836b9f9 | 22,908 |
def order_tweets_by_polarity(tweets, positive_highest=True):
"""Sort the tweets by polarity, receives positive_highest which determines
the order. Returns a list of ordered tweets."""
reverse = True if positive_highest else False
return sorted(tweets, key=lambda tweet: tweet.polarity, reverse=reverse... | 996c0aa6c374716f10d4d7a890162fe1bb87eef1 | 22,909 |
import hashlib
import re
import sys
import os
def text_file_md5(filename, exclude_lines=None, exclude_re=None,
prepend_lines=None, append_lines=None):
"""Get a MD5 (check) sum of a text file.
Works in the same way as `file_md5()` function but ignores newlines
characters and excludes lin... | aadfab0ae4a76ecace4c1736c0f4b81bc3c83bbb | 22,910 |
from scipy.stats import beta
from params import VoC_start_date, use_vaccine_effect
def read_in_Reff_file(file_date, VoC_flag=None, scenario=''):
"""
Read in Reff h5 file produced by generate_RL_forecast.
Args:
file_date: (date as string) date of data file
VoC_date: (date as string) date f... | 219118c333f14ba9f7a44416bd30e38c66b3d5d9 | 22,911 |
import sys
import pprint
def main(argv):
"""Main Compute Demo
When invoked from the command line, it will connect using secrets.py
(see secrets.py-dist for instructions and examples), and perform the
following tasks:
- List current nodes
- List available images (up to 10)
- List availabl... | 7d68d447591d9ca53db2a9bdc1108725f92c764a | 22,912 |
def string_with_fixed_length(s="", l=30):
"""
Return a string with the contents of s plus white spaces until length l.
:param s: input string
:param l: total length of the string (will crop original string if longer than l)
:return:
"""
s_out = ""
for i in range(0, l):
if i < len... | 2230a2893913eadb2c42a03c85728a5fe79e1e0f | 22,913 |
def fetch_ref_proteomes():
"""
This method returns a list of all reference proteome accessions available
from Uniprot
"""
ref_prot_list = []
response = urllib2.urlopen(REF_PROT_LIST_URL)
for ref_prot in response:
ref_prot_list.append(ref_prot.strip())
return ref_prot_list | f42c879f78a0e7281df369b40145c5d60aedb32b | 22,914 |
from typing import BinaryIO
def load(fp: BinaryIO, *, fmt=None, **kwargs) -> TextPlistTypes:
"""Read a .plist file (forwarding all arguments)."""
if fmt is None:
header = fp.read(32)
fp.seek(0)
if FMT_TEXT_HANDLER["detect"](header):
fmt = PF.FMT_TEXT
if fmt == PF.FMT_T... | d8445e388b33f69555c1270cebecfd552a34196a | 22,915 |
def _swig_add_metaclass(metaclass):
"""Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
def wrapper(cls):
return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
return wrapper | d1e4f766827c13fa312ce3485daf43be2fc0eda1 | 22,916 |
from typing import Set
def create_affected_entities_description(security_data: SecurityData, limit: int = 5) -> str:
"""Create a description of the entities which are affected by a security problem.
:param security_data: the security details for which to create the description
:param limit: the maximum nu... | 95adc5a6a1fe88e0ec80273deee95e39ee196a55 | 22,917 |
def amac_person_org_list_ext():
"""
中国证券投资基金业协会-信息公示-从业人员信息-基金从业人员资格注册外部公示信息
http://gs.amac.org.cn/amac-infodisc/res/pof/extperson/extPersonOrgList.html
:return:
:rtype: pandas.DataFrame
"""
data = get_data(url=amac_person_org_list_ext_url, payload=amac_person_org_list_ext_payload)
need_... | f84d40a79ae49ebdf5a8ecb6612b37515f5ea676 | 22,918 |
from dimarray import DimArray, Dataset
def concatenate(arrays, axis=0, _no_check=False, align=False, **kwargs):
""" concatenate several DimArrays
Parameters
-----------
arrays : list of DimArrays
arrays to concatenate
axis : int or str
axis along which to concatenate (must exist)... | 3204fb32fb2ea3192b469cd37c76f7018f3a8190 | 22,919 |
def ele_types(eles):
"""
Returns a list of unique types in eles
"""
return list(set([e['type'] for e in eles] )) | e87ea4c6256c2520f9f714dd065a9e8642f77555 | 22,920 |
def colorful_subgraph(G, colors, k, s, subgraph_type, get_detail=True, verbose=False):
"""Detect if colorful path exists fom s to any node by dynamic programming.
Args:
G (nx.Graph): with n nodes and m edges
colors (list): list of integers represents node colors
k (int): number of colors... | 644a1091bbee9bf79f236a8f815ae4c07fb1f538 | 22,921 |
import itertools
def find_all_combos(
conformer,
delta=float(120),
cistrans=True,
chiral_centers=True):
"""
A function to find all possible conformer combinations for a given conformer
Params:
- conformer (`Conformer`) an AutoTST `Conformer` object of interest
- de... | 1b5c5f44de23524a9392f51e76f46ef0f234648c | 22,922 |
import pyximport
from hmc2c import hmc_main_loop as c_hmc_main_loop
def hmc2(f, x, options, gradf, *args, **kargs):
"""
SAMPLES = HMC2(F, X, OPTIONS, GRADF)
Description
SAMPLES = HMC2(F, X, OPTIONS, GRADF) uses a hybrid Monte Carlo
algorithm to sample from the distribution P ~ EXP(-F), where... | 3e885f1bc0ec5a6d4c40d5fd7cc3db6ce37c8dd0 | 22,923 |
def generate_abbreviations(
labels: tp.Iterable[str],
max_abbreviation_len: int = 3,
dictionary: tp.Union[tp.Tuple[str], str] = "cdfghjklmnpqrstvxz"):
"""
Returns unique abbreviations for the given labels. Generates the abbreviations with
:func:`beatsearch.utils.generate_unique_abbre... | a22e68990147bd973c4a7af8e9e1a8f28fa7b4ac | 22,924 |
def best_hand(hand):
"""Из "руки" в 7 карт возвращает лучшую "руку" в 5 карт """
i = iter(combinations(hand, 5))
best_rank = 0, 0, 0
best_combination = None
for combination in i:
current_rank = hand_rank(combination)
if compare(current_rank, best_rank):
best_rank = curren... | c885625c2b5f60453b6dca59e25003b9f977e9d4 | 22,925 |
def calculate_label_counts(examples):
"""Assumes that the examples each have ONE label, and not a distribution over labels"""
label_counts = {}
for example in examples:
label = example.label
label_counts[label] = label_counts.get(label, 0) + 1
return label_counts | 4c45378c6e29ce3d1b40b4d02a112e1fbd23d8b6 | 22,926 |
def printer(arg1):
"""
Even though 'times' is destroyed when printer() has been called,
the 'inner' function created remembers what times is. Same goes
for the argument arg1.
"""
times = 3
def inner():
for i in range(times): print(arg1)
return inner | 7e3d2033602eaef9ef570c97a058208066073427 | 22,927 |
from bs4 import BeautifulSoup
def from_get_proxy():
"""
From "http://www.getproxy.jp"
:return:
"""
base = 'http://www.getproxy.jp/proxyapi?' \
'ApiKey=659eb61dd7a5fc509bef01f2e8b15669dfdb0f54' \
'&area={:s}&sort=requesttime&orderby=asc&page={:d}'
urls = [base.format('CN'... | b3302b0092eb973022e2d322cc00e1391fe68c8b | 22,928 |
def KORL(a, kappa=None):
""" log rounds k-ary OR """
k = len(a)
if k == 1:
return a[0]
else:
t1 = KORL(a[:k//2], kappa)
t2 = KORL(a[k//2:], kappa)
return t1 + t2 - t1.bit_and(t2) | 2c85f7131dcfe0b35d3bfd8b04b876fad320572f | 22,929 |
import json
import requests
def verify(token):
"""Verifies a JWS token, returning the parsed token if the token has a
valid signature by the key provided by the key of the OpenID
Connect server stated in the ISS claim of the token. If the
signature does not match that key, None is returned.
"""
... | 8d1dac4d1c87de3d2d619f58bdf077f82b54dfda | 22,930 |
def get_listing_panel(tool, ghidra):
""" Get the code listing UI element, so we can get up-to-date location/highlight/selection """
cvs = tool.getService(ghidra.app.services.CodeViewerService)
return cvs.getListingPanel() | f14477cf13cb7eb4e7ede82b0c2068ca53a30723 | 22,931 |
def template_data(environment, template_name="report_html.tpl", **kwds):
"""Build an arbitrary templated page.
"""
template = env.get_template(template_name)
return template.render(**environment) | 6b3c1ea5c280931280b5d6c69f380b9349ac0627 | 22,932 |
def resnet152_ibn_a(**kwargs):
"""
Constructs a ResNet-152-IBN-a model.
"""
model = ResNet_IBN(block=Bottleneck_IBN,
layers=[3, 8, 36, 3],
ibn_cfg=('a', 'a', 'a', None),
**kwargs)
return model | 5cb059910c5442b0df7c08471f75b96fe3fb4c80 | 22,933 |
import scipy
def calibratePose(pts3,pts2,cam,params_init):
"""
Calibrates the camera to match the view calibrated by updating R,t so that pts3 projects
as close as possible to pts2
:param pts3: Coordinates of N points stored in a array of shape (3,N)
:param pts2: Coordinates of N points stored in ... | 5f1fcf55ec934596fd46f129d12e8457173239eb | 22,934 |
import base64
def image_to_base64(file_image):
"""
ESSA FUNÇÃO TEM COMO OBJETIVO, CONVERTER FORMATO DE INPUT (PNG) -> BASE64
O ARQUIVO OBTIDO (PNG) É SALVO NA MÁQUINA QUE ESTÁ EXECUTANDO O MODELO.
# Arguments
file_image - Required : Caminho do arquivo
... | 74e9c46ce48e23fdb5453cb9ce5223dfb8e6004b | 22,935 |
from pathlib import Path
from typing import Set
def get_files_recurse(path: Path) -> Set:
"""Get all files recursively from given :param:`path`."""
res = set()
for p in path.rglob("*"):
if p.is_dir():
continue
res.add(p)
return res | c129ce43130da09962264f6e7935410685815943 | 22,936 |
from typing import List
def img_after_ops(img: List[str], ops: List[int]) -> List[str]:
"""Apply rotation and flip *ops* to image *img* returning the result"""
new_img = img[:]
for op in ops:
if op == Tile.ROTATE:
new_img = [cat(l)[::-1] for l in zip(*new_img)]
elif op == Tile.... | a28f1dbdf7f756c9b8b313d889596797466ab729 | 22,937 |
import functools
import urllib
def authenticated(method):
"""Decorate methods with this to require that the user be logged in.
Fix the redirect url with full_url.
Tornado use uri by default.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
user = self.current... | c4dc18af60b9270d644ed807ea1c74b821ea7bca | 22,938 |
import math
def ring_samp_ranges(zma, rng_atoms):
""" Set sampling range for ring dihedrals.
:param zma: Z-Matrix
:type zma: automol.zmat object
:param rng_atoms: idxs for atoms inside rings
:type rng_atoms: list
"""
samp_range_dct = {}
ring_value_dct = ring_dihedrals... | 6e1958f66f596d9b1230864e3b9a2b73cd01cb35 | 22,939 |
def users_key(group='default'):
""" Returns the user key """
return db.Key.from_path('users', group) | 1912165ff75c39c9fbcb1432f46ef80f9b08c096 | 22,940 |
def VolumetricFlow(self):
"""Volumetric flow (m^3/hr)."""
stream, mol = self.data
m = mol[0]
if m:
c = self.name # c = compound
c.T = stream.T
c.P = stream.P
c.phase = stream._phase
return c.Vm * m * 1000
else:
return 0. | c799c27079494561e30975a6e03b5c1cefe9a907 | 22,941 |
def build_queue_adapter(workflow_client, logger=None, **kwargs):
"""Constructs a queue manager based off the incoming queue socket type.
Parameters
----------
workflow_client : object ("distributed.Client", "fireworks.LaunchPad")
A object wrapper for different distributed workflow types
log... | bbd013fef1095dd4881a8b51561ed4080682141e | 22,942 |
import torch
def pad_sents(sents, pad_token, return_tensor = False):
""" Pad list of sentences according to the longest sentence in the batch.
The paddings should be at the end of each sentence.
@param sents (list[list[str]]): list of sentences, where each sentence
... | 3100ef6f1924685f7a46b22753830cdf203e565d | 22,943 |
def _take_along_axis(array, indices,
axis):
"""Takes values from the input array by matching 1D index and data slices.
This function serves the same purpose as jax.numpy.take_along_axis, except
that it uses one-hot matrix multiplications under the hood on TPUs:
(1) On TPUs, we use one-hot ... | 9a926a53341e0fc964fc568474ca29db286ed14e | 22,944 |
import requests
import logging
def send_envelope(
adfs_host: str,
envelope: str,
) -> requests.Response:
"""Send an envelope to the target ADFS server.
Arguments:
adfs_host: target ADFS server
envelope: envelope to send
Returns:
ADFS server response
"""
url = f"ht... | bc59fa99fa28432dd969f1a72bbae00af716b443 | 22,945 |
def display_main(choice):
"""
Link option To main board
"""
return main(choice) | 66b0b0d36d47b4107b5b57dce9ea94787f3fa83b | 22,946 |
import random
def generate_network_table(seed=None):
"""
Generates a table associating MAC and IP addressed to be distributed by our virtual network adapter via DHCP.
"""
# we use the seed in case we want to generate the same table twice
if seed is not None:
random.seed(seed)
# numbe... | d39915c129b2d5a99fc41c90b718fcca17d20cd5 | 22,947 |
import torch
def loss_mGLAD(theta, S):
"""The objective function of the graphical lasso which is
the loss function for the meta learning of glad
loss-meta = 1/B(-log|theta| + <S, theta>)
Args:
theta (tensor 3D): precision matrix BxDxD
S (tensor 3D): covariance matrix BxDxD (dim=D)
... | b056a5c57e681cca40c6a7a0d030dee25049e6de | 22,948 |
def parse_remote_path(remote_path):
""" Wrapper around the utils function - checks for the right protocol """
protocol, bucket, key = utils.parse_remote_path(remote_path)
assert protocol == "s3:", "Mismatched protocol (expected AWS S3)"
return bucket, key | 65c26139d0e28f64ae966a75bf730d1a6b8b2248 | 22,949 |
from typing import Callable
def operations(func: Callable) -> Callable:
"""Allows developers to specify operations which
should not be called in the fuzzing process.
Examples:
Ignoring operations specified by operation ids in lists
>>> @fuzz_lightyear.exclude.operations
..... | ce6d9596ff307f15c86d4823d3ebcfdafa5f4e33 | 22,950 |
def _gen_dfa_table(t: UxsdComplex) -> str:
"""Generate a 2D C++ array representing DFA table from an UxsdComplex's DFA.
The array is indexed by the state and input token value, such that table[state][input]
gives the next state.
"""
assert isinstance(t.content, UxsdDfa)
dfa = t.content.dfa
out = ""
out += "con... | f0bae5dd8f897786a62016b7b807e2c7730f1e89 | 22,951 |
def get_heat_capacity_derivative(Cv, temperature_list, plotfile='dCv_dT.pdf'):
"""
Fit a heat capacity vs T dataset to cubic spline, and compute derivatives
:param Cv: heat capacity data series
:type Cv: Quantity or numpy 1D array
:param temperature_list: List of temperatures used in repli... | 49f27209c9f6387fc25936481d5d35cebdc6523f | 22,952 |
def get_gradients_of_activations(model, x, y, layer_names=None, output_format='simple', nested=False):
"""
Get gradients of the outputs of the activation functions, regarding the loss.
Intuitively, it shows how your activation maps change over a tiny modification of the loss.
:param model: keras compile... | 5cb9234594b867383f92f4e2e7e91e39eb79d120 | 22,953 |
def string_to_screens_and_lines(source, allowed_width, allowed_height, f, pixels_between_lines = None, end_screens_with = (), do_not_include = ()):
"""
Convert a string to screens and lines.
Pygame does not allow line breaks ("\n") when rendering text. The purpose
of this function is to break a str... | f43907fdf47b342b1eac3100c07e9d452b0d865f | 22,954 |
def trim_spectrum(self, scouse, flux):
"""
Trims a spectrum according to the user inputs
"""
return flux[scouse.trimids] | 3f18259986e677f8e8a9718408cdb56352d956e5 | 22,955 |
def test_bitwise_and(a, b):
"""
>>> test_bitwise_and(0b01, 0b10)
0L
>>> test_bitwise_and(0b01, 0b11)
1L
>>> test_bitwise_and(0b01, 2.0)
Traceback (most recent call last):
...
NumbaError: 27:15: Expected an int, or object, or bool
>>> test_bitwise_and(2.0, 0b01)
Tracebac... | 0855921300751368eb0ad3f3cba37b6ddac759fd | 22,956 |
import inspect
def flagFunction(method, name=None):
"""
Determine whether a function is an optional handler for a I{flag} or an
I{option}.
A I{flag} handler takes no additional arguments. It is used to handle
command-line arguments like I{--nodaemon}.
An I{option} handler takes one argument... | 265f92ca52ec4b3c1b6b3955a7ac719f64099bad | 22,957 |
from pathlib import Path
def envnotfound(env):
"""`'Env "my-venv" not found. Did you mean "./my-venv"?'`"""
msg = f'Env "{env}" not found.'
if arg_is_name(env) and Path(env).exists():
msg += f'\nDid you mean "./{env}"?'
return msg | e2437bbf141a841650f33ede5d7fb6489a954f00 | 22,958 |
def random_translation_along_x(gt_boxes, points, offset_range):
"""
Args:
gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]]
points: (M, 3 + C),
offset_range: [min max]]
Returns:
"""
offset = np.random.uniform(offset_range[0], offset_range[1])
points[:, 0] += o... | 6998e463313faeaaf75e96b0374c0bdc5415c8f1 | 22,959 |
import numpy
import scipy
def predband(xd,yd,a,b,conf=0.95,x=None):
"""
Calculates the prediction band of the linear regression model at the desired confidence
level, using analytical methods.
Clarification of the difference between confidence and prediction bands:
"The 2sigma confidence interval is 95% sure to co... | a235548f4593cfc105bba9d7268dba2e14374df7 | 22,960 |
def orient_edges(G):
"""Orient remaining edges after colliders have been oriented.
:param G: partially oriented graph (colliders oriented)
:returns: maximally oriented DAG
"""
undir_list = [edge for edge in G.edges() if G.is_undir_edge(edge)]
undir_len = len(undir_list)
idx = 0
whi... | 958c22b7c7906219bfc52d2cc59945a22e4e1060 | 22,961 |
def _create_deserialize_fn(attributes: dict, globals: dict, bases: tuple[type]) -> str:
"""
Create a deserialize function for binary struct from a buffer
The function will first deserialize parent classes, then the class attributes
"""
lines = []
# For this class bases
for parent in bases:... | e5058b73d47a034323a4ebe65edbf888bdf98321 | 22,962 |
def blck_repeat(preprocessor: Preprocessor, args: str, contents: str) -> str:
"""The repeat block.
usage: repeat <number>
renders its contents one and copies them number times"""
args = args.strip()
if not args.isnumeric():
preprocessor.send_error("invalid-argument", "invalid argument. Usage: repeat [uint > 0]"... | 8dfedd854a68b2fcc33ea4b9714744302fe5934d | 22,963 |
import math
def is_prime(n: int) -> bool:
"""Determines if the natural number n is prime."""
# simple test for small n: 2 and 3 are prime, but 1 is not
if n <= 3:
return n > 1
# check if multiple of 2 or 3
if n % 2 == 0 or n % 3 == 0:
return False
# search for subsequent pri... | e7bd02271681906f9ee4e63305c5a6f630578171 | 22,964 |
import constants as c
import cPickle
def get_word_prob():
"""Returns the probabilities of all the words in the mechanical turk video labels.
"""
data = cPickle.load(open(c.datafile)) # Read in the words from the labels
wordcount = dict()
totalcount = 0
for label in data:
for word in la... | c9f137ad4e844ff3cea3c6f9b1d64e9422359b79 | 22,965 |
def angDistance(ra, dec, df, raCol='fieldRA', decCol='fieldDec'):
"""
"""
df['dist'] = angSep(ra, dec, df[raCol], df[decCol])
idx = df.dist.idxmin()
rval = df.loc[idx]
df.drop('dist', axis=1, inplace=True)
return rval | 9e88711ff33a7ac1a223608ea5441e1cfdbb7a01 | 22,966 |
def offer_in_influencing_offers(offerId, influencing_offers):
"""
Find if a passed offerId is in the influencing_offers list
Parameters
----------
offerId: Offer Id from portfolio dataframe.
influencing_offers : List of offers found for a customer
Returns
-------
1 if of... | 81c4a8bcb7432222a1fc5175449192681002539c | 22,967 |
from vortex.test import TestTuple
from vortex.test import VortexJSTupleLoaderTestHandler
def setupVortexServer(portNum=8345, wsPortNum=8344):
""" Setup Site
Sets up the web site to listen for connections and serve the site.
Supports customisation of resources based on user details
@return: Port objec... | 1cfa947cea049afeee6132b57cd0e918664e03ef | 22,968 |
def identity_block(filters, stage, block):
"""The identity block is the block that has no conv layer at shortcut.
# Arguments
filters: integer, used for first and second conv layers, third conv layer double this value
stage: integer, current stage label, used for generating layer names
b... | 43eb5d56a83d24db9bd60aabf1e7dbd601a093cb | 22,969 |
import psutil
def filebeat_service_running():
"""
Checks if the filebeat service is currently running on the OS.
:return: True if filebeat service detected and running, False otherwise.
"""
result = False
try:
filebeat_service = psutil.win_service_get('filebeat')
filebeat_servi... | 51f9bc865b4f7d2de760fcc6952755b5c7c9106a | 22,970 |
def unhandled_request_message(request, cassette):
"""Generate exception for unhandled requests."""
return UNHANDLED_REQUEST_EXCEPTION.format(
url=request.url, cassette_file_path=cassette.cassette_name,
cassette_record_mode=cassette.record_mode,
cassette_match_options=cassette.match_optio... | dcbfec51a88d3ad62395f48c7c046400177c07fd | 22,971 |
from django.contrib.auth import logout as auth_logout
def logout(request):
"""
Logs out the user and displays 'You are logged out' message.
"""
if request.method == 'GET':
return _new_api_403()
auth_logout(request) | 7e975fdd68295e893d8f14321f722e941833b872 | 22,972 |
def compara_dv(cpf, primeiro_dv, segundo_dv):
"""Valida se dígitos verificadores calculados são iguais aos inseridos."""
return "válido" if primeiro_dv == int(cpf[9]) and segundo_dv == int(cpf[10]) else "inválido" | 4b1794f466ce8c00e91c8c5f281996ea262591f8 | 22,973 |
def write_file(file_name, data, line_length):
""" Writes the results to a text file using a name based on file_name
input: string, list
returns: int
"""
pos = file_name.rfind('.')
fn_o = file_name[:pos] + '.OUT' + file_name[pos:]
f = open(fn_o, "w")
for fsn, sequence in data:
... | 0ad1b25106a6c9120289e8d55caafbebf475f9d5 | 22,974 |
def handle_duplicates(df, cutoff=5, agg_source_col='multiple'):
"""Aggregates duplicate measurements in a DataFrame.
Parameters
----------
df : pandas DataFrame
DataFrame with required columns: 'smiles', 'solvent', 'peakwavs_max'
cutoff : int
Wavelength cutoff in nm. Duplicate meas... | 0f37ba0256d3a73ebc86d628b65d054c049a7456 | 22,975 |
def splitData(features, target, trainFraction=0.25):
"""
Split the data into test and train data
Inputs:
> features: the model feature data (DataFrame)
> target: the target data (Series)
> trainFraction (0.25 by default): fraction of events to use for training
Outputs:
... | b3dba6e5b1082062995c4272c7e42fe24c7c8712 | 22,976 |
def poisson_moment( k, n):
"""
returns the moment of x**n with expectation value k
CURRENTLY A SET OF HARD CODED EXPRESSIONS! VERY FRAGILE!
--> would be *much* better if we could do this algorithmically
"""
if n==0:
return 1
elif n==1:
return k
elif n==2:
ret... | d2af07d550b0cf6ac9a410296b4ec12c78cc1505 | 22,977 |
def drug_encoder(input_smiles):
"""
Drug Encoder
Args:
input_smiles: input drug sequence.
Returns:
v_d: padded drug sequence.
temp_mask_d: masked drug sequence.
"""
temp_d = drug_bpe.process_line(input_smiles).split()
try:
idx_d = np.asarray([drug_idx[i] for... | 79f0e391e5cd72f981b9580d105ac41cc53d5f63 | 22,978 |
import os
def load_mapping_files():
"""Load local and remote mapping files."""
mappings = {}
local = ["properties", "countries", "professions",
"latin_countries", "latin_languages"]
remote = ["selibr"]
for title in local:
f = os.path.join(MAPPINGS, '{}.json'.format(title))
... | 443938c33c725723d6ce047630706171c11c2cbe | 22,979 |
def optimise_acqu_func_mledr(acqu_func, bounds, X_ob, func_gradient=True, gridSize=10000, n_start=5):
"""
Optimise acquisition function built on GP- model with learning dr
:param acqu_func: acquisition function
:param bounds: input space bounds
:param X_ob: observed input data
:param func_gradi... | 8a59f9f3c4b7b55a4ae56da93eed1c9820363ef6 | 22,980 |
def get_path_from_pc_name(pc_name):
"""Find out path of a template
Parameters
----------
pc_name : string
Name of template.
Returns
-------
tplPath : string
Path of template
"""
tplPath = pc_name + '.json'
# change path to template if in subdir
for i in p... | f2ee20f9f8728d672bb0658e80f9f04f2c9f0c11 | 22,981 |
def eq(*, alpha=None, omega):
"""Define dyadic comparison function equal to.
Dyadic case:
3 = 2 3 4
0 1 0
"""
return int(alpha == omega) | 1f8d826711e9d24a3b05de5f42a99b36744f4f38 | 22,982 |
import calendar
def generate_days(year):
"""Generates all tuples (YYYY, MM, DD) of days in a year
"""
cal = calendar.Calendar()
days = []
for m in range(1,13):
days.extend(list(cal.itermonthdays3(year, m)))
days = [d for d in set(days) if d[0] == year]
days.sort()
return days | 6d87910572957d21c9d5df668dfb5f2d02627817 | 22,983 |
import requests
import json
def nounClassifier(word):
"""Classifies noun as actor o object
Parameters
----------
word : str
Lematized noun to be classified (case-insensitive).
"""
word = word.lower()
response_raw = requests.get(
f"{API_URL}senses/search?lemma={word}&&&par... | aef33226b956a0d7b9fcb8b1b751d5a11e9136c4 | 22,984 |
def svn_repos_post_lock_hook(*args):
"""svn_repos_post_lock_hook(svn_repos_t repos, apr_pool_t pool) -> char"""
return _repos.svn_repos_post_lock_hook(*args) | 56bdafc41fa76d2a4d2f5e6b213fa86e8ca9416b | 22,985 |
def libdmtx_function(fname, restype, *args):
"""Returns a foreign function exported by `libdmtx`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequence of `ctype... | ed5f39d435aae453a0aeb8855fc0a21e1db334b8 | 22,986 |
from typing import Any
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
control_unit: ControlUnit = hass.data[DOMAIN][config_entry.entry_id]
diag: dict[str, Any] = {
"config": async_re... | ac4495e49745f9211a32cfaf3a15c03203282e50 | 22,987 |
async def instance_set_name_inurl(cluster_id: str, vm_uuid: str, new_name: str):
""" Set Instance (VM/Template) Name """
try:
try:
session = create_session(
_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()
)
except KeyError as key_error:
... | 3c942af4a57dad0beaef6f629d4b7900421eadbd | 22,988 |
def key_released(key):
"""
Takes a key, that's either a keycode or a character,
and says if it was released this frame.
"""
keycode = _to_keycode(key)
return (keycode not in current_frame_held_buttons) and \
(keycode in last_frame_held_buttons) | 4cb66ba924aae909f20db59eb2aef0ccc77d2860 | 22,989 |
def trim_snakes_old(lcs,ref,Nb,Ne,dat,Mb,Me):
"""Previously found matches can cause problems if they are not optimal.
In such a case sticking with the matches as found prevents subsequent
more advanced diff routines from recovering from an early sub-optimal
choice. To counter this all snakes and pseudo... | 0bf078ca2198bcf0c25e8a925bd0c096cafa4797 | 22,990 |
import asyncio
async def start(actual_coroutine):
"""
Start the testing coroutine and wait 1 second for it to complete.
:raises asyncio.CancelledError when the coroutine fails to finish its work
in 1 second.
:returns: the return value of the actual_coroutine.
:rtype: Any
"""
try:
... | 26e3737091ca798dbf8c0f6f2a18a1de4b0ec42b | 22,991 |
def get_node(path):
"""Returns a :class:`Node` instance at ``path`` (relative to the current site) or ``None``."""
try:
current_site = Site.objects.get_current()
except Site.DoesNotExist:
current_site = None
trailing_slash = False
if path[-1] == '/':
trailing_slash = True
try:
node, subpath = Node.obj... | 516460d05df4139ce5354f2c3ef5cf948d4b8213 | 22,992 |
from datetime import datetime
def new_post(blog_id, username, password, post, publish):
"""
metaWeblog.newPost(blog_id, username, password, post, publish)
=> post_id
"""
user = authenticate(username, password, 'zinnia.add_entry')
if post.get('dateCreated'):
creation_date = datetime.str... | 4bdd8464458bef5797854776222a178e891d6346 | 22,993 |
def upload(userid, filedata):
"""
Creates a preview-size copy of an uploaded image file for a new avatar
selection file.
"""
if filedata:
media_item = media.make_resized_media_item(filedata, (600, 500), 'FileType')
orm.UserMediaLink.make_or_replace_link(userid, 'avatar-source', media... | 3ffd3d5a26c35f20e5a3885ca597d8c0182ebc8a | 22,994 |
import os
def get_account_2_json(usr, pwd):
"""
将从环境变量获取的账号密码拼接成json
:return: 字典
"""
username = os.popen("env | grep {}".format(usr))
password = os.popen("env | grep {}".format(pwd))
username_list = username.read().split()
password_list = password.read().split()
username_dict = str... | 9eabc688a5da441cb6701eb62b93133ce9f73c56 | 22,995 |
def time_dconv_bn_nolinear(nb_filter, nb_row, nb_col,
stride=(2, 2), activation="relu"):
"""
Create time convolutional Batch Norm layer in decoders.
Parameters:
---------
filter_num : int
number of filters to use in convolution layer.
row_num : int
number of r... | 016082d3c09388a4ff9f8add5cb84a63a65775e8 | 22,996 |
import random
def ___generate_random_row_major_GM___(i, j, s=None):
"""Make a random row major sparse matrix of shape (i,j) at sparsity=s.
:param i:
:param j:
:param s:
:return:
"""
if s is None:
s = random.uniform(0, 0.1)
if s < 0.02: s = 0
if rAnk == mAster_rank:
... | 59eca064d240dc03fdbdc8d1807dbbbb996239d4 | 22,997 |
from typing import Tuple
from typing import Any
def parse_tuple(value: Tuple[Any, ...]) -> RGBA:
"""
Parse a tuple or list as a color.
"""
if len(value) == 3:
r, g, b = [parse_color_value(v) for v in value]
return RGBA(r, g, b, None)
elif len(value) == 4:
r, g, b = [parse_c... | 0766bd7189c5e0cd383d94944dacecd5fbef1320 | 22,998 |
import pathlib
from typing import Optional
def find_path(
start_path: pathlib.Path = pathlib.Path("."),
) -> Optional[pathlib.Path]:
"""Traverse the file system looking for the config file .craftier.ini.
It will stop earlier at the user's home directory, if it encounters a Git or
Mercurial directory,... | 00fbfabc8e0c6dd3c23b190e6278f70af566b25f | 22,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.