content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _rstrip_inplace(array):
"""
Performs an in-place rstrip operation on string arrays. This is necessary
since the built-in `np.char.rstrip` in Numpy does not perform an in-place
calculation.
"""
# The following implementation convert the string to unsigned integers of
# the right length. ... | f59d6d127d4d3f0725df5eee2e4586ccbea9288b | 3,653,937 |
def compute_fixpoint_0(graph, max_value):
"""
Computes the fixpoint obtained by the symbolic version of the backward algorithm for safety games.
Starts from the antichain of the safe set and works backwards using controllable predecessors.
The maximum value for the counters is a parameter to facilitate ... | e2ee9cb00ce6f88e03a080d85a635c208cdd5a35 | 3,653,938 |
def extract_unii_other_code(tree):
"""Extract the codes for other ingredients"""
unii_other_xpath = \
'//generalizedMaterialKind/code[@codeSystem="%s"]/@code' % UNII_OTHER_OID
return tree.getroot().xpath(unii_other_xpath) | 0576dc7537a9212990a72125b8fd406c457efb76 | 3,653,939 |
import functools
def initfunc(f):
"""
Decorator for initialization functions that should
be run exactly once.
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
if wrapper.initialized:
return
wrapper.initialized = True
return f(*args, **kwargs)
wrap... | 337ca902fc1fbe138ad5dd4c203a3cac77e89f57 | 3,653,940 |
def edit_frame(frame):
"""edit frame to analyzable frame
rgb 2 gray
thresh frame color
bitwise color
Args
frame (ndarray): original frame from movie
Returns
work_frame (ndarray): edited frame
"""
work_frame = frame
work_frame = cv2.cvtColor(work_frame, cv2.COLOR... | b82588fa81093c05e4a683b76aa367ba2be4b2e2 | 3,653,941 |
def manchester(bin_string):
"""
Applies the Manchester technique to a string of bits.
:param bin_string:
:type bin_string: str
:return:
:rtype: str
"""
signal_manager = Signal()
for bin_digit in bin_string:
if bin_digit == '0': # Generate +-
if signal_manager... | e5f58e929db74f0eeb2a003c25c5097f45c74989 | 3,653,942 |
from typing import List
def load_admin_cells(identifier: str) -> List[MultiPolygon]:
"""Loads the administrative region cells
Data is loaded from :py:const:`ADMIN_GEOJSON_TEMPLATE` ``% identifier``.
This is a wrapper function for :py:func:`load_polygons_from_json`.
Returns:
A list of the adm... | dc2083ca7392da5b2d6509b6dd8f108bd8218726 | 3,653,943 |
import inspect
def register_writer(format, cls=None):
"""Return a decorator for a writer function.
A decorator factory for writer functions.
A writer function should have at least the following signature:
``<class_name_or_generator>_to_<format_name>(obj, fh)``. `fh` is **always**
an open filehan... | b8312d987cecfa106c73afb4eca5299637d260f6 | 3,653,944 |
import torch
def accuracy(output, target, topk=1,axis=1,ignore_index=-100, exclude_mask=False):
"""Computes the precision@k for the specified values of k
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
"""
input_tensor=output.copy().detach()
target_tensor=target.copy().detach()
num_c... | a35d4bff308862c4c8a83948c619e66299d7887f | 3,653,946 |
def jitter_over_thresh(x: xr.DataArray, thresh: str, upper_bnd: str) -> xr.DataArray:
"""Replace values greater than threshold by a uniform random noise.
Do not confuse with R's jitter, which adds uniform noise instead of replacing values.
Parameters
----------
x : xr.DataArray
Values.
t... | 1a508c30aa68c3b8808f3fe0b254ad98621cd245 | 3,653,947 |
from .rename_axis import rename_axis_with_level
def index_set_names(index, names, level=None, inplace=False):
"""
Set Index or MultiIndex name.
Able to set new names partially and by level.
Parameters
----------
names : label or list of label
Name(s) to set.
level : int, label or... | 4ad24ea4c1fd42b1259d43e273c44c4295a9e329 | 3,653,948 |
def get_critic(obs_dim: int) -> tf.keras.Model:
"""Get a critic that returns the expect value for the current state"""
observation = tf.keras.Input(shape=(obs_dim,), name='observation')
x = layers.Dense(64, activation='tanh')(observation)
x = layers.Dense(64, activation='tanh')(x)
value = layers.Den... | 69082d6260666c733e32093fbc7180726f77acc6 | 3,653,949 |
def register_and_login_test_user(c):
"""
Helper function that makes an HTTP request to register a test user
Parameters
----------
c : object
Test client object
Returns
-------
str
Access JWT in order to use in subsequent tests
"""
c.post(
"/api/auth/regi... | b76f7f6afa9af453246ae304b1b0504bd68b8919 | 3,653,950 |
def get_ssh_challenge_token(account, appid, ip=None, vo='def'):
"""
Get a challenge token for subsequent SSH public key authentication.
The challenge token lifetime is 5 seconds.
:param account: Account identifier as a string.
:param appid: The application identifier as a string.
:param ip: IP... | 12da26b4a20e648ca9fc6d325647f42288324b83 | 3,653,951 |
def rootpath_capacity_exceeded(rootpath,newSize):
"""
Return True if rootpath is already allocated to the extent
it cannot accomadate newSize, otherwise return False
"""
vols_in_rootpath = Volume.objects.filter(root_path=rootpath)
rootpathallocsum = 0
if vols_in_rootpath.count() > 0:
... | 3b8d90f3693ce12de93c967d20c6a7b2ccb7ec38 | 3,653,952 |
import requests
import json
def user_token(user: str) -> str:
"""
Authorize this request with the GitHub app set by the 'app_id' and
'private_key' environment variables.
1. Get the installation ID for the user that has installed the app
2. Request a new token for that user
3. Return it so it c... | c02fae92505a922f58f231682a009d24ed6432bc | 3,653,953 |
def file_exists(path):
"""
Return True if the file from the path exists.
:param path: A string containing the path to a file.
:return: a boolean - True if the file exists, otherwise False
"""
return isfile(path) | 79610224c3e83f6ba4fdeb98b1faaf932c249ff2 | 3,653,954 |
from typing import Callable
from typing import Dict
def _static_to_href(pathto: Callable, favicon: Dict[str, str]) -> Dict[str, str]:
"""If a ``static-file`` is provided, returns a modified version of the icon
attributes replacing ``static-file`` with the correct ``href``.
If both ``static-file`` and ``h... | f54e5ced825dc44bfa14a09622c7fa9b179660c5 | 3,653,955 |
import torch
def concatenate(tensor1, tensor2, axis=0):
"""
Basically a wrapper for torch.dat, with the exception
that the array itself is returned if its None or evaluates to False.
:param tensor1: input array or None
:type tensor1: mixed
:param tensor2: input array
:type tensor2: numpy.... | 24791a201f1ddb64cd2d3f683ecc38471d21697b | 3,653,956 |
def setKey(key, keytype):
""" if keytype is valid, save a copy of key accordingly
and check if the key is valid """
global _key, _keytype, FREE_API_KEY, PREMIUM_API_KEY
keytype = keytype.lower()
if keytype in ("f", "fr", "free"):
keytype = "free"
FREE_API_KEY = key
elif keyt... | 8baab2972ea5c9fbe33845aaed7c1ab4cc631a2e | 3,653,957 |
import functools
import operator
def sum_(obj):
"""Sum the values in the given iterable.
Different from the built-in summation function, the summation is based on
the first item in the iterable. Or a SymPy integer zero is created
when the iterator is empty.
"""
i = iter(obj)
try:
... | 70727443ba5a62e5bd91e3c0a60130f6cc0b65e5 | 3,653,958 |
def setup_s3_client(job_data):
"""Creates an S3 client
Uses the credentials passed in the event by CodePipeline. These
credentials can be used to access the artifact bucket.
:param job_data: The job data structure
:return: An S3 client with the appropriate credentials
"""
try:
key... | bb51e03de125eeb6ff5e1e6d16b50ba07fdc7c56 | 3,653,959 |
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.):
"""
FROM KERAS
Pads each sequence to the same length:
the length of the longest sequence.
If maxlen is provided, any sequence longer
than maxlen is truncated to maxlen.
Truncation happens off... | 5d4603c5a71f898dc4f501d2424707ea10adbd0e | 3,653,961 |
def basic_pyxll_function_22(x, y, z):
"""if z return x, else return y"""
if z:
# we're returning an integer, but the signature
# says we're returning a float.
# PyXLL will convert the integer to a float for us.
return x
return y | 851b5eef683b0456a0f5bce7f3850698693b067e | 3,653,962 |
def job_hotelling(prob_label, tr, te, r, ni, n):
"""Hotelling T-squared test"""
with util.ContextTimer() as t:
htest = tst.HotellingT2Test(alpha=alpha)
test_result = htest.perform_test(te)
return {
'test_method': htest,
'test_result': test_result,
'time_se... | 137a3b4426a01675fe6995408ad71eec34126341 | 3,653,963 |
def return_circle_aperature(field, mask_r):
"""Filter the circle aperature of a light field.
Filter the circle aperature of a light field.
Parameters
----------
field : Field
Input square field.
mask_r : float, from 0 to 1
Radius of a circle mask.
Returns
... | 49ae52bfa639cf8a7b8592caa1dbf8dbdef115f8 | 3,653,964 |
import json
def user_get():
"""
Get information from the database about an user, given his id. If there are
field names received in the body, only those will be queried. If no field is
provided, every field will be selected. The body should be a JSON object
following the schema:
{
"use... | 02b1a1bc1bedc2098bd907098a40fad41c2391d7 | 3,653,965 |
def get_data_file_args(args, language):
"""
For a interface, return the language-specific set of data file arguments
Args:
args (dict): Dictionary of data file arguments for an interface
language (str): Language of the testbench
Returns:
dict: Language-specific data file argume... | 11e30b92316bad9a46b87bd9188f97d5e8860377 | 3,653,966 |
def branch_exists(branch):
"""Return True if the branch exists."""
try:
run_git("rev-parse --verify {}".format(branch), quiet=True)
return True
except ProcessExecutionError:
return False | 8f08eeb78b322220def2f883e8172ac94df97063 | 3,653,967 |
import numpy
def spectrum_like_noise(signal: numpy.ndarray,
*,
sampling_rate=40000,
keep_signal_amp_envelope=False,
low_pass_cutoff=50, # Hz
low_pass_order=6,
seed: int = 42... | 6e6ced3a5220a9a1d66c83a33a9232d265d18a1a | 3,653,968 |
import re
def check_string_capitalised(string):
""" Check to see if a string is in all CAPITAL letters. Boolean. """
return bool(re.match('^[A-Z_]+$', string)) | f496d79fafae4c89c3686856b42113c4818f7ed8 | 3,653,969 |
import torch
def sample_zero_entries(edge_index, seed, num_nodes, sample_mult=1.0):
"""Obtain zero entries from a sparse matrix.
Args:
edge_index (tensor): (2, N), N is the number of edges.
seed (int): to control randomness
num_nodes (int): number of nodes in the graph
sample_... | 211e97fa0a2622d49c50673c0b6255954383f3a0 | 3,653,970 |
import textwrap
def ped_file_parent_missing(fake_fs):
"""Return fake file system with PED file"""
content = textwrap.dedent(
"""
# comment
FAM II-1\tI-1\t0\t1\t2
FAM I-1 0\t0\t1\t1
"""
).strip()
fake_fs.fs.create_file("/test.ped", create_missing_dirs=True, contents=conten... | 9df19ab925984236aa581c9b8843591f05d3b7b4 | 3,653,971 |
import random
import requests
def GettingAyah():
"""The code used to get an Ayah from the Quran every fixed time"""
while True:
ayah = random.randint(1, 6237)
url = f'http://api.alquran.cloud/v1/ayah/{ayah}'
res = requests.get(url)
if len(res.json()['data']['text']) <= 280:
... | 5739cbd3554b97f01eefef7f59a4087e5497e3e7 | 3,653,972 |
def iterdecode(value):
"""
Decode enumerable from string presentation as a tuple
"""
if not value:
return tuple()
result = []
accumulator = u''
escaped = False
for c in value:
if not escaped:
if c == CHAR_ESCAPE:
escaped = True
... | d8b03338a4578ee7b37a4f6d31d23463fc0a9b84 | 3,653,973 |
def run_resolution_filter(image=None, image_path=None, height=600, width=1000):
"""
This will take the image which is correctly rotated yolo output. Initially, We
are doing for driving licenses only, Will return 1 if the height and width
are greater than 700 and 1100 pixels else it will return 10002
:return:... | fde3040dbb29d6c5f7d79237df51f425d2d043b4 | 3,653,974 |
import types
def text_to_emotion(text):
"""
テキストから感情を推測して返す
Parameters
----------
text : string
テキスト
Returns
-------
{'magnitude','score'}
"""
client = language.LanguageServiceClient()
document = types.Document(
content=text,
type=enums.Document.Ty... | b3b784fa777146f7f1a361784f848b28651676a4 | 3,653,975 |
def process_actions(list_response_json, headers, url, force_reset):
"""
If a policy does not exist on a given cluster find the right values
defined in qos_dict and apply them
"""
qos_dict = {}
# This dictionary sets the tiers and min/max/burst settings
qos_dict['tiers'] = {"bronze": [500, 50... | 1c3651518c8c0f0f174876afdd0961099b3af342 | 3,653,976 |
def validate_ac_power(observation, values):
"""
Run a number of validation checks on a daily timeseries of AC power.
Parameters
----------
observation : solarforecastarbiter.datamodel.Observation
Observation object that the data is associated with
values : pandas.Series
Series of ... | fcc487f61276e319316df3f99559ef935a7f0e7b | 3,653,977 |
import itertools
import six
def partition(predicate, iterable):
"""Use `predicate` to partition entries into falsy and truthy ones.
Recipe taken from the official documentation.
https://docs.python.org/3/library/itertools.html#itertools-recipes
"""
t1, t2 = itertools.tee(iterable)
return (
... | 5777203d9d34a9ffddc565129d8dda3ec91efc8e | 3,653,978 |
def get_node(obj, path):
"""Retrieve a deep object based on a path. Return either a Wrapped instance if the deep object is not a node, or another type of object."""
subobj = obj
indices = []
for item in path:
try:
subobj = subobj[item]
except Exception as e:
indic... | f48cb0dc5ae149d0758348725ebc521e7838230f | 3,653,980 |
def without_bond_orders(gra):
""" resonance graph with maximum spin (i.e. no pi bonds)
"""
bnd_keys = list(bond_keys(gra))
# don't set dummy bonds to one!
bnd_ord_dct = bond_orders(gra)
bnd_vals = [1 if v != 0 else 0
for v in map(bnd_ord_dct.__getitem__, bnd_keys)]
bnd_ord_dc... | 88b785c802a1d74a12f64a1eab6403429fa00cad | 3,653,981 |
def check_struc(d1, d2,
errors=[], level='wf'):
"""Recursively check struct of dictionary 2 to that of dict 1
Arguments
---------
d1 : dict
Dictionary with desired structure
d2 : dict
Dictionary with structre to check
errors : list of str, optional
Missin... | aa835e7bbd6274e73d0b3d45d1ec4d617af0a167 | 3,653,982 |
def indexoflines(LFtop):
""" Determining selected line index of Gromacs compatible topology files """
file1 = open(LFtop, "r")
readline = file1.readlines()
lineindex = ["x", "x", "x"]
n = 0
for line in readline:
linelist = line.split()
if "atomtypes" in linelist:
lineindex[0] = n
n += 1
elif "molecule... | dd2653c6245d9f7a0fa8647dcc841c51e01f9b2d | 3,653,983 |
def create_mock_github(user='octo-cat', private=False):
"""Factory for mock GitHub objects.
Example: ::
>>> github = create_mock_github(user='octocat')
>>> github.branches(user='octocat', repo='hello-world')
>>> [{u'commit': {u'sha': u'e22d92d5d90bb8f9695e9a5e2e2311a5c1997230',
... | 7eaffcc7bc22657eaf3c3e7d41d9492300128a73 | 3,653,984 |
def top_9(limit=21):
"""Vrni dano število knjig (privzeto 9). Rezultat je seznam, katerega
elementi so oblike [knjiga_id, avtor,naslov,slika] """
cur.execute(
"""SELECT book_id, authors, title, original_publication_year, average_rating,image_url
FROM books
ORDER BY average_rating DE... | ec87714ea5925c5d4115b0ee091597f7ffb1c323 | 3,653,986 |
def inverseTranslateTaps(lowerTaps, pos):
"""Method to translate tap integer in range
[-lower_taps, raise_taps] to range [0, lowerTaps + raiseTaps]
"""
# Hmmm... is it this simle?
posOut = pos + lowerTaps
return posOut | 827bdfc51b3581b7b893ff8ff02dd5846ff6cd0f | 3,653,988 |
def GMLstring2points(pointstring):
"""Convert list of points in string to a list of points. Works for 3D points."""
listPoints = []
#-- List of coordinates
coords = pointstring.split()
#-- Store the coordinate tuple
assert(len(coords) % 3 == 0)
for i in range(0, len(coords), 3):
list... | e755d344d163bdcdb114d0c9d614a1bbd40be29f | 3,653,989 |
def set_(key, value, service=None, profile=None): # pylint: disable=W0613
"""
Set a key/value pair in the etcd service
"""
client = _get_conn(profile)
client.set(key, value)
return get(key, service, profile) | c9689c53dc837caf182ac0b5d0e8552888ec70e9 | 3,653,990 |
def compute_cw_score_normalized(p, q, edgedict, ndict, params = None):
"""
Computes the common weighted normalized score between p and q
@param p -> A node of the graph
@param q -> Another node in the graph
@param edgedict -> A dictionary with key `(p, q)` and value `w`.
@param ndi... | 7769bc21d6a6bf176002ea6f4020cbe78f971b84 | 3,653,991 |
def prompt_user_friendly_choice_list(msg, a_list, default=1, help_string=None):
"""Prompt user to select from a list of possible choices.
:param msg:A message displayed to the user before the choice list
:type msg: str
:param a_list:The list of choices (list of strings or list of dicts with 'name' & 'de... | d2c81b8af3f2de3203dd8cfd11372909e2e9cbe3 | 3,653,992 |
import typing
import json
def fuse(search: typing.Dict, filepath: str):
"""Build a JSON doc of your pages"""
with open(filepath, "w") as jsonfile:
return json.dump(
[x for x in _build_index(search, id_field="id")],
fp=jsonfile,
) | 542aff31a2861bc8de8a25025582305db0ce2af1 | 3,653,993 |
def aggregate_gradients_using_copy_with_device_selection(
tower_grads, avail_devices, use_mean=True, check_inf_nan=False):
"""Aggregate gradients, controlling device for the aggregation.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over towers. The inner li... | 24d12a4e3ee63b96dd453bc901a9180ed956003b | 3,653,994 |
def ToOrdinal(value):
"""
Convert a numerical value into an ordinal number.
@param value: the number to be converted
"""
if value % 100//10 != 1:
if value % 10 == 1:
ordval = '{}st'.format(value)
elif value % 10 == 2:
ordval = '{}nd'.format(value)
elif... | 774bac5fd22714ba3eb4c9dd2b16f4236e2f5e8c | 3,653,995 |
from typing import List
def compute_partition(num_list: List[int]):
"""Compute paritions that add up."""
solutions = []
for bits in helper.bitprod(len(num_list)):
iset = []
oset = []
for idx, val in enumerate(bits):
(iset.append(num_list[idx]) if val == 0 else
... | 408f5f85b1648facdcebfd47f96f53221b54888e | 3,653,996 |
def renumber(conllusent):
"""Fix non-contiguous IDs because of multiword tokens or removed tokens"""
mapping = {line[ID]: n for n, line in enumerate(conllusent, 1)}
mapping[0] = 0
for line in conllusent:
line[ID] = mapping[line[ID]]
line[HEAD] = mapping[line[HEAD]]
return conllusent | 30f336cd63e7aff9652e6e3d1a35a21dc3379c99 | 3,653,997 |
def recall_at(target, scores, k):
"""Calculation for recall at k."""
if target in scores[:k]:
return 1.0
else:
return 0.0 | 0c3f70be3fb4cfde16d5e39b256e565f180d1655 | 3,653,998 |
def supports_dynamic_state() -> bool:
"""Checks if the state can be displayed with widgets.
:return: True if widgets available. False otherwise.
"""
return widgets is not None | bee2f32bb315f086b6bd8b75535eb8fdde36a188 | 3,653,999 |
def create_partial_image_rdd_decoder(key_type):
"""Creates a partial, tuple decoder function.
Args:
value_type (str): The type of the value in the tuple.
Returns:
A partial :meth:`~geopyspark.protobufregistry.ProtoBufRegistry.image_rdd_decoder`
function that requires ``proto_bytes`... | 2df5c506cf8603e9e4acbb4ccb77f8f5d830fe82 | 3,654,000 |
import json
def to_json(simple_object):
"""
Serializes the ``simple_object`` to JSON using the EnhancedJSONEncoder above.
"""
return json.dumps(simple_object, cls=EnhancedJSONEncoder) | c9f8c9474210661a7b63924a72442014c831e170 | 3,654,001 |
def bootstrap_metadata():
""" Provides cluster metadata which includes security modes
"""
return _metadata_helper('bootstrap-config.json') | ec2294606446a9b78a603826fca6f447ed2d9bb9 | 3,654,002 |
def unique_slug(*, title: str, new_slug: str = None) -> str:
"""Create unique slug.
Args:
title: The text where the slug will be generate.
new_slug: Custom slug to hard code.
Returns:
The created slug or hard code slug
"""
if new_slug is None:
slug = slugify(title)... | b4e119502edf144f8393b38a47e3fbeb25335aff | 3,654,003 |
import math
def dcg(r, k=None):
"""The Burges et al. (2005) version of DCG.
This is what everyone uses (except trec_eval)
:param r: results
:param k: cut-off
:return: sum (2^ y_i - 1) / log (i +2)
"""
result = sum([(pow(2, rel) - 1) / math.log(rank + 2, 2) for rank, rel in enumerate(r[:k]... | d93c500ba55411807570c8efebdeaa49ce7fe288 | 3,654,004 |
async def detect_objects(computervision_client, image_url):
"""Detect objects from a remote image"""
detect_objects_results_local = \
computervision_client.detect_objects(image_url)
return detect_objects_results_local.objects | 9adb2a3b2c08f99187159ad6a22047bbf3d4c30a | 3,654,005 |
def rgb(r=None, g=None, b=None, smooth=True, force=True):
"""
Set RGB values with PWM signal
:param r: red value 0-1000
:param g: green value 0-1000
:param b: blue value 0-1000
:param smooth: runs colors change with smooth effect
:param force: clean fade generators and set color
:retu... | 5d5455a785a719e5252c3333e45c06352e8769ed | 3,654,006 |
from .core.configs import get_configs
from .core.configs import set_configs
from .core.configs import del_configs
def handle_config(args, configs):
"""Handle `view` subcommand
:param args: parsed arguments
:type args: `argparse.Namespace`
:param configs: configurations object
:type configs: `... | 60fb9b289e99369a9f83bdf675a793fe85191257 | 3,654,007 |
from typing import Dict
from typing import List
def filter_safe_actions(
action_shield: Dict[int, Dict[ActionData, int]], energy: int, bel_supp_state: int
) -> List[ActionData]:
"""Utility function to filter actions according to required energy for them with given action shield.
Parameters
----------... | e62b24233792d4decca1bd853b6344a8541882be | 3,654,008 |
def fcard(card):
"""Create format string for card display"""
return f"{card[0]} {card[1]}" | ca3866011b418bf35e1b076afd7134926a9382f9 | 3,654,010 |
def resetChapterProgress(chapterProgressDict, chapter, initRepeatLevel):
"""This method resets chapter progress and sets initial level for repeat routine.
Args:
chapterProgressDict (dict): Chapter progress data.
chapter (int): Number of the chapter.
initRepeatLevel (int): Initial level ... | e02d6e97f556a2c080c2bc273255aacedf7bb086 | 3,654,011 |
def aStarSearch(problem, heuristic=nullHeuristic):
"""Search the node that has the lowest combined cost and heuristic first."""
"*** YOUR CODE HERE ***"
priorityqueue = util.PriorityQueue()
priorityqueue.push( (problem.getStartState(), [], 0), heuristic(problem.getStartState(), problem) )
checkedsta... | 0d84de971424d82020b48e35443bfe92cc2665d0 | 3,654,012 |
def gen_flag(p1=0.5, **_args):
"""
Generates a flag.
:param p1: probability of flag = 1
:param _args:
:return: flag
"""
return 1 if np.random.normal(0, 100) <= p1 * 100 else 0 | 0accef3f2fd03c4918b52db2f6c72d405243af87 | 3,654,013 |
from typing import OrderedDict
import re
def load_migrations(path):
"""
Given a path, load all migrations in that path.
:param path: path to look for migrations in
:type path: pathlib.Path or str
"""
migrations = OrderedDict()
r = re.compile(r'^[0-9]+\_.+\.py$')
filtered = filter(
... | 5bd761e6a9ffab4aa08a473e8d2c667e7fb87813 | 3,654,014 |
def filterkey(e, key, ns=False):
"""
Gibt eine Liste aus der Liste C{e} mit dem Attribut C{key} zurück.
B{Beispiel 1}: Herauslesen der SRS aus einer Liste, die C{dict}'s enthält.
>>> e = [{'SRS':'12345', 'Name':'WGS-1'}, {'SRS':'54321', 'Name':'WGS-2'}]
>>> key = "SRS"
>>> filterkey(e, key)
... | f56967e9623622d2dffdb9fe6f128893df9ad798 | 3,654,015 |
def on_coordinator(f):
"""A decorator that, when applied to a function, makes a spawn of that function happen on the coordinator."""
f.on_coordinator = True
return f | d9c97c47255d165c67a4eb67a18cc85c3c9b9386 | 3,654,018 |
def redirect_subfeed(match):
"""
URL migration: my site used to have per-category/subcategory RSS feeds
as /category/path/rss.php. Many of the categories have Path-Aliases
in their respective .cat files, but some of the old subcategories no
longer apply, so now I just bulk-redirect all unaccounted-f... | 101509cbf75ce9be5307edd265988cca662a7880 | 3,654,019 |
from typing import List
from typing import Tuple
import random
def _train_test_split_dataframe_strafified(df:pd.DataFrame, split_cols:List[str], test_ratio:float=0.2, verbose:int=0, **kwargs) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
ref. the function `train_test_split_dataframe`
"""
df_inspection = d... | 82c4f2a1da3d7e7a4a854c037ab209dffe01f5b2 | 3,654,020 |
def index():
"""
This route will render a template.
If a query string comes into the URL, it will return a parsed
dictionary of the query string keys & values, using request.args
"""
args = None
if request.args:
args = request.args
return render_template("public/index.ht... | ae76de55fb9263264d87447fc2fe173ad62e3245 | 3,654,021 |
from typing import Type
from typing import List
def multi_from_dict(cls: Type[T_FromDict], data: dict, key: str) -> List[T_FromDict]:
"""
Converts {"foo": [{"bar": ...}, {"bar": ...}]} into list of objects using the cls.from_dict method.
"""
return [cls.from_dict(raw) for raw in data.get(key, [])] | 44b9aa28d93f24cc76cddf3cba9fbcbcde937d3d | 3,654,022 |
import inspect
def infer_signature(func, class_name=''):
"""Decorator that infers the signature of a function."""
# infer_method_signature should be idempotent
if hasattr(func, '__is_inferring_sig'):
return func
assert func.__module__ != infer_method_signature.__module__
try:
fu... | e1ab5d9850b4a3026ecd563324026c9cd1675d31 | 3,654,023 |
def field_wrapper(col):
"""Helper function to dynamically create list display method
for :class:`ViewProfilerAdmin` to control value formating
and sort order.
:type col: :data:`settings.ReportColumnFormat`
:rtype: function
"""
def field_format(obj):
return col.format.format(getattr(... | 0a41b5462a6905af5d1f0cc8b9f2bdd00206e6bd | 3,654,024 |
def is_isotropic(value):
""" Determine whether all elements of a value are equal """
if hasattr(value, '__iter__'):
return np.all(value[1:] == value[:-1])
else:
return True | 9c99855d53cf129931c9a9cb51fc491d2fe0df21 | 3,654,025 |
def grouper(iterable, n, fillvalue=None):
"""Iterate over a given iterable in n-size groups."""
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue) | 26adffa4a3c748defe3732d5b94358dda20d095c | 3,654,026 |
def format_gro_coord(resid, resname, aname, seqno, xyz):
""" Print a line in accordance with .gro file format, with six decimal points of precision
Nine decimal points of precision are necessary to get forces below 1e-3 kJ/mol/nm.
@param[in] resid The number of the residue that the atom belongs to
@pa... | ceeeeeafe4f7484fa17ee4ebd79363209c8f7391 | 3,654,027 |
def return_as_list(ignore_nulls: bool = False):
"""
Enables you to write a list-returning functions using a decorator. Example:
>>> def make_a_list(lst):
>>> output = []
>>> for item in lst:
>>> output.append(item)
>>> return output
Is equivalent to:
>>> @retur... | 5f5f089e5664ffbbd5d78a71bf984909e677bcc5 | 3,654,028 |
def assemble_insert_msg_content(row, column, digit):
"""Assemble a digit insertion message."""
return str(row) + CONTENT_SEPARATOR + str(column) + CONTENT_SEPARATOR + str(digit) | 5c4a40aedf4569a8f12793356c2cbedecf32d839 | 3,654,030 |
from typing import Union
def get_difference_of_means(uni_ts: Union[pd.Series, np.ndarray]) -> np.float64:
"""
:return: The absolute difference between the means of the first and the second halves of a
given univariate time series.
"""
mid = int(len(uni_ts) / 2)
return np.abs(get_mean(... | 5e7e709afffde843f3f1be7941c620d4f248e8b4 | 3,654,031 |
def user_collection():
"""
用户的收藏页面
1. 获取参数
- 当前页
2. 返回数据
- 当前页
- 总页数
- 每页的数据
:return:
"""
user = g.user
if not user:
return "请先登录"
# 获取当前页
page = request.args.get('p', 1)
page_show = constants.USER_COLLECTION_MAX_NEWS
# 校验参数
t... | d5ad3a3121dfc169952cad514b3fa930662dd2af | 3,654,032 |
def activity(*, domain, name, version):
"""Decorator that registers a function to `ACTIVITY_FUNCTIONS`
"""
def function_wrapper(func):
identifier = '{}:{}:{}'.format(name, version, domain)
ACTIVITY_FUNCTIONS[identifier] = func
return function_wrapper | 1529c19b8d1d5be02c45e87a446abf62aafc143a | 3,654,033 |
def OEDParser(soup, key):
""" The parser of Oxford Learner's Dictionary. """
rep = DicResult(key)
rep.defs = parseDefs(soup)
rep.examples = parseExample(soup)
return rep | 21b4670047e06f1251e70e09aed5da4dba0449ec | 3,654,034 |
def X_SIDE_GAP_THREE_METHODS(data):
"""
Upside/Downside Gap Three Methods
:param pd.DataFrame data: pandas DataFrame with open, high, low, close data
:return pd.Series: with indicator data calculation results
"""
fn = Function('CDLXSIDEGAP3METHODS')
return fn(data) | 87d3ca966d13756c3cd2bf15647a4d696f1e1f02 | 3,654,035 |
def fix_legacy_database_uri(uri):
""" Fixes legacy Database uris, like postgres:// which is provided by Heroku but no longer supported by SqlAlchemy """
if uri.startswith('postgres://'):
uri = uri.replace('postgres://', 'postgresql://', 1)
return uri | aa3aa20110b7575abf77534d08a35dccb04b731d | 3,654,036 |
def create_need():
"""
Créé le besoin en db
:return:
"""
student = Student.query.filter_by(id_user=session['uid']).first()
title = request.form.get('title')
description = request.form.get('description')
speaker_id = request.form.get('speaker_id')
estimated_tokens = int(request.form.... | d8af541668818e1ed40382b4ed457ac819ab3ce6 | 3,654,037 |
def insert_rolling_mean_columns(data, column_list, window):
"""This function selects the columns of a dataframe
according to a provided list of strings, re-scales its
values and inserts a new column in the dataframe with the
rolling mean of each variable in the column list and the
provided window le... | fd37ca307aaa0d755cd59aa69320003d02cb677a | 3,654,038 |
def get_url_names():
""" Получение ссылок на контент
Returns:
Здесь - список файлов формата *.str
"""
files = ['srts/Iron Man02x26.srt', 'srts/Iron1and8.srt']
return files | 4ee8fdd5ab9efc04eda4bfe1205e073064030520 | 3,654,039 |
from datetime import datetime
def unix_utc_now() -> int:
"""
Return the number of seconds passed from January 1, 1970 UTC.
"""
delta = datetime.utcnow() - datetime(1970, 1, 1)
return int(delta.total_seconds()) | b9768b60cf6f49a7cccedd88482d7a2b21cf05a2 | 3,654,040 |
from typing import Set
def _preload_specific_vars(env_keys: Set[str]) -> Store:
"""Preloads env vars from environ in the given set."""
specified = {}
for env_name, env_value in environ.items():
if env_name not in env_keys:
# Skip vars that have not been requested.
continue... | 6eb6c09f56235b024f15749d8ec65e8801991b43 | 3,654,041 |
import re
def _format_workflow_id(id):
"""
Add workflow prefix to and quote a tool ID.
Args:
id (str): ...
"""
id = urlparse.unquote(id)
if not re.search('^#workflow', id):
return urlparse.quote_plus('#workflow/{}'.format(id))
else:
return urlparse.quote_plus(id) | ea6b6f83ef430128c8a876c9758ce3d70b1bef63 | 3,654,042 |
def calc_log_sum(Vals, sigma):
"""
Returns the optimal value given the choice specific value functions Vals.
Parameters
----------
Vals : [numpy.array]
A numpy.array that holds choice specific values at common grid points.
sigma : float
A number that controls the variance of the ... | 18f71725ea4ced0ea5243fb201f25ae636547947 | 3,654,043 |
def comment_create(request, post_pk):
"""記事へのコメント作成"""
post = get_object_or_404(Post, pk=post_pk)
form = CommentForm(request.POST or None)
if request.method == 'POST':
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('blog:post_detail'... | fe6357cfcff1a522064ad9f49b030cf63a02b575 | 3,654,044 |
import torch
def tensor_from_var_2d_list(target, padding=0.0, max_len=None, requires_grad=True):
"""Convert a variable 2 level nested list to a tensor.
e.g. target = [[1, 2, 3], [4, 5, 6, 7, 8]]
"""
max_len_calc = max([len(batch) for batch in target])
if max_len == None:
max_len = max_len_... | 2aa5fcc5b2be683c64026126da55330937cd8242 | 3,654,045 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.