content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def continuous_setting(agents: List[Agent]) -> Allocation:
"""
Algorithm 3.
Approximation algorithm of the optimal auction for a continuous cake.
Complexity and approximation:
- Requires at most 2n2 values from each agent.
- Runs in time polynomial in n.
- Approximates the optimal welfare b... | 72,000 |
def test_functional_activate_twice_round_trip(filesystem):
"""
title: Cache replication.
description:
Restore cache operations from a replicated cache and make sure
second failover is possible to return to original configuration
pass_criteria:
- A cache exported object appears after s... | 72,001 |
def plot_on_sphere(xyz_data, normalize=False):
"""
plots each row of an nx3 numpy array on the surface of a sphere
to do this we first normalize each row
"""
#make 3d figure
fig = plt.figure()
ax = plt.axes(projection='3d')
#build up a sphere
u, v = np.mgrid[0:2*np.pi:200j, 0:np... | 72,002 |
def test_atomic_unsigned_byte_min_exclusive_3_nistxml_sv_iv_atomic_unsigned_byte_min_exclusive_4_5(mode, save_output, output_format):
"""
Type atomic/unsignedByte is restricted by facet minExclusive with
value 145.
"""
assert_bindings(
schema="nistData/atomic/unsignedByte/Schema+Instance/NIS... | 72,003 |
def hybrid(n_geracoes, graph):
"""
:param n_geracoes: igual a numero de vertices no grapho
:param graph: tuple dos dois mapas retirados de read file
:return:
O Algoritmo hibrido e exactamente igual ao genetico, no entanto, introduz a solucao optima
conseguida pela pesquisa local na populacao in... | 72,004 |
def get_flatten_name(fea):
""" Get names of feature after flatten.
Parameters
----------
fea: list or str
return value of get_itervar_feature or a line of logfile
Returns
-------
feature_names: Array of str
"""
feature_name = {
"_attr_": ["length", "nest_level", "t... | 72,005 |
def main(config_path):
"""
Train and evaluate a 2D UNet on the public ICH dataset using the parameters sepcified on the JSON at the
config_path. The evaluation is performed by k-fold cross-validation.
"""
# load config file
cfg = Config(settings=None)
cfg.load_config(config_path)
# Make... | 72,006 |
def change_style(style, representer):
"""
Change the style of a particular YAML representer.
"""
def new_representer(dumper, data):
scalar = representer(dumper, data)
scalar.style = style
return scalar
return new_representer | 72,007 |
def move_piece(board, player, piece, initial, final, jumpFlag=False, jumpPosition = None):
"""
Moves a piece on the board and modifies the cell values as required.
"""
assert ((jumpFlag) and (jumpPosition != None)) or ((not jumpFlag) and (jumpPosition == None)), "Jump position not passed but jump fl... | 72,008 |
def sponge(N:bytearray, d:int):
"""
Sponge construction for hash functions.
N: Thing to hash \n
d: size of hash wanted \n
return bytearray
"""
def pad(N, r):
iN = bm.bytes_to_int(N)
lN = int.bit_length(iN)
# Number of 0 to add
b = (r - ((lN + 3) % r)) % r
... | 72,009 |
def test_CD_diagram_wrong_input_boolean():
"""
Testing the CD_diagram function with the wrong dataframe input (boolean)
"""
with pytest.raises(AttributeError):
cd_diagram = saveCD(True) | 72,010 |
def track_event(tracking_id, category, action, uid=None, label=None, value=0,
software_version=None, timeout=2, thread=True):
"""
Record an event with Google Analytics
Parameters
----------
tracking_id : str
Google Analytics tracking ID.
category : str
Event cate... | 72,011 |
def get_expected_calls(mocker: MockerFixture, file_name: str) -> List:
"""List of the first 20 expected open calls for the write_nexus_corp method with default args."""
expected_calls = [
mocker.call(file_name, 'w'),
mocker.call().__enter__(),
mocker.call().write('! Nexus corner point da... | 72,012 |
def scanD(d, ck, minSupport):
"""
计算候选数据集CK在数据集D中的支持度,
并返回支持度大于最小支持度 minSupport 的数据
Args:
D 数据集
Ck 候选项集列表
minSupport 最小支持度
Returns:
retList 支持度大于 minSupport 的集合
supportData 候选项集支持度数据
"""
# ssCnt 临时存放选数据集 Ck 的频率. 例如: a->10, b->5, c->8
ssCnt = {... | 72,013 |
def accountNames():
""" invert the accountfields list so we can use it to look up user input. """
return dict(
itertools.chain.from_iterable(
((alias.lower(), k.lower()) for alias in aliases)
for k, aliases in accountFields.items()
)
) | 72,014 |
def _readfile(fname, strip="\n"):
"""Shortcut for reading a text file."""
with codecs.open(fname, 'r', 'UTF8') as fp:
content = fp.read()
return content.strip(strip) if strip else content | 72,015 |
def part1and2(data):
"""
>>> part1and2(read_input())
(266, 19242)
"""
grid = defaultdict(int)
length = defaultdict(int)
for wire in data:
wire_grid = process_instructions(wire)
for location in wire_grid:
grid[location] += 1
length[location] += wire_... | 72,016 |
def create_operon_figure(operon: Operon,
plot_ignored: bool,
feature_colors: Optional[dict] = {},
bounds: Optional[Tuple[int, int]] = None,
existing_ax: Optional[Axes] = None,
color_by_blast_stat... | 72,017 |
def functions_str(graph, examples: bool = True, add_count: bool = True, **kwargs) -> str:
"""Make a summary string of the functions in the graph."""
df = function_table_df(graph, examples=examples)
headers = list(df.columns)
if add_count:
headers[0] += ' ({})'.format(len(df.index))
return ta... | 72,018 |
def duffing(n_points: int = 10**6, x_0: float = 0.1, y_0: float = 0.1, a: float = 2.75, b: float = 0.15) -> PlotData:
"""
Calculates a list of (x, y) points according to the Duffing Map
https://en.wikipedia.org/wiki/Duffing_map
:param n_points: The number of (x, y) plot points to calculate
:param x_... | 72,019 |
def smartDequeue(segment, readOnlyQueue=False, verbose=False):
""" This function is called after downloading the first segment of every nzbFile
It determines whether or not the segment's parent nzbFile is part of a par archive. If
it is and is also an 'extra' par file ('extra' pars are pars other than the ... | 72,020 |
def _sliding_attacks(square, occupied, deltas, limit=_default_limit):
"""
计算棋子的攻击范围
:param square:
:param occupied:
:param deltas:
:param limit:
:return:
"""
attacks = 0
for delta in deltas:
sq = square
while True:
sq += delta
if not limit(... | 72,021 |
def other_object_webhook_handler(event, event_data, event_type, event_subtype):
"""Handle updates to transfer, charge, invoice, invoiceitem and plan objects.
Docs for:
- charge: https://stripe.com/docs/api#charges
- coupon: https://stripe.com/docs/api#coupons
- invoice: https://stripe.com/docs/api#... | 72,022 |
def get_github_repo_url():
"""
Build URL to github repo
"""
return 'git://github.com/%s/%s.git' % (MOZILLA_GITHUB_ACCOUNT, DEEPSPEECH_GITHUB_PROJ) | 72,023 |
def vnpy_opt_DAY_IN_2(opt):
"""
vnpy 优化结果清洗, 针对 DAY_IN_2
:param opt:
:return:
"""
data = re.compile(r'DAY_IN_2\':\s(\d+)\}"\]:\s([\d\.]+)').findall(opt)
data = np.array(data).T
dic = {
"DAY_IN_2": pd.Series(data[0], dtype=np.int),
"capital": pd.Series(data[1], dtype=np.fl... | 72,024 |
def check_stages(start_from, stages):
""" Trigger stages rerun """
# nothing to do if no stage passed on cmd line
if not start_from:
return
def tryint(i):
# we usually expect int, can be also single char like 'a' or 'b'
try:
return int(i)
except ValueError:
... | 72,025 |
def get_request(url: str) -> HTMLResponse:
"""Makes a http requests to the server.
:param url: The url to send the get requests.
returns: The html response from the server.
"""
session = HTMLSession()
return session.get(url) | 72,026 |
def sync_detailed(
*,
client: AuthenticatedClient,
json_body: SearchEventIn,
) -> Response[Union[ErrorResponse, SearchEventOut]]:
"""Search Event
Dado um Trecho, uma lista de Grupos que resultam da pesquisa
por esse Trecho e um price token, atualiza os preços dos Grupos e o token.
Contabil... | 72,027 |
def add(lhs, rhs):
"""Elementwise addition.
Parameters
----------
lhs : relay.Expr
The left hand side input data
rhs : relay.Expr
The right hand side input data
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.add(lhs, rhs) | 72,028 |
def guess(input_ch, answer, dash, count):
"""
this function checks whether the user guesses the answer.
"""
guess_word = ""
while True:
# check whether the alphabet user entered matches the answer
for i in range(len(answer)):
if answer[i] == input_ch:
gues... | 72,029 |
def view_url(context):
"""Last part of the url for viewing this context.
By default: for Images and Files, redirect to .../view
Code taken from CMFPlone/skins/plone_scripts/livesearch_reply.py
"""
portalProperties = getToolByName(context, 'portal_properties')
siteProperties = getattr(portalPro... | 72,030 |
def track_state_update(
self,
update_task: DatabaseTask,
session,
track_factory_txs,
block_number,
block_timestamp,
block_hash,
):
"""Return int representing number of Track model state changes found in transaction."""
num_total_changes = 0
# This stores the track_ids created or... | 72,031 |
def ignore(x):
"""Method to indicate bypassing property validation"""
return x | 72,032 |
def main():
"""Main function for pyim-cis."""
args = parse_args()
args.command.run(args) | 72,033 |
def check_free_space(dest, required_space, msg):
""" Make sure the required space is available on destination, raising an IOError if there is not. """
free_space = psutil.disk_usage(dest).free
if free_space < required_space:
raise IOError(
errno.ENOSPC,
f'{msg} {free_space / ... | 72,034 |
def get_alembic_config(db_url: str) -> Config:
"""
Создает объект конфигурации alembic, чтобы программно вызывать команды
alembic
"""
cmd_options = SimpleNamespace(
config=os.path.join(MODULE_PATH, 'alembic.ini'),
db_url=db_url,
raiseerr=False,
rev_range=None,
... | 72,035 |
def _time_bb_splits(games):
"""
This function plots the time it takes for the spy to leave the CC after the most recent BB.
If the spy fails to leave after the BB (shot, timeout, etc.), then it is the time from BB to
game end.
If the spy BBs multiple times in the same convo without leaving, it wil... | 72,036 |
def alpha(freqs, cfc_mat, qfc_mat=None):
""" calculate alpha from expansion
"""
# Obtain the imaginary frequency and sort other freqs
ridxs = tuple(idx for idx, freq in enumerate(freqs) if freq < 0.0)
assert len(ridxs) == 1, ('Freqs should only have one imag')
ridx = ridxs[0]
freqs = tuple... | 72,037 |
def setldapconfig(addr, username, password, base) :
""" Configure les paramètres LDAP """
cfg = configparser.ConfigParser()
cfg.read(srv_path)
cfg.set('Ldap', 'ldap_address', addr)
cfg.set('Ldap', 'ldap_username', username)
cfg.set('Ldap', 'ldap_password', password.replace("%", "$percent"))
... | 72,038 |
def capture_with_stderr(command, cwd=None, env=None, timeout=0, pgrp=0):
"""Run a program in the background and capture its output.
stdout and stderr are captured independently.
:Parameters:
- `command`: The command to execute. If it is a string, it will be
parsed for command-line argum... | 72,039 |
def to_rad(pseudo_dms):
""" convert pseudo DMS string (DDD.MMSS) to radians """
w = pseudo_dms.split('.') # separate degree and MMSS
degree = int(w[0])
minute = int(w[1][:2])
second = int(w[1][2:])
return (degree + minute / 60 + second / 3600) / 180 * pi | 72,040 |
def test_render_operation_description_multiline(testrenderer, oas_fragment):
"""Operation's multiline 'description' is rendered."""
markup = textify(
testrenderer.render_operation(
"/evidences",
"post",
oas_fragment(
"""
description: |... | 72,041 |
def default_for_key(key, *args, **kwargs):
"""The :func:`default_for_key` decorator will register the given metric in the global metric dict
(`metrics.DEFAULT_METRICS`) so that it can be referenced by name in instances of :class:`.MetricList` such as in the
list given to the :class:`.torchbearer.Model`.
... | 72,042 |
def website_create(request):
"""
хендлер для запроса, создать сайт
создает и возвращает сайт, или ошибка
:param request:
:return:
"""
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
req = json_request(request)
name = req['name']
ip_address = req['ip... | 72,043 |
def httpserver(request):
"""The returned ``httpserver`` provides a threaded HTTP server instance
running on a randomly assigned port on localhost. It can be taught which
content (i.e. string) to serve with which response code and comes with
following attributes:
* ``code`` - HTTP response code (int... | 72,044 |
def test_valid_between_export(
factory,
date_ranges,
date_range,
sqlite_database: Runner,
):
"""Check that the exported date range columns contain the correct values."""
object = factory.create(
transaction__workbasket__status=WorkflowStatus.PUBLISHED,
valid_between=getattr(date_... | 72,045 |
def eval_request_bool(val, default=False):
"""
Evaluates the boolean value of a request parameter.
:param val: the value to check
:param default: bool to return by default
:return: Boolean
"""
assert isinstance(default, bool)
if val is not None:
val = val.lower()
if val... | 72,046 |
def _drop_constant_dims(ys):
"""Returns a view of the matrix `ys` with dropped constant rows."""
ys = np.asarray(ys)
if ys.ndim != 2:
raise ValueError("Expecting a matrix.")
variances = ys.var(axis=1)
active_mask = variances > 0.
return ys[active_mask, :] | 72,047 |
def test_join_users_group(app, session):
"""Test the public_users group membership for public users."""
# with app.app_context():
request = KeycloakScenario.create_user_request()
KEYCLOAK_SERVICE.add_user(request, return_if_exists=True)
user = KEYCLOAK_SERVICE.get_user_by_username(request.user_name)... | 72,048 |
def correlateToOBTmissionEpoch(pyUTCtime):
"""correlate the local time to OBT mission epoch time"""
return pyUTCtime - s_obtMissionEpochWithLeapSeconds | 72,049 |
def plot_poi_filtered_poi_coordinates(poi=None, poi_filtered=None):
"""Plot mean coordinates of all trajectories."""
china_geod = gpd.GeoDataFrame.from_file('.//plots//bou2_4p.shp',
encoding='gb18030')
plt.close("all")
fig, ax_objs = plt.subplots(1, 2, figsiz... | 72,050 |
def applicationNavigation(ctx, translator, navigation):
"""
Horizontal, primary-only navigation view.
For the navigation element currently being viewed, copies of the
I{selected-app-tab} and I{selected-tab-contents} patterns will be
loaded from the tag. For all other navigation elements, copies of... | 72,051 |
def update_notice():
"""
Update a row in notice table.
:return:
"""
error = None
# Initialize form
doc_change_notice_form = DocChangeNoticeForm(request.form, csrf_enabled=False)
doc_change_id = doc_change_notice_form.doc_change_id.data
# Get Users from DB
users = User.query.or... | 72,052 |
def by_priority(feedback):
"""
Converts a feedback into a numeric representation for sorting.
Args:
feedback (Feedback): The feedback object to convert
Returns:
float: A decimal number representing the feedback's relative priority.
"""
category = Feedback.CATEGORIES.UNKNOWN
... | 72,053 |
def get_feature_2(sentence: str, index: int) -> str:
"""Token to the right."""
tokens = tok(sentence)
return tokens[index + 1].lower() if index < len(tokens) - 1 else "" | 72,054 |
def split_by_gaps(vec,num_gaps = 1,index = None):
"""
Aggregates the indices of a vector based on gaps between index values.
The number of gaps is specified by num_gaps,
and the largest num_gaps gaps in the sorted array
are used to cluster values.
Arguments
---------
vec : A one-d... | 72,055 |
def is_hashable(obj):
"""Returns true if *obj* can be hashed"""
try:
hash(obj)
except TypeError:
return False
return True | 72,056 |
def add_ping_info(host_bundle, output):
"""
Sets the Ping log for each host to the most recent Ping output
author: Noah Lowry and Miles Stanley
:param host1: The first host involved in the ping test
:param host2: The second host involved in the ping test
:param output: The output of the ping tes... | 72,057 |
def _check_atomic_number(z:int) -> None:
"""
Checks if the atomic number provided is valid or not.
"""
if z <= 0:
raise InvalidAtomicNumber("Atomic number (Z) of an element cant be zero or less than zero.")
elif z > 118:
raise InvalidAtomicNumber("Atomic number (Z) of an element can... | 72,058 |
def checkout_confirm(request):
"""View for confirming the users order, if he confirms it saves
the order to the database and does all appropriate actions as well."""
order = get_order(request)
cart = request.session.get("cart")
# If the user has no order, no cart or has not chosen an
# address... | 72,059 |
def set_printoptions(precision=None, threshold=None, edgeitems=None,
linewidth=None, suppress=None,
nanstr=None, infstr=None,
formatter=None):
"""
Set printing options.
These options determine the way floating point numbers, arrays and
othe... | 72,060 |
def point_form(boxes):
""" Convert prior_boxes to (xmin, ymin, xmax, ymax)
representation for comparison to point form ground truth data.
Args:
boxes: (tensor) center-size default boxes from priorbox layers.
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
... | 72,061 |
def configure_app(app: Flask) -> None:
"""
The configuration is read from the filename in the "FLASK_SETTINGS_FILENAME"
environment variable (if it exists) and some other important settings
Additional settings such as SECRET_KEY and other settings should be added
accordingly.
:param Flask app:... | 72,062 |
def after_success(dry_run: bool = True) -> None:
"""
travis jobs to run in travis.yml section "after_success":
- coverage report
- codecov
- codeclimate report upload
Parameter
---------
cPREFIX
from environment, the command prefix like 'wine' or ''
cPIP
... | 72,063 |
def stim_data(elec, max_spk=1024):
"""
retrieve segment data containing stim waveforms
Args:
elec:
max_spk:
Returns:
tuple counts, events - count, the number of spikes
events - list of SegmentDataPacket classes
"""
c_spikes = _c.SegmentDataArray(max_spk)
eve... | 72,064 |
def is_valid(number, table=None):
"""Checks to see if the number provided passes the Damm algorithm."""
try:
return bool(validate(number), table=table)
except ValidationError:
return False | 72,065 |
def custom_policies(threescale, schema, request, testconfig):
"""Create custom policies"""
policies = []
params1 = {"name": "policy_registry", "version": "0.1", "schema": schema}
policy = threescale.policy_registry.create(params=params1)
policies.append(policy)
params2 = {"name": "policy_to_upd... | 72,066 |
def send_to_telegram(telegram_text, options):
""" Send custom message to telegram using bot_token."""
bot_token = options.telegramtoken
bot_chatID = options.telegramchatid
send_text = 'https://api.telegram.org/bot{}/sendMessage?chat_id={}&parse_mode=Markdown&text=```{}```'.format(
bot_token,
... | 72,067 |
def test_sorted_terms():
"""This tests that we can get the terms of a given topic using lambda
to calculate the relevance ranking. A common workflow is that once we
visualize the topics we modify the lambda slide and we are interested
in a particular lambda value, then with this function we can get the
... | 72,068 |
def dbscan(points, eps, minpts):
"""
Implementation of [DBSCAN]_ (*A density-based algorithm for discovering
clusters in large spatial databases with noise*). It accepts a list of
points (lat, lon) and returns the labels associated with the points.
References
----------
.. [DBSCAN] Ester, M... | 72,069 |
def inject_noise_in_upload(ctx):
"""Inject noise into weights before the client upload them to server
"""
for p in ctx.model.parameters():
noise = get_random("Normal", p.shape, {
"loc": 0,
"scale": ctx.nbafl_scale_u
}, p.device)
p.data += noise | 72,070 |
def line_search(f, x_k, g_k, p_k, ls_method='back_tracking', ls_params={'alf': 1, 'rho': 0.3, 'mu': 1e-4, 'iter_lim': 1000}):
"""
This function performs line search for an objective function "f" using pytorch
ie. at x_k, find an alf for which x_k + alf*p_k decreases the objective function
INPUTS:
... | 72,071 |
def plot_categorical_columns(df):
""" Univariate analysis of categorical columns
This function accepts the dataframe df which analyzes all the variable in the data and performs the univariate analysis using bar plot.
Keyword arguments:
df - Pandas dataframe which has the data.
... | 72,072 |
def run_latest_install(installer: str,
delete_installer: bool,
installer_downloaded: bool) -> None:
"""
If the install script is newer than this script (as determined by
the version number at the head of this script), run that newer
script instead.
:par... | 72,073 |
def analytical_leg_jacobian(leg_angles, sign):
"""
Computes the analytical Jacobian.
Args:
` leg_angles: a list of 3 numbers for current abduction, hip and knee angle.
sign: whether it's a left (1) or right(-1) leg.
"""
l_up = 0.2
l_low = 0.2
l_hip = HIP_COEFFICIENT* (-1)**(sign + 1)... | 72,074 |
def calibration_subset(calibratedfile, calibrationfile, lexnames, calibrationfile_subset,
includevar=True):
"""Generate a calibration file for a subset of lexica represented in the input data.
Take <calibratedfile>, containing standardized data (mean 0, std. dev. 1) for a set of named le... | 72,075 |
def create_widget(rig, bone_name, bone_transform_name=None):
""" Creates an empty widget object for a bone, and returns the object.
"""
obj_name = WGT_PREFIX + rig.name + '_' + bone_name
scene = bpy.context.scene
collection = ensure_widget_collection(bpy.context)
# Check if it already exists in... | 72,076 |
def make_context(asset_depth=0):
"""
Create a base-context for rendering views.
Includes app_config and JS/CSS includers.
`asset_depth` indicates how far into the url hierarchy
the assets are hosted. If 0, then they are at the root.
If 1 then at /foo/, etc.
"""
context = flatten_app_config()
context['ITEMS'] =... | 72,077 |
def process_categorical_data(df):
"""Splits categories and converts categories to numbers
Args:
df: Pandas DataFrame
Return
categories: Pandas DataFrame
"""
# create a dataframe of the 36 individual category columns
categories = df['categories'].str.split(pat = ';', expand = T... | 72,078 |
def mean_time_weekday_view(user_id):
"""
Returns mean presence time of given user grouped by weekday.
"""
data = get_data()
if user_id not in data:
log.debug('User %s not found!', user_id)
abort(404)
weekdays = group_by_weekday(data[user_id])
return [
(day_abbr[week... | 72,079 |
def test_reuse_all_components(pkg_util, scenario, repo, koji):
"""Rebuild the test module again, without changing any of the components with:
`fedpkg module-build -w --optional rebuild_strategy=only-changed`
Checks:
* Verify that all the components are reused from the first build.
* Verify that mo... | 72,080 |
def next_vol_pred(model, data_generator, verbose=False):
"""
get the next batch, predict model output
returns (input_vol, y_true, y_pred, <prior>)
"""
# batch to input, output and prediction
sample = next(data_generator)
with timer.Timer('prediction', verbose):
pred = model.predict... | 72,081 |
def marshal_bson(
obj: object,
types: Iterable=BSON_TYPES,
fields: Optional[List[str]]=None,
) -> dict:
""" Recursively marshal a Python object to a BSON-compatible dict
that can be passed to PyMongo, Motor, etc...
Args:
obj: It's members can be nested Python
obje... | 72,082 |
def api_get_all_sysrepo_modules():
"""
Returns all Sysrepo module names
"""
return json_resp(sr_model.get_modules_names()) | 72,083 |
def get_category_index_from_categories(categories, category):
"""
Gets the index of a category from the categories dictionary. If the category
doesn't exist, it creates a new entry for that category name and returns
the new index number.
"""
if category not in categories:
categories[cat... | 72,084 |
def test_combine_inputs_collision_2():
"""Tests the combine_and_validate_inputs functionality
when there are collisions of keys and values"""
with pytest.raises(ValueError):
graph.FunctionGraph.combine_config_and_inputs({'a': 1}, {'a': 1}) | 72,085 |
def check(model, a, b, pos, val):
"""
`a` and `b`: the two arrays to check (here `b`
corresponds to the array `x` in the model).
`pos`: number of correct values and positions
`val`: numbver correct values
(regardless if there are correct position or not)
"""
n = len(a)
# number of e... | 72,086 |
def next_wangib(date):
"""Waning gibbous."""
return find_moon_phase(date, pi * 2.0, pi + (pi / 4.0)) | 72,087 |
def create_repas_noel_column(X):
"""Crée la variable pour le repas de Noël"""
X["repas_noel"] = X["repas_noel"] * X["effectif"]
return X | 72,088 |
def intervalLength(aa, wrapAt=360.):
"""Returns the length of an interval."""
if wrapAt is None:
return (aa[1] - aa[0])
else:
return (aa[1] - aa[0]) % wrapAt | 72,089 |
def memmap_unlink(filename):
"""Wrapper around os.unlink with a retry mechanism.
The retry mechanism has been implemented primarily to overcome a race
condition happening during the finalizer of a np.memmap: when a process
holding the last reference to a mmap-backed np.memmap/np.array is about to
d... | 72,090 |
def append_to_xl(file, df_dict, overwrite=True):
"""appends dictionary of dataframes to an Excel file
overwrite: will append data to existing file, else create a copy and
adds data to it
Args:
file (str): input excel filename
df_dict (dict): dictionary of key:DataFrame format
overwrite (bool, option... | 72,091 |
def is_valid_ordering(ordering):
"""checks if an ordering is valid
Args:
ordering (str): The ordering of a note
Returns:
bool: True if the ordering is valid
"""
if re.match(r'^[0-9_]+$', ordering):
return True
else:
return False | 72,092 |
def translateDNA_6Frames(sequence) :
"""returns 6 translation of sequence. One for each reading frame"""
trans = (
translateDNA(sequence, 'f1'),
translateDNA(sequence, 'f2'),
translateDNA(sequence, 'f3'),
translateDNA(sequence, 'r1'),
translateDNA(sequence, 'r2'),
translateDNA(sequence, 'r3')... | 72,093 |
def dataset_to_dataframe(ds: xr.Dataset, dim_order: t.List[str] = None):
"""Convert an xarray Dataset to a pandas DataFrame.
Stores Dataset attributes and fixes the merged/expand_dims dimension names
bug.
Parameters
----------
ds : xr.Dataset
The Dataset to convert.
dim_order : lis... | 72,094 |
def load(f, where=None):
"""Read Amiga disk font file."""
# read & ignore header
_read_header(f)
hunk_id = _read_ulong(f)
if hunk_id != _HUNK_CODE:
raise FileFormatError('Not an Amiga font data file: no code hunk found (id %04x)' % hunk_id)
glyphs, props = _read_font_hunk(f)
return F... | 72,095 |
def test_repr_MockObject():
"""
Test ``MockObject.__repr__``.
"""
empty = MockObject()
mo_p = re.compile(r"^(?P<_><)sunpy\.tests\.mocks\.MockObject \{\} "
"at 0x[0-9A-Fa-f]+L?(?(_)>|)$")
assert mo_p.match(repr(empty)) is not None | 72,096 |
def block(self, hash_or_number: str, **kwargs):
"""
Return the content of a requested block.
https://docs.blockfrost.io/#tag/Cardano-Blocks/paths/~1blocks~1{hash_or_number}/get
:param hash_or_number: Hash or number of the requested block.
:type hash_or_number: str
:param return_type: Optional.... | 72,097 |
def sql_from_one_hot_encoder(
X: list, categories: list, drop_first: bool = False, column_naming: str = None
) -> list:
"""
---------------------------------------------------------------------------
Returns the SQL code needed to deploy a one-hot encoder model using its
attributes.
Parameters... | 72,098 |
def test_settings_disable():
"""Test to make sure DISABLE actually disables cache."""
Settings.DISABLE = True
with Capturing() as output1:
caller1()
with Capturing() as output2:
caller1()
assert len(output1) == 12
assert len(output2) == 12
return | 72,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.