content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_date(date_str: str) -> date:
"""Just a wrapper to avoid having to declare dateutil as a dependency in other projects."""
return dateutil_parser(date_str).date() | 5,308,700 |
def dagger(x: torch.Tensor) -> torch.Tensor:
"""Conjugate transpose of a batch of matrices. Matrix dimensions are
assumed to be the final two, with all preceding dimensions batched over."""
return x.conj().transpose(-2, -1) | 5,308,701 |
def node_factory(edge_model, children_null=True, base_model=models.Model):
"""
Dag Node factory
"""
class Node(base_model, NodeBase):
class Meta:
abstract = True
children = models.ManyToManyField(
"self",
blank=children_null,
symmetrical=... | 5,308,702 |
def geometry_mask(
geometries,
out_shape,
transform,
all_touched=False,
invert=False):
"""Create a mask from shapes.
By default, mask is intended for use as a
numpy mask, where pixels that overlap shapes are False.
Parameters
----------
geometries : iter... | 5,308,703 |
def detection_area(self):
"""
Checks the area to have obstacles
:return: float
"""
image = ImageGrab.grab(self.area)
gray_img = ImageOps.grayscale(image)
arr = np.array(gray_img.getcolors())
# print(arr.mean())
return arr.mean() | 5,308,704 |
def _get_data_by_filename(fname: str) -> Path:
"""
Download file or used cached version.
Args:
fname (str): name of file to download
Returns:
Path: path at which file lives
"""
full_fname = DATA_PATH.joinpath(fname)
# check if file exists - download if necessary
if not... | 5,308,705 |
def build_input(data_path, batch_size, size, mode):
"""Build image and targets.
Args:
data_path: Filename for data.
batch_size: Input batch size.
mode: Either 'train' or 'eval'.
Returns:
volumes: Batches of volumes. [batch_size, volume_size, volume_size, volume_size]
targets: Batches of targe... | 5,308,706 |
def _get_publication(paper_entry: dict) -> Publication:
"""
Using a paper entry provided, this method builds a publication instance
Parameters
----------
paper_entry : dict
A paper entry retrieved from arXiv API
Returns
-------
Publication, or None
A publication instanc... | 5,308,707 |
def get_table_13():
"""表 13 玄関ポーチに設置された照明設備の人感センサーによる補正係数
Args:
Returns:
list: 表 13 玄関ポーチに設置された照明設備の人感センサーによる補正係数
"""
table_13 = (0.9, 1.0)
return table_13 | 5,308,708 |
def Parse(text: str) -> ParsedUniversalDependencies:
"""Parses the provided text."""
doc = nlp(text)
return __parse_tokens(doc) | 5,308,709 |
def Log_GetTimestamp(*args):
"""Log_GetTimestamp() -> wxChar"""
return _misc_.Log_GetTimestamp(*args) | 5,308,710 |
def get_seismic1d_eign_matrix(mu, density):#TODO!!
""" Retrun matrix of eigenvectors"""
c_p = np.sqrt(mu/density)
return np.array([[1/c_p, 1/c_p], [1, 1]]) | 5,308,711 |
def computer_move(state) -> bool:
"""
Method to decide which movements
"""
sorted_movements = sorted(explore_leaves(state), key=lambda x: x[0], reverse=state.board.turn)
if len(sorted_movements) == 0:
logger.debug('No moves to make: GAME OVER?')
return True
_log_moves(sorted_mov... | 5,308,712 |
def find_left_anchor_index(fragment_info, fragments):
"""
Description:
Use the fragment information to find which fragment is the left anchor
:param fragment_info: [list[dict]] the list of fragment information
:param fragments: [list] the list of fragments being searched
:return: left_anchor_ind... | 5,308,713 |
def get_all_preconditions(action_set):
"""
Returns a set of all preconditions for the actions in the given set
"""
all_precons = set()
for a in action_set:
all_precons.update(a.precondition)
return all_precons | 5,308,714 |
def confusionmatrix(tt, tp, gn=['', '', ''], plot=False, title='',
cmm='Blues', fontsize=20, ylabel='True', xlabel='Prediction'):
"""
Calculates and/or plots the confusion matrix for machine learning algorithm
results.
:type tt: list[float]
:param tt: Real targets.
:type t... | 5,308,715 |
def _to_string(*args: Object) -> Object:
"""Convert an integer to a string"""
if len(args) != 1:
return Error("It must recieve one parameter")
number: Object = args[0]
if not isinstance(number, Integer):
return Error("It must be an integer")
return String(str(number.value)) | 5,308,716 |
def compose_conformers(*conformers: Optional[Conformer]) -> Optional[Conformer]:
"""
Return a single conformer which is the composition of the input conformers.
If a single conformer is given, return the conformer.
"""
conformers = tuple(filter(None, conformers))
if not conformers:
re... | 5,308,717 |
def model_fn_builder(config: Configs, tasks,
num_train_steps, pretraining_config=None):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params):
"""The `model_fn` for TPUEstimator."""
log("Building model...")
is_training = (mode == tf.... | 5,308,718 |
async def _(session: CommandSession):
"""
real run the cmd after deal approval and scheduler
"""
data = await CallbackHandler(session).normalize(session.ctx.get('payload'))
if not data:
return
await real_run(*data.values(), session.bot.config.ID) | 5,308,719 |
def get_ul_inds(udeg, ls):
"""
"""
# Turn `ls` into a slice
if isinstance(ls, integers):
ls = slice(ls, ls + 1)
if isinstance(ls, slice):
# List of indices user is accessing
inds = []
# Fill in the `None`s
if ls.start is None:
ls = slice(0, ls... | 5,308,720 |
def f_line(x, m, b):
"""
Line fit with equation y = mx + b
Parameters
----------
x : array
x values
m : float
slope
b : float
y-intercept
Returns
-------
y : array
y values
"""
y = m*x + b
return y | 5,308,721 |
def extractLostInTranslation(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Third Prince Elmer' in item['tags']:
return buildReleaseMessageWithType(item, 'Third Prince Elmer', vol, chp, frag=fr... | 5,308,722 |
def determinize(perspective: cs.Perspective, mode=0) -> GameState:
"""Determinize the given perspective into a deterministic state.
The mode parameter determines the way in which determinization happens.
"""
if mode == 0:
is_declarer = perspective.player == perspective.declarer
played_... | 5,308,723 |
def parse_value(file, section, key):
""" Read ini file and returns unique value
:param file: File to be parsed
:type file: str
:param section: Section targeted
:type section: str
:param key: Parameter to be read
:type key: str
:return: Read value
:rtype: str
"""
config = Con... | 5,308,724 |
def demo_JmE(X, Y, DPiters=1000):
"""
Explore the posterior of our model.
"""
""" Create expert shell """
expert = MixtureOfExperts.experts.IndpendentRBF(input_dim=X.shape[1], output_dim=Y.shape[1],
process_mean='Constant', ard=True)
expert._p... | 5,308,725 |
def magazineluiza_parser(html):
"""
Parser for magazineluiza.com.br.
There's an attribute with a JSON containing all the info we need when
the item is available. When it isn't, we must retrieve the info from
another JSON, one much less complete (without best price).
"""
item = {}
# Cr... | 5,308,726 |
def getDistance(sensor):
"""
Return the distance of an obstacle for a sensor.
The value returned by the getValue() method of the distance sensors
corresponds to a physical value (here we have a sonar, so it is the
strength of the sonar ray). This function makes a conversion to a
distance value ... | 5,308,727 |
def sjoin(
left_df,
right_df,
how="inner",
predicate="intersects",
lsuffix="left",
rsuffix="right",
**kwargs,
):
"""Spatial join of two GeoDataFrames.
See the User Guide page :doc:`../../user_guide/mergingdata` for details.
Parameters
----------
left_df, right_df : Geo... | 5,308,728 |
def compute_BtBinv(B, C):
"""Create block inverses.
Helper function that creates inv(B_i.T B_i) for each block row i in C,
where B_i is B restricted to the sparsity pattern of block row i.
Parameters
----------
B : {array}
(M,k) array, typically near-nullspace modes for coarse grid, i.... | 5,308,729 |
def fixed_onepoint(p_0, p_1):
"""
Given two individuals, create two children using one-point crossover and
return them. The same point is selected on both genomes for crossover
to occur. Crossover points are selected within the used portion of the
genome by default (i.e. crossover does not occu... | 5,308,730 |
def get_pipeline_ids(db_name='./grades.sqlite3'):
"""
:param db_name:
:return:
"""
with lite.connect(db_name) as con:
cur = con.cursor()
result = cur.execute("SELECT pipeline_id FROM students")
try:
resut = (ids[0] for ids in result.fetchall())
except Exc... | 5,308,731 |
def iterchilds(travtree, parentcoord):
"""generator that yields all childs of a parent with given coordinats
for use in :func:`iternodes`
"""
for n in list(filter(coord_pattern_child(parentcoord), travtree.values())):
yield n
yield from iterchilds(travtree, n['coords']) | 5,308,732 |
def update_individual_metadata(ts):
"""Update individual metadata in ts object.
Returns new list of individuals with updated metadata
"""
individuals = []
oldname = None
i = 0
for ind in ts.individuals():
popindex = ts.nodes()[ind.nodes[0]].population
popname = ts.population... | 5,308,733 |
def get_trt_logger():
"""
Get the global TensorRT logger created by Polygraphy.
Returns:
trt.Logger: The TensorRT logger.
"""
global TRT_LOGGER
if TRT_LOGGER is None:
TRT_LOGGER = trt.Logger()
return TRT_LOGGER | 5,308,734 |
def _convert_rx101_to_mobile(
model_path: str,
num_classes: int,
output_path: str or Path = "./rx101_optimized_scripted1.ptl",
):
"""Function handling conversion of MSCG-Net Rx101 Models
:param model_path:
:param num_classes:
:param output_path:
:return:
"""
# PATH='/content/dri... | 5,308,735 |
def unify_index_info_couch_dates_fmt(index_info):
"""Applies standardization to secondary keys 'date' type keys.
@param index_info: is a index data to workout for
"""
clean_info = {}
index_keys = [key for key in index_info.iterkeys()]
for index_key in index_keys:
if not index_key == 'da... | 5,308,736 |
def stellar_dist(row: pd.Series, push: float) -> pd.Series:
"""Calculate the fluxes for the stellar objects at a given distance.
For use with pandas.DataFrame.apply(). Requires the columns:
- 'distance'
- 'radio'
- 'optical_in_mJy'
Args:
row: The pd.Series object containing... | 5,308,737 |
def mysql_config_path():
"""
根据平台查询mysql配置文件
:return:
"""
_platform = platform.system()
print('当前平台为:{}'.format(_platform))
mysql_config = None
if _platform == 'Darwin':
mysql_config = "/Users/yuxiang/Documents/Developer/WeChat/baixiaotu-mini/sqlconfig.json"
elif _platform ==... | 5,308,738 |
def calculate_case_distances(
graph: nx.DiGraph, case: Case, *, additional_attributes: "list[str]" = []
) -> "dict[str, float]":
"""
Extracts the distances between the current graph and a given case across trace,
time, and the additional attributes provided.
Arguments:
graph: nx.DiGraph
... | 5,308,739 |
def index_to_position(index, nelx, nely):
"""
Convert the index of a element to the centroid of the element
"""
return numpy.array([(index % nelx)+.5, index/nelx+.5]) | 5,308,740 |
def imdb(inp, api_key=None):
""".imdb <movie> -- gets information about <movie> from IMDb"""
if not api_key:
return None
content = http.get_json("https://www.omdbapi.com/", t=inp, apikey=api_key)
if content["Response"] == "Movie Not Found":
return "movie not found"
elif content["R... | 5,308,741 |
def get_api_key(api_file):
""" Return an API key from the user's home directory """
with open('{_home}/.{_api_file}'.format(_home = os.path.expanduser('~'),
_api_file = api_file)) as f:
return f.read().replace('\n', '') | 5,308,742 |
def smooth(sig, window_size):
"""
Apply a uniform moving average filter to a signal.
Parameters
----------
sig : ndarray
The signal to smooth.
window_size : int
The width of the moving average filter.
Returns
-------
ndarray
The convolved input signal with the... | 5,308,743 |
def filter_by_oid_alt(instructions, oid):
""" For a given list of instructions and an Order ID,
return the list of instructions that reference that Order ID.
:param instructions: list of instructions
:type instructions: list or tuple
:param oid: Order ID
:type oid: int
:return: list of inst... | 5,308,744 |
def get_sequence_lineage(request, upi):
"""
Internal API.
Get the lineage for an RNA sequence based on the
classifications from all database cross-references.
"""
try:
queryset = Xref.objects.filter(upi=upi).select_related('accession')
results = queryset.filter(deleted='N')
... | 5,308,745 |
def consensus_binned(gdir):
"""Bin consensus ice thickness ice estimates.
Updates the 'inversion_flowlines' save file.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
"""
flowlines = gdir.read_pickle('inversion_flowlines')
fl = flo... | 5,308,746 |
def get_function_fb_graph():
"""Get call - facebook."""
return requests.get('http://graph.facebook.com') | 5,308,747 |
def mat_to_pose_wxyz(mat):
"""Convert matrix to pos and wxyz quaternion."""
p = mat[:3, 3].tolist()
p += tra.quaternion_from_matrix(mat).tolist()
return np.array(p) | 5,308,748 |
def setDefaultCompressionCodecName(compressionCodecName):
"""
:param compressionCodecName: java.lang.String
"""
return _java_type_.setDefaultCompressionCodecName(compressionCodecName) | 5,308,749 |
def plot_ece(lrs, y, log_prior_odds_range=None, ax=plt):
"""
Generates an ECE plot for a set of LRs and corresponding ground-truth
labels.
The x-axis indicates the log prior odds of a sample being drawn from class
1; the y-axis shows the entropy for (1) a non-informative system (dotted
line), (... | 5,308,750 |
def do_ajax_update_no_effect(parser, token):
"""
Updates a target div by binding a onclick event to a link which uses jquery.metadata to parse for the target div and data source url
"""
try:
args_list = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "... | 5,308,751 |
def standardize_rows(M):
""" Distribute the rows of the cost matrix normally to allow for accurate comparisons of error and description
cost. """
rv = np.matrix(M)
for i in range(rv.shape[0]):
mean = np.mean(M[i, :])
stdev = np.std(M[i, :])
rv[i, :]= (M[i, :]- mean)/stdev
ret... | 5,308,752 |
def refine_group_join_event_msg(ctx: EventMsg) -> _GroupJoinEventMsg:
"""某人进群事件"""
if not isinstance(ctx, EventMsg):
raise ContextTypeError('Expected `EventMsg`, but got `%s`' % ctx.__class__)
if ctx.EventName == EventNames.ON_EVENT_GROUP_JOIN:
return _GroupJoinEventMsg(ctx)
return None | 5,308,753 |
def test_upsert_content_sync_state_update(settings):
""" Verify that upsert_content_sync_state updates a ContentSyncState record for the content """
settings.CONTENT_SYNC_BACKEND = "content_sync.backends.SampleBackend"
content = WebsiteContentFactory.create(markdown="abc")
abc_checksum = content.calcula... | 5,308,754 |
def init(dataset_name):
"""
Initialize a new dataset at the current dir.
Then run the upload command to copy all the files in this
directory to FloydHub.
floyd data upload
"""
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
namespace, name = get... | 5,308,755 |
def parse_dlna(dlna_server):
"""
Return a dict of title: url from dlna
"""
res = [
s
for s in upnpclient.Device("http://{}/rootDesc.xml".format(dlna_server)).services
if s.name == "ContentDirectory"
][0].Browse(
ObjectID="2$8",
BrowseFlag="BrowseDirectChildren... | 5,308,756 |
def pretty_choices(index, role_name, account_id):
"""
Formats the output of the account option
:return: formatted print
"""
account_alias = identify_known_accounts(account_id)
if account_alias:
print(" %s | %s (Account: %s - %s)" % (index, role_name, account_id, account_alias))
else:... | 5,308,757 |
def sax_optimization(locator, data, time_series_len, BOUND_LOW, BOUND_UP, NGEN, MU, CXPB, start_gen, building_name):
"""
A multi-objective problem set for three objectives to maximize using the DEAP library and NSGAII algorithm:
1. Compound function of accurracy, complexity and compression based on the work... | 5,308,758 |
def split(
string: str, delimiter: str = " ", quote: str = '"', escaped_quote: str = r"\""
) -> Iterator[str]:
"""
A split function that is aware of quotes and parentheses.
:param string: string to split
:param delimiter: string defining where to split, usually a comma or space
:param quote: st... | 5,308,759 |
def test_state_gen_and_count():
"""Test generation of binary states using bin_states() and xbin_states()."""
assert np.array_equal( bin_states(5), np.vstack([i for i in xbin_states(5)]) )
states = bin_states(5)
p, s = state_probs(states)
assert np.isclose(p, 1/32).all()
assert np.array_equal(s,... | 5,308,760 |
def test_get_steering_wheel_heat_on_init(monkeypatch):
"""Test get_steering_wheel_heat() after initialization."""
_mock = TeslaMock(monkeypatch)
_controller = Controller(None)
_data = _mock.data_request_vehicle()
_wheel = HeatedSteeringWheelSwitch(_data, _controller)
assert _wheel is not None... | 5,308,761 |
def randomize_and_play_circuit(n_gates: int, init_state: str = "z"):
"""
:param n_gates: the depth of the circuit
:param init_state: starting position on the bloch sphere
:return:
"""
state = init_state
for ind in range(n_gates):
state = play_clifford(cliffords[np.random.ra... | 5,308,762 |
def pair(dice):
"""Score the given roll in the 'Pair' category"""
counts = dice_counts(dice)
for i in [6, 5, 4, 3, 2, 1]:
if counts[i] >= 2:
return 2*i
return 0 | 5,308,763 |
def get_data_for_fit(expt, mask):
"""
exlucdes pre-bleach frame (T[0]) from the array
Parameters
----------
data: aicsimageio.aics_image.AICSImage
mask: np.ndarray
Returns
-------
data_for_fit: np.ndarray
"""
norm_inside = _norm_extract(expt, mask)
data_for_fit = norm_... | 5,308,764 |
def renumerate_article_sortorder(apps, schema_editor):
""" Renumerate articles for consistent and guaranteed unique sortorder. """
Message = apps.get_model('newsletter', 'Message')
for message in Message.objects.all():
for index, article in enumerate(message.articles.all()):
# We're us... | 5,308,765 |
def gen_docker_image_reference():
"""Generating a docker image reference including image ID.
returns the docker image reference and image ID"""
image_id = 'sha256:some-long-fake-id-with-numbers-{}'
docker_image_refrence = 'this.is.some.fake.{}/registry:{}@{}'.format(
fauxfactory.gen_alpha().lowe... | 5,308,766 |
def add_anomaly_data(egg_data: pd.DataFrame) -> pd.DataFrame:
"""
Given a dataframe of egg data, add a column for each anomaly metric, and populate it with the
results of running the breakpoint analysis on each row
Args:
egg_data (pd.DataFrame): the dataframe containing the egg temperature data
... | 5,308,767 |
def set_wm_strut_partial(window, left, right, top, bottom, left_start_y,
left_end_y, right_start_y, right_end_y, top_start_x,
top_end_x, bottom_start_x, bottom_end_x):
"""
Sets the partial struts for a window.
:param window: A window identifier.
... | 5,308,768 |
def get_connection(database_name: str):
"""Hakee yhteyden tietokantaan ja palauttaa sen.
"""
return connection | 5,308,769 |
def logmsgbox(loglevel='info',title='',msg=''):
"""Log an info/warn/error message, while also showing it in a message box.
Parameters:
-----------
loglevel : str
One of 'info' (default), 'warn', 'error', i.e. log levels from
the logging module. The levels are mapped to the tkinter
... | 5,308,770 |
def generate_graph_seq2seq_io_data(
df, x_offsets, y_offsets, add_time_in_day=True, add_day_in_week=False, scaler=None
):
"""
Generate samples from
:param df:
:param x_offsets:
:param y_offsets:
:param add_time_in_day:
:param add_day_in_week:
:param scaler:
:return... | 5,308,771 |
def execute(cmd, stderr_to_stdout=False, stdin=None, cwd=None):
"""Execute a command in the shell and return a tuple (rc, stdout, stderr)"""
if stderr_to_stdout:
stderr = STDOUT
else:
stderr = PIPE
p = Popen(cmd, shell=False, bufsize=0, close_fds=True, stdin=stdin, stdout=PIPE, stderr=s... | 5,308,772 |
def get_random_number_with_zero(min_num: int, max_num: int) -> str:
"""
Get a random number in range min_num - max_num of len max_num (padded with 0).
@param min_num: the lowest number of the range in which the number should be generated
@param max_num: the highest number of the range in which the numb... | 5,308,773 |
def cluster_props(all_props: List[CollisionProp]) -> dict:
""" Many provided properties are overlapping -- some subsumes some others, cluster them for later usage.
:return: a dict of central points -> sorted props in decreasing order of their epsilons
"""
d = defaultdict(list) # base point -> List of p... | 5,308,774 |
def COMMETHOD(idlflags, restype, methodname, *argspec):
"""Specifies a COM method slot with idlflags.
XXX should explain the sematics of the arguments.
"""
paramflags = []
argtypes = []
# collect all helpstring instances
# We should suppress docstrings when Python is started with -OO
h... | 5,308,775 |
def _validate_rpc_ip(rpc_server_ip):
"""Validates given ip for use as rpc host bind address.
"""
if not is_valid_ipv4(rpc_server_ip):
raise NetworkControllerError(desc='Invalid rpc ip address.')
return rpc_server_ip | 5,308,776 |
def deploy(ctx):
"""Deploy the project to pypi"""
print('Deploying to Pypi!')
ctx.run('python setup.py sdist bdist_wheel --universal')
ctx.run('twine upload dist/*') | 5,308,777 |
def normalize_data(df):
"""Normalizes a dataframe."""
scaler=MinMaxScaler()
df[FEATURE_NAMES] = scaler.fit_transform(df[FEATURE_NAMES])
return df | 5,308,778 |
def hex_to_root(hex_string: str) -> Root:
"""
Convert hex string to trie root.
Parameters
----------
hex_string :
The hexadecimal string to be converted to trie root.
Returns
-------
root : `Root`
Trie root obtained from the given hexadecimal string.
"""
return ... | 5,308,779 |
def setup(bot):
"""Add class as a cog"""
bot.add_cog(configurations(bot)) | 5,308,780 |
def redis_connection():
"""
Returns a redis connection from one of our pools.
"""
pool = ConnectionPoolManager.connection_pool(**CONNECTION_KWARGS)
return Redis(connection_pool=pool) | 5,308,781 |
def count_simple(a, alphabet_len):
"""Counts items in a. """
result = zeros(alphabet_len, Int)
for i in ravel(a):
result[i] += 1
return result | 5,308,782 |
def titanic(refresh=False):
"""
Usage: [arg1]:[refresh=False(default)/True - True if the file should be downloaded and refreshed again from intenet]
Type: Supervised - Classification
Name: Titanic
Target variable: Survived
Description: Sample Dataset
Returns: Pandas DataFrame
"""
if ... | 5,308,783 |
def log_launch_config(*, logger=logging.root):
"""Log logging configuration details relevant for a user with the given logger."""
if any(launch_config.file_handlers):
logger.info('All log files can be found below {}'.format(launch_config.log_dir))
logger.info('Default logging verbosity is set to {}'... | 5,308,784 |
def gen_acquisition_delta(interval):
"""Generate delta in days for an acquisition day since 1970-01-01.
Args:
interval: ISO8601 date range
Returns:
generator producing delta in days from 1970-01-01
Example:
gen_acquisition_delta('R90/P16D/2000-01-01')
"""
epoch = datet... | 5,308,785 |
def verify_error_db_redis(dut, table, **kwargs):
"""
Verify error db using redis cli
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param :dut:
:param :table:
:param :route:
:param :mask:
:param :ifname:
:param :nhp:
:param :operation:
:param :rc:
:param :result: ... | 5,308,786 |
def _select_manager(backend_name):
"""Select the proper LockManager based on the current backend used by Celery.
:raise NotImplementedError: If Celery is using an unsupported backend.
:param str backend_name: Class name of the current Celery backend. Usually value of
current_app.extensions['celery... | 5,308,787 |
def send_email(sender: str, password: str, recipients: list, body: str,
*attachments):
"""Send and email through a Microsoft Office 365 account.
Parameters
----------
sender : str
The email address sending the email
password : str
The email password
recipients : l... | 5,308,788 |
def ivim_model_selector(gtab, fit_method='LM', **kwargs):
"""
Selector function to switch between the 2-stage Levenberg-Marquardt based
NLLS fitting method (also containing the linear fit): `LM` and the Variable
Projections based fitting method: `VarPro`.
Parameters
----------
fit_method : ... | 5,308,789 |
def temperature():
"""
Raspberry Pi temperature
"""
return render_template("temperature.html") | 5,308,790 |
def convert_size_bytes_to_human_readable_format(size_bytes):
"""
Converts a size in bytes to a human readable format.
:param size_bytes: The size in bytes
:return: Bytes converted to readable format
"""
if size_bytes == 0:
return "0B"
size_name = ("B", "KiB", "MiB", "GiB", "TiB", "P... | 5,308,791 |
def activate(client, name, file_=None):
"""Activate a model view.
Args:
client (obj):
creopyson Client.
name (str):
View name.
`file_` (str, optional):
Model name. Defaults is current active model.
Returns:
None
"""
data = {"name... | 5,308,792 |
def delete_table(userId, id):
"""
Deletes a table from the db. Only can be called via the saved_search.html
"""
try:
savedSearch = SavedSearch.objects(id=id).first()
tableName = savedSearch.name
doDelete = True
message = tableName+" deleted successfully!"
if saved... | 5,308,793 |
def _get_heatmap(job_name, build_number, builds, group_field, count_skips, project=None):
"""Run the aggregation to get the Jenkins heatmap report"""
# Get the run IDs for the last 5 Jenkins builds
build_min = build_number - (builds - 1)
build_max = build_number + 1
build_range = [str(bnum) for bnum... | 5,308,794 |
def control_4_5_ensure_route_tables_are_least_access(regions):
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
offenders_links = []
control = "4.5"
description = "Ensure routing tables for VPC peering are least access"
scored = Fals... | 5,308,795 |
def _merge_splitter(first, index, second):
""" Merge one splitter into another at a given index.
"""
if first.orientation() != second.orientation():
first.insertWidget(index, second)
second.show()
else:
items = [second.widget(i) for i in xrange(second.count())]
for item ... | 5,308,796 |
def main():
"""\bAssignify is a tool for benchmarking assignment algorithms. With this tool
you can generate your own graphs (command: generate-graph) and run simulations
(command: simulate). Further information can be found with command_name --help.
"""
pass | 5,308,797 |
def kiv_pred(df: Kerneldict, lam: float, xi: float, stage: int) -> np.ndarray:
"""Kernel instrumental variable prediction."""
n = len(df["y1"])
m = len(df["y2"])
brac = make_psd(df["K_ZZ"]) + lam * np.eye(n)
W = np.linalg.solve(brac, df["K_XX"]).T @ df["K_Zz"]
brac2 = make_psd(W @ W.T) + m * xi * make_psd(... | 5,308,798 |
def reject_old_python_versions(minimum_version):
"""Guard against old python versions.
Args:
minimum_version: a tuple that indicates the minimum Python version.
"""
minimum_version_string = '.'.join(str(x) for x in minimum_version)
if not hasattr(sys, 'version_info'):
sys.stderr.write('Very old versi... | 5,308,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.