content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def df_to_bytes(df: pd.DataFrame) -> bytes:
"""Write dataframe to bytes.
Use pyarrow parquet if available, otherwise csv.
"""
if pyarrow is None:
return df_to_bytes_csv(df)
return df_to_bytes_parquet(df) | 5,318,200 |
def select_training_voxels(input_masks, threshold=0.1, datatype=np.float32, t1=0):
"""
Select voxels for training based on a intensity threshold
Inputs:
- input_masks: list containing all subject image paths for a single modality
- threshold: minimum threshold to apply (after normalizing im... | 5,318,201 |
def find_intersections(formula_lists,group_labels,exclusive = True):
"""
Docstring for function pyKrev.find_intersections
====================
This function compares n lists of molecular formula and outputs a dictionary containing the intersections between each list.
Use
----
find_intersections([... | 5,318,202 |
def wcs_align(hdu_in, header, outname=None, clobber=False):
"""
This function is used to align one FITS image to a specified header. It takes the following arguments:
:param hdu_in: the HDU to reproject (must have header and data)
:param header: the target header to project to
:param outname: the f... | 5,318,203 |
def save_pumping_test(pump_test, path="", name=None):
"""Save a pumping test to file.
This writes the variable to a csv file.
Parameters
----------
path : :class:`str`, optional
Path where the variable should be saved. Default: ``""``
name : :class:`str`, optional
Name of the f... | 5,318,204 |
def test_comparisons():
"""
Check that comparison operators work for Tensors
"""
t1 = rev.Tensor(2)
t2 = rev.Tensor(2)
t3 = rev.Tensor(1)
t4 = rev.Tensor(3)
# test against another Tensor
assert t1 == t2
assert t1 <= t2
assert t1 >= t2
assert t3 < t1
assert t3 <= t1
... | 5,318,205 |
def merge_flag_dictionaries(a: Dict[str, str], b: Dict[str, str]) -> Dict[str, str]:
"""
>>> a = {'CFLAGS': '-1'}
>>> b = {'CFLAGS': ' -2'}
>>> merge_flag_dictionaries(a, b)
{'CFLAGS': '-1 -2'}
"""
a_copy = deepcopy(a)
b_copy = deepcopy(b)
merged_entries = {}
f... | 5,318,206 |
def _delete_magic(line):
"""Returns an empty line if it starts with the # [magic] prefix
"""
return '' if line.startswith(_PREFIX) else line | 5,318,207 |
def opened(f_or_fn, mode):
"""
Yields an opened file or file-like object.
Args:
file_or_filename: Either an already opened file or file-like
object, or a filename to open.
mode: The mode to open the file in.
"""
if isinstance(f_or_fn, basestring):
with open(f_or_fn,... | 5,318,208 |
async def test_cancel_during_receive() -> None:
"""
Test that cancelling a pending receive() operation does not cause an item in the stream to be
lost.
"""
receiver_scope = None
async def scoped_receiver() -> None:
nonlocal receiver_scope
with CancelScope() as receiver_scope:
... | 5,318,209 |
def init_db_conn(connect_string, username, passwd, show_connection_info, show_version_info=True):
"""initializes db connections, can work with PyGres or psycopg2"""
global _CONN
try:
dbinfo = connect_string
if show_connection_info:
print(dbinfo)
if USE_JYTHON:
_CONN = zxJDBC.connect(connect_string, usern... | 5,318,210 |
def getDriversForConnectedUsbDevices():
"""Get any matching drivers for connected USB devices.
@return: Pairs of drivers and device information.
@rtype: generator of (str, L{DeviceMatch}) tuples
"""
usbDevs = itertools.chain(
(DeviceMatch(KEY_CUSTOM, port["usbID"], port["devicePath"], port)
for port in... | 5,318,211 |
def persist_data(message, session, prepared_insert_stmt):
"""Summary
process raw message from kafka and store data into cassandra
Args:
message (JSON): JSON string that contains the raw data
session (Session): the session object that is connected to current cassandra cluster
"""
... | 5,318,212 |
def untokenize(words):
"""
Source: https://github.com/commonsense/metanl/blob/master/metanl/token_utils.py
Untokenizing a text undoes the tokenizing operation, restoring
punctuation and spaces to the places that people expect them to be.
Ideally, `untokenize(tokenize(text))` should be identical to `... | 5,318,213 |
def create_new_course(request_ctx, account_id, course_name=None, course_course_code=None, course_start_at=None, course_end_at=None, course_license=None, course_is_public=None, course_is_public_to_auth_users=None, course_public_syllabus=None, course_public_description=None, course_allow_student_wiki_edits=None, course_a... | 5,318,214 |
def addReference(inData, reference):
"""
"""
from copy import deepcopy
data = deepcopy(inData)
existing_refs = [x for x in data['relatedIdentifiers'] if x['relationType']=='References']
ref_list = [ x['relatedIdentifier'] for x in existing_refs]
if ( reference not in ref_list):
pr... | 5,318,215 |
def len_path_in_limit(p, n=128):
"""if path len in limit, return True"""
return len(p) < n | 5,318,216 |
def threshold(tensor, density):
"""
Computes a magnitude-based threshold for given tensor.
:param tensor: PyTorch tensor
:type tensor: `torch.Tensor`
:param density: Desired ratio of nonzeros to total elements
:type density: `float`
:return: Magnitude threshold
:rtype: `float`
"""
... | 5,318,217 |
def test_rating(response_fx, client_fx):
"""GET /songs/rating/<id>
POST /songs/rating/<id>
Test good rating values.
"""
response = response_fx('/songs')
song = response["data"][0]
assert song["rating"] == 5
rating = response_fx(song["rating_url"])
assert rating["rating"] == 5
... | 5,318,218 |
def _nt_quote_args(args):
"""Quote command-line arguments for DOS/Windows conventions.
Just wraps every argument which contains blanks in double quotes, and
returns a new argument list.
"""
# XXX this doesn't seem very robust to me -- but if the Windows guys
# say it'll work, I guess I'l... | 5,318,219 |
def algorithm_free_one_only_over_isls(
output_dynamic_state_dir,
time_since_epoch_ns,
satellites,
ground_stations,
sat_net_graph_only_satellites_with_isls,
ground_station_satellites_in_range,
num_isls_per_sat,
sat_neighbor_to_if,
list_gsl_interface... | 5,318,220 |
def button_click(x, y):
""" when the button is 'clicked', that is: a mouse event is trapped within
the area of the button object, clear the screen from anything hitherto drawn
on it and call the function play() again """
if -70 < x < 70 and -90 < y < -50:
screen.clearscreen()
play(... | 5,318,221 |
def combine_fo_m(m, moved_f):
"""
derate
1 -> available
0 -> not available
rules for combing after moving fo
r -> min(m,fo)
"""
df = pd.DataFrame({"m": m,
"newf": moved_f})
return df.apply(min, axis=1) | 5,318,222 |
def modify_drone(solution, simulation):
"""Modifies the drone of a random operation.
...
Parameters:
solution(List[Transportation]): The list of the transportations of the solution
simulation(Simulation): The simulation
Returns:
List[Transportation]: The modified solution
"... | 5,318,223 |
def keygen():
"""
Generates random RSA keys
"""
a = gen_prime()
b = gen_prime()
if a == b:
keygen()
c = a * b
m = (a - 1) * (b - 1)
e = coPrime(m)
d = mod_inverse(e, m)
return (e, d, c) | 5,318,224 |
def psd_9(**kwargs):
"""powerlaw psd, log; no gaps, no alias, gauss noise
0.5 fq extension; x8 red leak; rescale lc mean
"""
# fqlag parameters #
n = 2**8
dt = 1.0
fql = np.logspace(np.log10(0.5/(dt*n)), np.log10(0.5*dt), 6)
lc, extra = simulate_light_curves(n=n, dt... | 5,318,225 |
def _succ(p, l):
"""
retrieve the successor of p in list l
"""
pos = l.index(p)
if pos + 1 >= len(l):
return l[0]
else:
return l[pos + 1] | 5,318,226 |
def generate_diff_mos(laygen, objectname_pfix, placement_grid, routing_grid_m1m2, devname_mos_boundary, devname_mos_body,
devname_mos_dmy, m=1, m_dmy=0, origin=np.array([0,0])):
"""generate an analog differential mos structure with dummmies """
pg = placement_grid
rg12 = routing_grid_m... | 5,318,227 |
def fetch_rrlyrae_templates(**kwargs):
"""Access the RR Lyrae template data (table 1 of Sesar 2010)
These return approximately 23 ugriz RR Lyrae templates, with normalized
phase and amplitude.
Parameters
----------
Returns
-------
templates: :class:`RRLyraeTemplates` object
co... | 5,318,228 |
def BVHTreeAndVerticesInWorldFromObj(obj):
"""
Input: Object of Blender type Object
Output: BVH Tree necessary for ray tracing and vertsInWorld = verts in global coordinate system.
"""
mWorld = obj.matrix_world
vertsInWorld = [mWorld @ v.co for v in obj.data.vertices]
bvh = BVHTree.FromPoly... | 5,318,229 |
def FixPssm(p):
"""FixPssm(p)
p is a MP object. This function fix the pssm, make each position sum to 1.
"""
for k in list(p.motifs.keys()):
for pssm in p.motifs[k]['pssm']:
for row in pssm:
rsum = sum([float(t) for t in row])
for t in range(len(row)):... | 5,318,230 |
def cli(ctx, version):
"""Library installation command for Minipresto."""
if not version:
version = utils.get_cli_ver()
lib_dir = os.path.join(ctx.minipresto_user_dir, "lib")
if os.path.isdir(lib_dir):
response = ctx.logger.prompt_msg(
f"The Minipresto library at {lib_dir} ... | 5,318,231 |
def _readline(ser):
"""Read a line from device on 'ser'.
ser open serial port
Returns all characters up to, but not including, a newline character.
"""
line = bytearray() # collect data in a byte array
while True:
c = ser.read(1)
if c:
if c == b'\n':
... | 5,318,232 |
def axline(x=None,y=None,a=None,b=None,label=None,lab_loc=0,ax=None,plot_kw={},**kwargs):
"""Generalised axis lines.
This function aims to generalise the usage of axis lines calls (axvline/axhline) together and
to allow lines to be specified by a slope/intercept according to the function y=a*x + b.
Parameters... | 5,318,233 |
def getPermCityState(permRecord):
"""Returns a string with the 'location' of the perm.
It is generated from the starting city and starting state.
This important conversion is used in many places and thus
warrants its own commonized utility method.
Input: a CSVRecord/permanent object.
Output: a ... | 5,318,234 |
def direct_group(parent):
"""Direct ldap access CLI group"""
@parent.group()
def direct():
"""Direct access to LDAP data"""
pass
@direct.command()
@click.option('-c', '--cls', help='Object class', required=True)
@click.option('-a', '--attrs', help='Addition attributes',
... | 5,318,235 |
def listPDBCluster(pdb, ch, sqid=95):
"""Returns the PDB sequence cluster that contains chain *ch* in structure
*pdb* for sequence identity level *sqid*. PDB sequence cluster will be
returned in as a list of tuples, e.g. ``[('1XXX', 'A'), ]``. Note that
PDB clusters individual chains, so the same PDB ... | 5,318,236 |
def elem_to_Z(sym: str) -> int:
"""
Converts element symbol to atomic number.
Parameters
----------
sym : str
Element string.
Returns
-------
int
Atomic number.
Examples
--------
>>> rd.utils.elem_to_Z('H')
1
>>> rd.utils.elem_to_Z('Br')
35
... | 5,318,237 |
def fn_I_axion_p(omega,xi_11,zeta_11,h_11,c_11,P_nuc,l,v,a,b,beta_11,k2,L_squid, R_squid, L_i, k_i, C_1, L_1, L_2, k_f, N_series,N_parallel):
"""Total axion-induced current through primary circuit, as a function of:
-- angular frequency omega
-- piezoaxionic tensor component xi_11
-- electroaxionic tens... | 5,318,238 |
def _C(startmat,endmat):
"""Calculate right Cauchy-Green deformation
tensor to go from start to end
:startmat: ndarray
:endmat: ndarray
:returns: ndarray
"""
F=_F(startmat,endmat)
C=np.dot(F.T,F)
return C | 5,318,239 |
def create_step_length(step_list):
"""
This function accepts a list of strings.
Each element in < step_list > has the format "Step< order >: < step >".
This function would return a dictionary called < step_length >.
This function should iterate over the < step_list > list.
For each step, the fun... | 5,318,240 |
def valid_uuid(uuid):
"""
Check if the given string is a valid uuid
"""
regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I)
match = regex.match(uuid)
return bool(match) | 5,318,241 |
def get_products_stats_data(domains, datespan, interval,
datefield='created_at'):
"""
Number of products by created time
"""
# groups products by the interval and returns the time interval and count
ret = (SQLProduct.objects
.filter(domain__in=domains,
... | 5,318,242 |
def task_schemas_json_orchestrator():
"""Schemas - generate hat-orchestrator JSON schema repository data"""
return _get_task_json(
[schemas_json_dir / 'orchestrator.yaml'],
[src_py_dir / 'hat/orchestrator/json_schema_repo.json']) | 5,318,243 |
def stopStreaming():
"""
Stop streaming.
Will return an `error` if streaming is not active.
"""
return __createJSON("StopStreaming", {}) | 5,318,244 |
def quit():
"""Exit the event loop on all MPI ranks.
This will cause :func:`event_loop` to terminate on all
MPI ranks.
"""
global finished, _event_loop_running
comm.bcast(('QUIT', None, None))
finished = True
_event_loop_running = False | 5,318,245 |
def process_doc(
doc: BeautifulSoup, proc: Callable = None, log: bool = True
) -> Union[None, Dict[str, Union[str, List]]]:
"""
Process soup to extract text in sections recursively
ex return:
{
"title": "Chapter 1",
"text": "",
"sections": [
{
"ti... | 5,318,246 |
def gain_corr_double_ExpDecayFunc(t, tau_A, tau_B, amp_A, amp_B, gc):
"""
Specific form of an exponential decay used for flux corrections.
Includes a "gain correction" parameter that is ignored when correcting
the distortions.
"""
y = gc * (1 + amp_A * np.exp(-t / tau_A) + amp_B * np.exp(-t / ta... | 5,318,247 |
def cross_entropy_sequence_loss(logits, targets, sequence_length):
"""Calculates the per-example cross-entropy loss for a sequence of logits and
masks out all losses passed the sequence length.
Args:
logits: Logits of shape `[T, B, vocab_size]`
targets: Target classes of shape `[T, B]`
sequence_len... | 5,318,248 |
def get_common_interior_polygons(polygon, list_of_polygons):
"""Check if polygon resides inside any polygon
in the list_of_polygons.
Parameters
----------
polygon: matplotlib.Polygon
Returns
-------
list_of_common_polygons: list
A filtered list of ids
... | 5,318,249 |
def criar_arquivo(nome_arquivo='passwords'):
"""Criará o arquivo que conterá as senhas.
Args:
nome_arquivo (str, optional): [Se for dado um argumento, o nome do arquivo será este argumento]. Senão, recebe 'passwords'.
"""
try:
arquivo = open(nome_arquivo + '.txt', 'wt+')
arquivo... | 5,318,250 |
def handle_image_size(input_image: np.ndarray, dimension: tuple):
"""
:param input_image:
:param dimension:
:return:
"""
assert input_image.ndim == 3, (
"Image should have 3 dimension '[HxWxC]'" "got %s",
(input_image.shape,),
)
assert len(dimension) == 2, (
... | 5,318,251 |
def netconvecs_to_listoflists(t_vec, id_vec, minmax=None):
"""
Convert data from NetCon.record(tvec, idvec) vectors into a dict
where the keys of the dict are the ids and the value is a list of
timestamps associated with that id.
:param tvec: Timestamp vector.
:param idvec: Associated ids o... | 5,318,252 |
def log_roulette_selection_method(fx_input, optimization_type_input, n_individuals_input, seed_input):
"""Roulette selection method with a twist. Here the evaluation value is processed with a log function. It reduces the difference between individuals, which increases population diversity."""
random.seed(se... | 5,318,253 |
def evaluate(attention_model,x_test,y_test):
"""
cv results
Args:
attention_model : {object} model
x_test : {nplist} x_test
y_test : {nplist} y_test
Returns:
cv-accuracy
"""
attention_model.batch... | 5,318,254 |
def reorder_cols_df(df, cols):
"""Reorder the columns of a DataFrame to start with the provided list of columns"""
cols2 = [c for c in cols if c in df.columns.tolist()]
cols_without = df.columns.tolist()
for col in cols2:
cols_without.remove(col)
return df[cols2 + cols_without] | 5,318,255 |
def remove_interface_configured_service_policy(device, interface, out=None):
""" Remove any service policy configured under interface
Args:
device (`obj`): Device object
interface (`str`): Interface to remove service policy from
out (`dict`): Show run interface <interfac... | 5,318,256 |
def uri_resolve(base: Union[str, Path], path: Optional[str]) -> str:
"""
Backport of datacube.utils.uris.uri_resolve()
"""
if path:
p = Path(path)
if p.is_absolute():
return p.as_uri()
if isinstance(base, Path):
base = base.absolute().as_uri()
return urljoin(... | 5,318,257 |
def plot_composanteOfEigenVector(matrixFileName, maxNumberOfVariables, numberOfComponent):
"""
-> Plot the major contribution to the eigenvectors
-> matrixFileName is name of the file where the matrix is stored
-> maxNumberOfVariables is the number of variables to display in plot
- can be set to "all"
-> numberO... | 5,318,258 |
def process_file_s3(out_dir, s3_dest, file):
"""
prepares and uploads data files to s3,
returns nothing
"""
file_name = f"{out_dir}/{file}"
gz_compress_csv(file_name)
os.remove(file_name) # removes the original .csv file after .gz version is created. This is to save disk space on containe... | 5,318,259 |
def preprocess_report(rep, rep2):
""" Processes lists containing report grades """
rv = np.asarray([rep], dtype="float32")
rv2 = np.asarray([rep2], dtype="float32")
return rv, rv2 | 5,318,260 |
async def async_check_srv_record(hass: HomeAssistant, host: str) -> dict[str, Any]:
"""Check if the given host is a valid Minecraft SRV record."""
# Check if 'host' is a valid SRV record.
return_value = None
srv_records = None
try:
srv_records = await aiodns.DNSResolver().query(
... | 5,318,261 |
def add_923_heat_rate(df):
"""
Small function to calculate the heat rate of records with fuel consumption and net
generation.
Parameters
----------
df : dataframe
Must contain the columns net_generation_mwh and
fuel_consumed_for_electricity_mmbtu
Returns
-------
dat... | 5,318,262 |
def get_local_bounding_box_min_max():
"""Gets an Axis-Aligned Bounding Box for the canonical die model, in local coordinate space."""
return np.array([[-0.49946,-0.48874,-0.52908],
[0.50094,0.51166,0.47132]]).T | 5,318,263 |
def add_renderer_globals(event):
"""Update the render dictionary with globals for every page."""
request = event['request']
event['user_id'] = authenticated_userid(request)
event['csrf_token'] = request.session.get_csrf_token() | 5,318,264 |
def get_inception_features(inputs, inception_graph, layer_name="pool_3:0"):
"""Compose the preprocess_for_inception function with TFGAN run_inception."""
preprocessed = preprocess_for_inception(inputs)
return tfgan_eval.run_inception(
preprocessed,
graph_def=inception_graph,
output_tensor=layer... | 5,318,265 |
def v4_multimax(iterable):
"""Return a list of all maximum values.
Bonus 1 - on short solution.
"""
try:
max_item = max(iterable)
except ValueError:
return []
return [
item
for item in iterable
if item == max_item
] | 5,318,266 |
def forwards(apps, schema_editor):
"""
Having added the new 'exhibition' Work type, we're going to assume that
every Event of type 'museum' should actually have one Exhibition attached.
So, we'll add one, with the same title as the Event.
And we'll move all Creators from the Event to the Exhibition... | 5,318,267 |
def uncompress_data():
"""Uncompress the data files"""
import gzip
with gzip.open(NEWS_FILE_NAME_COMPRESSED, 'rb') as compressed_file:
with open(NEWS_FILE_NAME_COMPRESSED[:-3], 'wb') as outfile:
outfile.write(compressed_file.read()) | 5,318,268 |
def sig_beg_to_adj_ground_ht(ds):
"""
Height in meters from GLAS signal beginning to whichever of the two lowest peaks has greater amplitude.
"""
return get_heights_from_distance(
ds, top_metric='sig_begin_dist', bottom_metric='adj_ground_peak_dist'
) | 5,318,269 |
def enable_logging() -> None:
"""Enable logging, off by default."""
global LOG
LOG = True
config_logging(logging, logging.INFO, log_file=f'{time.strftime("%Y-%m-%d %H-%M", time.localtime())}.log') | 5,318,270 |
def tree_to_formula(tree: DecisionTreeClassifier, concept_names: List[str], target_class: int) -> str:
"""
Translate a decision tree into a set of decision rules.
:param tree: sklearn decision tree
:param concept_names: concept names
:param target_class: target class
:return: decision rule
... | 5,318,271 |
def update_user_in_cache(user):
"""Get all users and create Cache files for each user."""
logger.info("Creating user in cache files.")
if ENABLE_USER_CACHING:
try:
if not os.path.exists(USER_CACHE_DIR):
os.makedirs(USER_CACHE_DIR)
# Create file for each user... | 5,318,272 |
def static_checker(workflow_inputs, workflow_outputs, step_inputs, step_outputs):
# type: (List[Dict[Text, Any]], List[Dict[Text, Any]], List[Dict[Text, Any]], List[Dict[Text, Any]]) -> None
"""Check if all source and sink types of a workflow are compatible before run time.
"""
# source parameters: wor... | 5,318,273 |
def datefix(datestr):
""" transform string into a python datetime object
handle mm/dd/yy or mm/dd/yyyy or dashes instead of slashes """
fix = datestr.replace('-','/')
if len(fix) > 4:
try:
return datetime.strptime(fix, "%m/%d/%y")
except ValueError:
return da... | 5,318,274 |
async def test_authenticated_socks5_request():
"""
Send an HTTP request via a SOCKS proxy.
"""
network_backend = AsyncMockBackend(
[
# The initial socks CONNECT
# v5 USERNAME/PASSWORD
b"\x05\x02",
# v1 VALID USERNAME/PASSWORD
b"\x01... | 5,318,275 |
def vector_angle(v1: Vector3D, v2: Vector3D) -> float:
"""
Calculate the angle between two given vectors.
Keyword arguments:
v1 -- First vector
v2 -- Second vector
"""
v1_n = normalize_vector(v1)
v2_n = normalize_vector(v2)
return math.acos(dot_product(v1_n, v2_n) / (vector_norm(v1_... | 5,318,276 |
def removed_mirrored_association(left_assoc, right_assoc):
"""
Remove the mirrored association (associations like (a, b) and (b, a)) that occurs in the intra-night associations.
The column id used to detect mirrored association are candid.
We keep the associations with the smallest jd in the left_assoc ... | 5,318,277 |
def sample_trajectory(smc_N, alpha, beta, radius, n_samples, seq_dist,
jt_traj=None, debug=False, reset_cache=True):
""" A particle Gibbs implementation for approximating distributions over
junction trees.
Args:
smc_N (int): Number of particles in SMC in each Gibbs iteration
... | 5,318,278 |
def create_token(data):
"""
Validator for the advertise api endpoint.
"""
schema = {
"type": "object",
"properties": {
'name': {
'type': 'string'
}
},
"additionalProperties": False,
"required": ['name']
}
try:
... | 5,318,279 |
def product(d1: Dataset[_T], d2: Dataset[_U], predicate: str = "intersects") -> Iterator[Tuple[_T, _U]]:
"""
Helper function if you don't care about metadata like errors etc.
"""
yield from Product(d1, d2, predicate) | 5,318,280 |
def valgrind_supports_exit_early():
"""Checks if we support early exit from valgrind"""
version = helpers.run_subprocess(['valgrind', '--version'])
match = re.match(r'valgrind-(\d)\.(\d+).*', version)
if match:
return int(match.group(2)) >= 14
return False | 5,318,281 |
def read_rows(input_file, expected_fields):
"""Read the input_file as a CSV; validate that the expected_fields are
present. Sys.exit if not
:return: pair of list of dicts (rows in the CSV), and a list of headers
found in the input_file"""
reader = csv.DictReader(input_file)
all_rows = [d for d i... | 5,318,282 |
def document_etag(value: dict, ignore_fields: List[str] = None) -> str:
"""Computes and returns a valid ETag for the input value."""
h = hashlib.sha1()
h.update(dumps(value, sort_keys=True).encode("utf-8"))
return h.hexdigest() | 5,318,283 |
def answer(request):
"""
Save the answer.
GET parameters:
html:
turn on the HTML version of the API
BODY
json in following format:
{
"answer": #answer, -- for one answer
"answers": [#answer, #answer, #answer ...] -- for multiple ans... | 5,318,284 |
def assert_allclose(actual: int, desired: int, atol: float):
"""
usage.scipy: 1
usage.statsmodels: 4
"""
... | 5,318,285 |
def test_run_command(ctx, **kwargs):
"""Runs fnfi commands on test data using default options.
fnfi defaults for the run command can be modified by adding the respective option, e.g. add --procs 4"""
def update_ctx(kwargs, ctx):
for k, v in defaults.items() + kwargs.items() + {ctx.args[i][2:]: ctx.... | 5,318,286 |
def valid_client_model(initialize_db):
"""
A fixture for creating a valid client model.
Args:
initialize_db (None): initializes the database and drops tables when
test function finishes.
"""
return Client(username='Leroy Jenkins', avatar_url='').save() | 5,318,287 |
def merge_features(df: pd.DataFrame)-> pd.DataFrame:
"""
Merges features that estimate the same thing
"""
# kelvin conversions
df['station_max_temp_c'] += 273.15
df['station_min_temp_c'] += 273.15
df['station_avg_temp_c'] += 273.15
df = (df
.fillna(method = 'backfill')
... | 5,318,288 |
def threatActorSTIX(adversaries):
"""
Parse the adversaries key to convert it to STIX
"""
adversariesList = []
for adv in adversaries: adversariesList.append(ThreatActor(name="%s"%(adv))) if len(adversaries) >= 1 else adversariesList.append(ThreatActor(name="%s"%(adversaries[0])))
return adversariesList | 5,318,289 |
def merge_channels(data, sampling_rate, filter_data: bool = True):
"""Merge channels based on a running maximum.
Args:
data (ndarray): [samples, channels]
sampling_rate (num): in Hz
Returns:
ndarray: merged across
"""
data = np.array(data) # ensure data is an np.array (and... | 5,318,290 |
def maximalEigenvector(A):
""" using the eig function to compute eigenvectors """
n = A.shape[1]
_,v = np.linalg.eig(A)
return abs(np.real(v[:n,0])/np.linalg.norm(v[:n,0],1)) | 5,318,291 |
def basic_earnings_power(stock, date=None, lookback_period: timedelta = timedelta(days=0), period: str = 'FY'):
"""
:param stock: ticker(s) in question. Can be a string (i.e. 'AAPL') or a list of strings (i.e. ['AAPL', 'BA']).
:param date: Can be a datetime (i.e. datetime(2019, 1, 1)) or list of datetimes.... | 5,318,292 |
def remove_hyperlinks(text):
"""Remove hyperlinks from text."""
# If text is empty, return None.
if not text: return None
# If is tokenized, merge tokens.
if is_tokenized(text):
was_tokenized = True
normalized_text = merge_tokens(text)
else:
was_tokenized = False
... | 5,318,293 |
def test_prepare_key_for_scan(valid_search):
"""Key isn't validated or set for a scan"""
valid_search.mode = "scan"
# Key condition isn't even on the right model
valid_search.key = User.joined < "now"
prepared = valid_search.prepare()
assert prepared.key is None | 5,318,294 |
def read_struct_file(struct_file, return_type=GeoStruct):
"""read an existing PEST-type structure file into a GeoStruct instance
Args:
struct_file (`str`): existing pest-type structure file
return_type (`object`): the instance type to return. Default is GeoStruct
Returns:
[`pyemu.... | 5,318,295 |
def _check_nx(path):
"""NX - This mitigation technique attempts to mark
as the binary as non-executable memory. E.g. An attacker
can't as easily fill a buffer with shellcode and jump
to the start address. It is common for this to be disabled
for things like JIT interpreters.
"""
headers = _e... | 5,318,296 |
def verify_auth(username, password):
""" Verify the HTTP Basic Auth credentials """
config = app.config
return username == config['USERNAME'] and password == config['PASSWORD'] | 5,318,297 |
def main(): # pragma: no cover
"""
A wrapper for the program entrypoint that formats uncaught exceptions in a
crash report template.
"""
settings = SettingStore()
try:
settings.load()
except MnamerException as e:
tty.error(e)
raise SystemExit(2)
try:
fron... | 5,318,298 |
def make_mask(imagename, thresh, fl=False, useimage=False, pixelmin=0, major=0,
minor=0, pixelsize=0, line=False, overwrite_old=True,
closing_diameter=6, pbimage=None, myresidual=None, myimage=None,
extension='.fullmask'):
"""
Makes a mask on any image you want it to.
... | 5,318,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.