response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Prepare list of pandas DataFrames to be used as input to pd.concat.
Ensure any columns of type 'category' have the same categories across each
dataframe.
Parameters
----------
df_list : list
List of dataframes with same columns.
inplace : bool
True if input list can be modified. Default is False.
Returns
----... | def categorical_df_concat(df_list, inplace=False):
"""
Prepare list of pandas DataFrames to be used as input to pd.concat.
Ensure any columns of type 'category' have the same categories across each
dataframe.
Parameters
----------
df_list : list
List of dataframes with same columns.... |
Union entries in ``iterables`` into a set.
| def _union_all(iterables):
"""Union entries in ``iterables`` into a set.
"""
return set().union(*iterables) |
Sort a set, sorting ``None`` before other elements, if present.
| def _sort_set_none_first(set_):
"""Sort a set, sorting ``None`` before other elements, if present.
"""
if None in set_:
set_.remove(None)
out = [None]
out.extend(sorted(set_))
set_.add(None)
return out
else:
return sorted(set_) |
Create an empty dataframe with columns of particular types.
Parameters
----------
*columns
The (column_name, column_dtype) pairs.
Returns
-------
typed_dataframe : pd.DataFrame
The empty typed dataframe.
Examples
--------
>>> df = empty_dataframe(
... ('a', 'int64'),
... ('b', 'float64'),
... ('c... | def empty_dataframe(*columns):
"""Create an empty dataframe with columns of particular types.
Parameters
----------
*columns
The (column_name, column_dtype) pairs.
Returns
-------
typed_dataframe : pd.DataFrame
The empty typed dataframe.
Examples
--------
>>> d... |
Check that a list of Index objects are all equal.
Parameters
----------
indexes : iterable[pd.Index]
Iterable of indexes to check.
Raises
------
ValueError
If the indexes are not all the same. | def check_indexes_all_same(indexes, message="Indexes are not equal."):
"""Check that a list of Index objects are all equal.
Parameters
----------
indexes : iterable[pd.Index]
Iterable of indexes to check.
Raises
------
ValueError
If the indexes are not all the same.
"""... |
Check if a path is hidden.
Parameters
----------
path : str
A filepath. | def hidden(path):
"""Check if a path is hidden.
Parameters
----------
path : str
A filepath.
"""
return os.path.split(path)[1].startswith('.') |
Ensure that a directory named "path" exists. | def ensure_directory(path):
"""
Ensure that a directory named "path" exists.
"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == EEXIST and os.path.isdir(path):
return
raise |
Ensure that the directory containing `path` exists.
This is just a convenience wrapper for doing::
ensure_directory(os.path.dirname(path)) | def ensure_directory_containing(path):
"""
Ensure that the directory containing `path` exists.
This is just a convenience wrapper for doing::
ensure_directory(os.path.dirname(path))
"""
ensure_directory(os.path.dirname(path)) |
Ensure that a file exists. This will create any parent directories needed
and create an empty file if it does not exist.
Parameters
----------
path : str
The file path to ensure exists. | def ensure_file(path):
"""
Ensure that a file exists. This will create any parent directories needed
and create an empty file if it does not exist.
Parameters
----------
path : str
The file path to ensure exists.
"""
ensure_directory_containing(path)
open(path, 'a+').close() |
Updates the modified time of an existing file. This will create any
parent directories needed and create an empty file if it does not exist.
Parameters
----------
path : str
The file path to update.
times : tuple
A tuple of size two; access time and modified time | def update_modified_time(path, times=None):
"""
Updates the modified time of an existing file. This will create any
parent directories needed and create an empty file if it does not exist.
Parameters
----------
path : str
The file path to update.
times : tuple
A tuple of siz... |
Get the last modified time of path as a Timestamp. | def last_modified_time(path):
"""
Get the last modified time of path as a Timestamp.
"""
return pd.Timestamp(os.path.getmtime(path), unit='s', tz='UTC') |
Check whether `path` was modified since `dt`.
Returns False if path doesn't exist.
Parameters
----------
path : str
Path to the file to be checked.
dt : pd.Timestamp
The date against which to compare last_modified_time(path).
Returns
-------
was_modified : bool
Will be ``False`` if path doesn't exists, o... | def modified_since(path, dt):
"""
Check whether `path` was modified since `dt`.
Returns False if path doesn't exist.
Parameters
----------
path : str
Path to the file to be checked.
dt : pd.Timestamp
The date against which to compare last_modified_time(path).
Returns
... |
Get the root directory for all zipline-managed files.
For testing purposes, this accepts a dictionary to interpret as the os
environment.
Parameters
----------
environ : dict, optional
A dict to interpret as the os environment.
Returns
-------
root : string
Path to the zipline root dir. | def zipline_root(environ=None):
"""
Get the root directory for all zipline-managed files.
For testing purposes, this accepts a dictionary to interpret as the os
environment.
Parameters
----------
environ : dict, optional
A dict to interpret as the os environment.
Returns
-... |
Get a path relative to the zipline root.
Parameters
----------
paths : list[str]
List of requested path pieces.
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
newpath : str
The requested path joined with the zipline root. | def zipline_path(paths, environ=None):
"""
Get a path relative to the zipline root.
Parameters
----------
paths : list[str]
List of requested path pieces.
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
newpath : str
... |
Get the path to the default zipline extension file.
Parameters
----------
environ : dict, optional
An environment dict to forwart to zipline_root.
Returns
-------
default_extension_path : str
The file path to the default zipline extension file. | def default_extension(environ=None):
"""
Get the path to the default zipline extension file.
Parameters
----------
environ : dict, optional
An environment dict to forwart to zipline_root.
Returns
-------
default_extension_path : str
The file path to the default zipline ... |
The root directory for zipline data files.
Parameters
----------
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
data_root : str
The zipline data root. | def data_root(environ=None):
"""
The root directory for zipline data files.
Parameters
----------
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
data_root : str
The zipline data root.
"""
return zipline_path(['data'], env... |
Ensure that the data root exists. | def ensure_data_root(environ=None):
"""
Ensure that the data root exists.
"""
ensure_directory(data_root(environ=environ)) |
Get a path relative to the zipline data directory.
Parameters
----------
paths : iterable[str]
List of requested path pieces.
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
newpath : str
The requested path joined with the zipline data root. | def data_path(paths, environ=None):
"""
Get a path relative to the zipline data directory.
Parameters
----------
paths : iterable[str]
List of requested path pieces.
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
newpath : s... |
The root directory for zipline cache files.
Parameters
----------
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
cache_root : str
The zipline cache root. | def cache_root(environ=None):
"""
The root directory for zipline cache files.
Parameters
----------
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
cache_root : str
The zipline cache root.
"""
return zipline_path(['cache']... |
Ensure that the data root exists. | def ensure_cache_root(environ=None):
"""
Ensure that the data root exists.
"""
ensure_directory(cache_root(environ=environ)) |
Get a path relative to the zipline cache directory.
Parameters
----------
paths : iterable[str]
List of requested path pieces.
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
newpath : str
The requested path joined with the zipline cache root. | def cache_path(paths, environ=None):
"""
Get a path relative to the zipline cache directory.
Parameters
----------
paths : iterable[str]
List of requested path pieces.
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
newpath :... |
Decorator that applies pre-processors to the arguments of a function before
calling the function.
Parameters
----------
**processors : dict
Map from argument name -> processor function.
A processor function takes three arguments: (func, argname, argvalue).
`func` is the the function for which we're proce... | def preprocess(*_unused, **processors):
"""
Decorator that applies pre-processors to the arguments of a function before
calling the function.
Parameters
----------
**processors : dict
Map from argument name -> processor function.
A processor function takes three arguments: (fun... |
Wrap a function in a processor that calls `f` on the argument before
passing it along.
Useful for creating simple arguments to the `@preprocess` decorator.
Parameters
----------
f : function
Function accepting a single argument and returning a replacement.
Examples
--------
>>> @preprocess(x=call(lambda x: x + 1... | def call(f):
"""
Wrap a function in a processor that calls `f` on the argument before
passing it along.
Useful for creating simple arguments to the `@preprocess` decorator.
Parameters
----------
f : function
Function accepting a single argument and returning a replacement.
Exa... |
Build a preprocessed function with the same signature as `func`.
Uses `exec` internally to build a function that actually has the same
signature as `func. | def _build_preprocessed_function(func,
processors,
args_defaults,
varargs,
varkw):
"""
Build a preprocessed function with the same signature as `func`.
Uses `exec` internally ... |
Convert a tuple into a range with error handling.
Parameters
----------
tup : tuple (len 2 or 3)
The tuple to turn into a range.
Returns
-------
range : range
The range from the tuple.
Raises
------
ValueError
Raised when the tuple length is not 2 or 3. | def from_tuple(tup):
"""Convert a tuple into a range with error handling.
Parameters
----------
tup : tuple (len 2 or 3)
The tuple to turn into a range.
Returns
-------
range : range
The range from the tuple.
Raises
------
ValueError
Raised when the tup... |
Convert a tuple into a range but pass ranges through silently.
This is useful to ensure that input is a range so that attributes may
be accessed with `.start`, `.stop` or so that containment checks are
constant time.
Parameters
----------
tup_or_range : tuple or range
A tuple to pass to from_tuple or a range to r... | def maybe_from_tuple(tup_or_range):
"""Convert a tuple into a range but pass ranges through silently.
This is useful to ensure that input is a range so that attributes may
be accessed with `.start`, `.stop` or so that containment checks are
constant time.
Parameters
----------
tup_or_range... |
Check that the steps of ``a`` and ``b`` are both 1.
Parameters
----------
a : range
The first range to check.
b : range
The second range to check.
Raises
------
ValueError
Raised when either step is not 1. | def _check_steps(a, b):
"""Check that the steps of ``a`` and ``b`` are both 1.
Parameters
----------
a : range
The first range to check.
b : range
The second range to check.
Raises
------
ValueError
Raised when either step is not 1.
"""
if a.step != 1:
... |
Check if two ranges overlap.
Parameters
----------
a : range
The first range.
b : range
The second range.
Returns
-------
overlaps : bool
Do these ranges overlap.
Notes
-----
This function does not support ranges with step != 1. | def overlap(a, b):
"""Check if two ranges overlap.
Parameters
----------
a : range
The first range.
b : range
The second range.
Returns
-------
overlaps : bool
Do these ranges overlap.
Notes
-----
This function does not support ranges with step != ... |
Merge two ranges with step == 1.
Parameters
----------
a : range
The first range.
b : range
The second range. | def merge(a, b):
"""Merge two ranges with step == 1.
Parameters
----------
a : range
The first range.
b : range
The second range.
"""
_check_steps(a, b)
return range(min(a.start, b.start), max(a.stop, b.stop)) |
helper for ``_group_ranges``
| def _combine(n, rs):
"""helper for ``_group_ranges``
"""
try:
r, rs = peek(rs)
except StopIteration:
yield n
return
if overlap(n, r):
yield merge(n, r)
next(rs)
for r in rs:
yield r
else:
yield n
for r in rs:
... |
Group any overlapping ranges into a single range.
Parameters
----------
ranges : iterable[ranges]
A sorted sequence of ranges to group.
Returns
-------
grouped : iterable[ranges]
A sorted sequence of ranges with overlapping ranges merged together. | def group_ranges(ranges):
"""Group any overlapping ranges into a single range.
Parameters
----------
ranges : iterable[ranges]
A sorted sequence of ranges to group.
Returns
-------
grouped : iterable[ranges]
A sorted sequence of ranges with overlapping ranges merged togethe... |
Return any ranges that intersect.
Parameters
----------
ranges : iterable[ranges]
A sequence of ranges to check for intersections.
Returns
-------
intersections : iterable[ranges]
A sequence of all of the ranges that intersected in ``ranges``.
Examples
--------
>>> ranges = [range(0, 1), range(2, 5), range(4... | def intersecting_ranges(ranges):
"""Return any ranges that intersect.
Parameters
----------
ranges : iterable[ranges]
A sequence of ranges to check for intersections.
Returns
-------
intersections : iterable[ranges]
A sequence of all of the ranges that intersected in ``rang... |
Run a backtest for the given algorithm.
This is shared between the cli and :func:`zipline.run_algo`. | def _run(handle_data,
initialize,
before_trading_start,
analyze,
algofile,
algotext,
defines,
data_frequency,
capital_base,
bundle,
bundle_timestamp,
start,
end,
output,
trading_calendar,
... |
Load all of the given extensions. This should be called by run_algo
or the cli.
Parameters
----------
default : bool
Load the default exension (~/.zipline/extension.py)?
extension : iterable[str]
The paths to the extensions to load. If the path ends in ``.py`` it is
treated as a script and executed. If it ... | def load_extensions(default, extensions, strict, environ, reload=False):
"""Load all of the given extensions. This should be called by run_algo
or the cli.
Parameters
----------
default : bool
Load the default exension (~/.zipline/extension.py)?
extension : iterable[str]
The pat... |
Run a trading algorithm.
Parameters
----------
start : datetime
The start date of the backtest.
end : datetime
The end date of the backtest..
initialize : callable[context -> None]
The initialize function to use for the algorithm. This is called once
at the very begining of the backtest and should be u... | def run_algorithm(start,
end,
initialize,
capital_base,
handle_data=None,
before_trading_start=None,
analyze=None,
data_frequency='daily',
bundle='quantopian-quandl',
... |
To resolve the symbol in the LEVERAGED_ETF list,
the date on which the symbol was in effect is needed.
Furthermore, to maintain a point in time record of our own maintenance
of the restricted list, we need a knowledge date. Thus, restricted lists
are dictionaries of datetime->symbol lists.
new symbols should be entere... | def load_from_directory(list_name):
"""
To resolve the symbol in the LEVERAGED_ETF list,
the date on which the symbol was in effect is needed.
Furthermore, to maintain a point in time record of our own maintenance
of the restricted list, we need a knowledge date. Thus, restricted lists
are dict... |
Apply a prefix to each line in s after the first. | def pad_lines_after_first(prefix, s):
"""Apply a prefix to each line in s after the first."""
return ('\n' + prefix).join(s.splitlines()) |
Template ``formatters`` into ``docstring``.
Parameters
----------
owner_name : str
The name of the function or class whose docstring is being templated.
Only used for error messages.
docstring : str
The docstring to template.
formatters : dict[str -> str]
Parameters for a a str.format() call on ``docst... | def format_docstring(owner_name, docstring, formatters):
"""
Template ``formatters`` into ``docstring``.
Parameters
----------
owner_name : str
The name of the function or class whose docstring is being templated.
Only used for error messages.
docstring : str
The docstri... |
Decorator allowing the use of templated docstrings.
Examples
--------
>>> @templated_docstring(foo='bar')
... def my_func(self, foo):
... '''{foo}'''
...
>>> my_func.__doc__
'bar' | def templated_docstring(**docs):
"""
Decorator allowing the use of templated docstrings.
Examples
--------
>>> @templated_docstring(foo='bar')
... def my_func(self, foo):
... '''{foo}'''
...
>>> my_func.__doc__
'bar'
"""
def decorator(f):
f.__doc__ = format_d... |
Copies the docstring from one function to another.
Parameters
----------
from_ : any
The object to copy the docstring from.
to : any
The object to copy the docstring to.
Returns
-------
to : any
``to`` with the docstring from ``from_`` | def copydoc(from_, to):
"""Copies the docstring from one function to another.
Parameters
----------
from_ : any
The object to copy the docstring from.
to : any
The object to copy the docstring to.
Returns
-------
to : any
``to`` with the docstring from ``from_``
... |
Format a bulleted list of values.
| def bulleted_list(items, max_count=None, indent=2):
"""Format a bulleted list of values.
"""
if max_count is not None and len(items) > max_count:
item_list = list(items)
items = item_list[:max_count - 1]
items.append('...')
items.append(item_list[-1])
line_template = (" ... |
Because Zulip uses management commands in production, `manage.py
help` is a form of documentation for users. Here we exclude from
that documentation built-in commands that are not constructive for
end users or even Zulip developers to run.
Ideally, we'd do further customization to display management
commands with more... | def get_filtered_commands() -> Dict[str, str]:
"""Because Zulip uses management commands in production, `manage.py
help` is a form of documentation for users. Here we exclude from
that documentation built-in commands that are not constructive for
end users or even Zulip developers to run.
Ideally, ... |
Run a FilteredManagementUtility. | def execute_from_command_line(argv: Optional[List[str]] = None) -> None:
"""Run a FilteredManagementUtility."""
utility = FilteredManagementUtility(argv)
utility.execute() |
Generate semi-realistic looking time series data for testing analytics graphs.
days -- Number of days of data. Is the number of data points generated if
frequency is CountStat.DAY.
business_hours_base -- Average value during a business hour (or day) at beginning of
time series, if frequency is CountStat.HOUR (... | def generate_time_series_data(
days: int = 100,
business_hours_base: float = 10,
non_business_hours_base: float = 10,
growth: float = 1,
autocorrelation: float = 0,
spikiness: float = 1,
holiday_rate: float = 0,
frequency: str = CountStat.DAY,
partial_sum: bool = False,
random_se... |
This is a preparatory migration for our Analytics tables.
The backstory is that Django's unique_together indexes do not properly
handle the subgroup=None corner case (allowing duplicate rows that have a
subgroup of None), which meant that in race conditions, rather than updating
an existing row for the property/(realm... | def clear_duplicate_counts(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""This is a preparatory migration for our Analytics tables.
The backstory is that Django's unique_together indexes do not properly
handle the subgroup=None corner case (allowing duplicate rows that have a
sub... |
Access a confirmation object from one of the provided confirmation
types with the provided key.
The mark_object_used parameter determines whether to mark the
confirmation object as used (which generally prevents it from
being used again). It should always be False for MultiuseInvite
objects, since they are intended to... | def get_object_from_key(
confirmation_key: str, confirmation_types: List[int], *, mark_object_used: bool
) -> ConfirmationObjT:
"""Access a confirmation object from one of the provided confirmation
types with the provided key.
The mark_object_used parameter determines whether to mark the
confirmati... |
Generate a unique link that a logged-out user can visit to unsubscribe from
Zulip e-mails without having to first log in. | def one_click_unsubscribe_link(user_profile: UserProfile, email_type: str) -> str:
"""
Generate a unique link that a logged-out user can visit to unsubscribe from
Zulip e-mails without having to first log in.
"""
return create_confirmation_link(
user_profile, Confirmation.UNSUBSCRIBE, url_ar... |
Get the record for this key, raising InvalidCreationKey if non-None but invalid. | def validate_key(creation_key: Optional[str]) -> Optional["RealmCreationKey"]:
"""Get the record for this key, raising InvalidCreationKey if non-None but invalid."""
if creation_key is None:
return None
try:
key_record = RealmCreationKey.objects.get(creation_key=creation_key)
except Real... |
Returns all rows from a cursor as a dict | def dictfetchall(cursor: CursorWrapper) -> List[Dict[str, Any]]:
"""Returns all rows from a cursor as a dict"""
desc = cursor.description
return [dict(zip((col[0] for col in desc), row)) for row in cursor.fetchall()] |
Fixed price plan offer configured via /support which the
customer is yet to buy or schedule a purchase. | def get_configured_fixed_price_plan_offer(
customer: Customer, plan_tier: int
) -> Optional[CustomerPlanOffer]:
"""
Fixed price plan offer configured via /support which the
customer is yet to buy or schedule a purchase.
"""
if plan_tier == customer.required_plan_tier:
return CustomerPlan... |
Utility function for reactivating deactivated registrations. | def do_reactivate_remote_server(remote_server: RemoteZulipServer) -> None:
"""
Utility function for reactivating deactivated registrations.
"""
if not remote_server.deactivated:
billing_logger.warning(
"Cannot reactivate remote server with ID %d, server is already active.",
... |
This is the endpoint accessed via the billing_access_url, generated by
remote_realm_billing_entry entry. | def remote_realm_billing_finalize_login(
request: HttpRequest,
*,
signed_billing_access_token: PathOnly[str],
full_name: Optional[str] = None,
tos_consent: Literal[None, "true"] = None,
enable_major_release_emails: Literal[None, "true", "false"] = None,
enable_maintenance_release_emails: Lit... |
Endpoint for users in the RemoteRealm flow that are logging in for the first time
and still have to have their RemoteRealmBillingUser object created.
Takes the POST from the above form asking for their email address
and sends confirmation email to the provided
email address in order to verify. Only the confirmation lin... | def remote_realm_billing_confirm_email(
request: HttpRequest,
*,
signed_billing_access_token: PathOnly[str],
email: str,
) -> HttpResponse:
"""
Endpoint for users in the RemoteRealm flow that are logging in for the first time
and still have to have their RemoteRealmBillingUser object created... |
The user comes here via the confirmation link they received via email.
Creates the RemoteRealmBillingUser object and redirects to
remote_realm_billing_finalize_login with a new signed access token,
where they will finally be logged in now that they have an account. | def remote_realm_billing_from_login_confirmation_link(
request: HttpRequest,
*,
confirmation_key: PathOnly[str],
) -> HttpResponse:
"""
The user comes here via the confirmation link they received via email.
Creates the RemoteRealmBillingUser object and redirects to
remote_realm_billing_final... |
Takes the POST from the above form and sends confirmation email to the provided
email address in order to verify. Only the confirmation link will grant
a fully authenticated session. | def remote_billing_legacy_server_confirm_login(
request: HttpRequest,
*,
server_uuid: PathOnly[str],
email: str,
next_page: VALID_NEXT_PAGES_TYPE = None,
) -> HttpResponse:
"""
Takes the POST from the above form and sends confirmation email to the provided
email address in order to verif... |
The user comes here via the confirmation link they received via email. | def remote_billing_legacy_server_from_login_confirmation_link(
request: HttpRequest,
*,
confirmation_key: PathOnly[str],
full_name: Optional[str] = None,
tos_consent: Literal[None, "true"] = None,
enable_major_release_emails: Literal[None, "true", "false"] = None,
enable_maintenance_release_... |
Do a simple queue size check for queues whose workers don't publish stats files. | def check_other_queues(queue_counts_dict: Dict[str, int]) -> List[Dict[str, Any]]:
"""Do a simple queue size check for queues whose workers don't publish stats files."""
results = []
for queue, count in queue_counts_dict.items():
if queue in normal_queues:
continue
if count ... |
Returns a sorted list of unique dependencies specified by the requirements file `fpath`.
Removes comments from the output and recursively visits files specified inside `fpath`.
`fpath` can be either an absolute path or a relative path. | def expand_reqs(fpath: str) -> List[str]:
"""
Returns a sorted list of unique dependencies specified by the requirements file `fpath`.
Removes comments from the output and recursively visits files specified inside `fpath`.
`fpath` can be either an absolute path or a relative path.
"""
absfpath =... |
Returns the Python version as string 'Python major.minor.patchlevel' | def python_version() -> str:
"""
Returns the Python version as string 'Python major.minor.patchlevel'
"""
return subprocess.check_output(["/usr/bin/python3", "-VV"], text=True) |
Creates a file, called package_index, in the virtual environment
directory that contains all the PIP packages installed in the
virtual environment. This file is used to determine the packages
that can be copied to a new virtual environment. | def create_requirements_index_file(venv_path: str, requirements_file: str) -> str:
"""
Creates a file, called package_index, in the virtual environment
directory that contains all the PIP packages installed in the
virtual environment. This file is used to determine the packages
that can be copied to... |
Returns the packages installed in the virtual environment using the
package index file. | def get_venv_packages(venv_path: str) -> Set[str]:
"""
Returns the packages installed in the virtual environment using the
package index file.
"""
with open(get_index_filename(venv_path)) as reader:
return {p.strip() for p in reader.read().split("\n") if p.strip()} |
Tries to copy packages from an old virtual environment in the cache
to the new virtual environment. The algorithm works as follows:
1. Find a virtual environment, v, from the cache that has the
highest overlap with the new requirements such that:
a. The new requirements only add to the packages of v.
... | def try_to_copy_venv(venv_path: str, new_packages: Set[str]) -> bool:
"""
Tries to copy packages from an old virtual environment in the cache
to the new virtual environment. The algorithm works as follows:
1. Find a virtual environment, v, from the cache that has the
highest overlap with the... |
Patches the bin/activate script so that the value of the environment variable VIRTUAL_ENV
is set to venv_path during the script's execution whenever it is sourced. | def do_patch_activate_script(venv_path: str) -> None:
"""
Patches the bin/activate script so that the value of the environment variable VIRTUAL_ENV
is set to venv_path during the script's execution whenever it is sourced.
"""
# venv_path should be what we want to have in VIRTUAL_ENV after patching
... |
Warning: su_to_zulip assumes that the zulip checkout is owned by
the zulip user (or whatever normal user is running the Zulip
installation). It should never be run from the installer or other
production contexts before /home/zulip/deployments/current is
created. | def su_to_zulip(save_suid: bool = False) -> None:
"""Warning: su_to_zulip assumes that the zulip checkout is owned by
the zulip user (or whatever normal user is running the Zulip
installation). It should never be run from the installer or other
production contexts before /home/zulip/deployments/current... |
Example of the useful subset of the data:
{
'ID': 'ubuntu',
'VERSION_ID': '18.04',
'NAME': 'Ubuntu',
'VERSION': '18.04.3 LTS (Bionic Beaver)',
'PRETTY_NAME': 'Ubuntu 18.04.3 LTS',
}
VERSION_CODENAME (e.g. 'bionic') is nice and readable to Ubuntu
developers, but we avoid using it, as it is not available on
RHEL-ba... | def parse_os_release() -> Dict[str, str]:
"""
Example of the useful subset of the data:
{
'ID': 'ubuntu',
'VERSION_ID': '18.04',
'NAME': 'Ubuntu',
'VERSION': '18.04.3 LTS (Bionic Beaver)',
'PRETTY_NAME': 'Ubuntu 18.04.3 LTS',
}
VERSION_CODENAME (e.g. 'bionic') is nice and r... |
Known families:
debian (includes: debian, ubuntu)
ubuntu (includes: ubuntu)
fedora (includes: fedora, rhel, centos)
rhel (includes: rhel, centos)
centos (includes: centos) | def os_families() -> Set[str]:
"""
Known families:
debian (includes: debian, ubuntu)
ubuntu (includes: ubuntu)
fedora (includes: fedora, rhel, centos)
rhel (includes: rhel, centos)
centos (includes: centos)
"""
distro_info = parse_os_release()
return {distro_info["ID"], *distro_i... |
In order to determine if we need to run some
process, we calculate a digest of the important
files and strings whose respective contents
or values may indicate such a need.
filenames = files we should hash the contents of
extra_strings = strings we should hash directly
Grep for callers to see examples of how ... | def is_digest_obsolete(
hash_name: str, filenames: Sequence[str], extra_strings: Sequence[str] = []
) -> bool:
"""
In order to determine if we need to run some
process, we calculate a digest of the important
files and strings whose respective contents
or values may indicate such a need.
... |
Remove the port from a hostname:port string. Brackets on a literal
IPv6 address are included. | def deport(netloc: str) -> str:
"""Remove the port from a hostname:port string. Brackets on a literal
IPv6 address are included."""
r = SplitResult("", netloc, "", "", "")
assert r.hostname is not None
return "[" + r.hostname + "]" if ":" in r.hostname else r.hostname |
Secret key generation taken from Django's startproject.py | def generate_django_secretkey() -> str:
"""Secret key generation taken from Django's startproject.py"""
# We do in-function imports so that we only do the expensive work
# of importing cryptography modules when necessary.
#
# This helps optimize noop provision performance.
from django.utils.cry... |
Safe phrase is in lower case and doesn't contain characters which can
conflict with split boundaries. All conflicting characters are replaced
with low dash (_). | def get_safe_phrase(phrase: str) -> str:
"""
Safe phrase is in lower case and doesn't contain characters which can
conflict with split boundaries. All conflicting characters are replaced
with low dash (_).
"""
phrase = SPLIT_BOUNDARY_REGEX.sub("_", phrase)
return phrase.lower() |
The idea is to convert IGNORED_PHRASES into safe phrases, see
`get_safe_phrase()` function. The only exception is when the
IGNORED_PHRASE is at the start of the text or after a split
boundary; in this case, we change the first letter of the phrase
to upper case. | def replace_with_safe_phrase(matchobj: Match[str]) -> str:
"""
The idea is to convert IGNORED_PHRASES into safe phrases, see
`get_safe_phrase()` function. The only exception is when the
IGNORED_PHRASE is at the start of the text or after a split
boundary; in this case, we change the first letter of ... |
This returns text which is rendered by BeautifulSoup and is in the
form that can be split easily and has all IGNORED_PHRASES processed. | def get_safe_text(text: str) -> str:
"""
This returns text which is rendered by BeautifulSoup and is in the
form that can be split easily and has all IGNORED_PHRASES processed.
"""
soup = BeautifulSoup(text, "lxml")
text = " ".join(soup.text.split()) # Remove extra whitespaces.
for phrase_r... |
During the parsing/validation phase, it's useful to have separate
tokens for "indent" chunks, but during pretty printing, we like
to attach an `.indent` field to the substantive node, whether
it's an HTML tag or template directive or whatever. | def shift_indents_to_the_next_tokens(tokens: List[Token]) -> None:
"""
During the parsing/validation phase, it's useful to have separate
tokens for "indent" chunks, but during pretty printing, we like
to attach an `.indent` field to the substantive node, whether
it's an HTML tag or template directiv... |
Select a bash profile file to add setup code to. | def setup_bash_profile() -> None:
"""Select a bash profile file to add setup code to."""
BASH_PROFILES = [
os.path.expanduser(p) for p in ("~/.bash_profile", "~/.bash_login", "~/.profile")
]
def clear_old_profile() -> None:
# An earlier version of this script would output a fresh .bash... |
Works for both partials and partial blocks. | def get_handlebars_partial(text: str, i: int) -> str:
"""Works for both partials and partial blocks."""
end = i + 10
unclosed_end = 0
while end <= len(text):
if text[end - 2 : end] == "}}":
return text[i:end]
if not unclosed_end and text[end] == "<":
unclosed_end... |
Registers --skip-provision-check argument to be used with various commands/tests in our tools. | def add_provision_check_override_param(parser: ArgumentParser) -> None:
"""
Registers --skip-provision-check argument to be used with various commands/tests in our tools.
"""
parser.add_argument(
"--skip-provision-check",
action="store_true",
help="Skip check that provision has b... |
Get the exit code of the server, or None if it is still running. | def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
"""Get the exit code of the server, or None if it is still running."""
if server.poll() is not None:
message = "Server died unexpectedly!"
if log_file:
message += f"\nSee {log_file}\n"
... |
Common context used for things like outgoing emails that don't
have a request. | def common_context(user: UserProfile) -> Dict[str, Any]:
"""Common context used for things like outgoing emails that don't
have a request.
"""
return {
"realm_uri": user.realm.uri,
"realm_name": user.realm.name,
"root_domain_url": settings.ROOT_DOMAIN_URI,
"external_url_s... |
Accept a GET param `?nav=no` to render an isolated, navless page. | def is_isolated_page(request: HttpRequest) -> bool:
"""Accept a GET param `?nav=no` to render an isolated, navless page."""
return request.GET.get("nav") == "no" |
Context available to all Zulip Jinja2 templates that have a request
passed in. Designed to provide the long list of variables at the
bottom of this function in a wide range of situations: logged-in
or logged-out, subdomains or not, etc.
The main variable in the below is whether we know what realm the
user is trying t... | def zulip_default_context(request: HttpRequest) -> Dict[str, Any]:
"""Context available to all Zulip Jinja2 templates that have a request
passed in. Designed to provide the long list of variables at the
bottom of this function in a wide range of situations: logged-in
or logged-out, subdomains or not, e... |
The optional user parameter requests that a UserActivity row be
created/updated to record this request.
In particular, unauthenticate requests and those authenticated to
a non-user object like RemoteZulipServer should not pass the
`user` parameter. | def process_client(
request: HttpRequest,
user: Union[UserProfile, AnonymousUser, None] = None,
*,
is_browser_view: bool = False,
client_name: Optional[str] = None,
query: Optional[str] = None,
) -> None:
"""The optional user parameter requests that a UserActivity row be
created/updated ... |
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes. | def user_passes_test(
test_func: Callable[[HttpRequest], bool],
login_url: Optional[str] = None,
redirect_field_name: str = REDIRECT_FIELD_NAME,
) -> Callable[
[Callable[Concatenate[HttpRequest, ParamT], HttpResponse]],
Callable[Concatenate[HttpRequest, ParamT], HttpResponse],
]:
"""
Decorat... |
Creates a session, logging in the user, using the Django method,
and also adds helpful data needed by our server logs. | def do_login(request: HttpRequest, user_profile: UserProfile) -> None:
"""Creates a session, logging in the user, using the Django method,
and also adds helpful data needed by our server logs.
"""
# As a hardening measure, pass the user_profile through the dummy backend,
# which does the minimal va... |
This wrapper adds client info for unauthenticated users but
forces authenticated users to go through 2fa. | def web_public_view(
view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse],
redirect_field_name: str = REDIRECT_FIELD_NAME,
login_url: str = settings.HOME_NOT_LOGGED_IN,
) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]:
"""
This wrapper adds client info for unauthenticated... |
Extracts the role and API key as a tuple from the Authorization header
for HTTP basic authentication. | def get_basic_credentials(
request: HttpRequest, beanstalk_email_decode: bool = False
) -> Tuple[str, str]:
"""
Extracts the role and API key as a tuple from the Authorization header
for HTTP basic authentication.
"""
try:
# Grab the base64-encoded authentication string, decode it, and s... |
Used for situations where something running on the Zulip server
needs to make a request to the (other) Django/Tornado processes running on
the server. | def internal_api_view(
is_tornado_view: bool,
) -> Callable[
[Callable[Concatenate[HttpRequest, ParamT], HttpResponse]],
Callable[Concatenate[HttpRequest, ParamT], HttpResponse],
]:
"""Used for situations where something running on the Zulip server
needs to make a request to the (other) Django/Torna... |
The reason we need to create this function is that the stock
otp_required decorator doesn't play well with tests. We cannot
enable/disable if_configured parameter during tests since the decorator
retains its value due to closure.
Similar to :func:`~django.contrib.auth.decorators.login_required`, but
requires the user ... | def zulip_otp_required_if_logged_in(
redirect_field_name: str = "next",
login_url: str = settings.HOME_NOT_LOGGED_IN,
) -> Callable[
[Callable[Concatenate[HttpRequest, ParamT], HttpResponse]],
Callable[Concatenate[HttpRequest, ParamT], HttpResponse],
]:
"""
The reason we need to create this func... |
Prevent MIT mailing lists from signing up for Zulip | def email_is_not_mit_mailing_list(email: str) -> None:
"""Prevent MIT mailing lists from signing up for Zulip"""
address = Address(addr_spec=email)
if address.domain == "mit.edu":
# Check whether the user exists and can get mail.
try:
DNS.dnslookup(f"{address.username}.pobox.ns.a... |
This function verifies the request is allowed to make SCIM requests on this subdomain,
by checking the provided bearer token and ensuring it matches a scim client configured
for this subdomain in settings.SCIM_CONFIG.
Returns True if successful. | def validate_scim_bearer_token(request: HttpRequest) -> bool:
"""
This function verifies the request is allowed to make SCIM requests on this subdomain,
by checking the provided bearer token and ensuring it matches a scim client configured
for this subdomain in settings.SCIM_CONFIG.
Returns True if ... |
Changing a realm's subdomain is a highly disruptive operation,
because all existing clients will need to be updated to point to
the new URL. Further, requests to fetch data from existing event
queues will fail with an authentication error when this change
happens (because the old subdomain is no longer associated with... | def do_change_realm_subdomain(
realm: Realm,
new_subdomain: str,
*,
acting_user: Optional[UserProfile],
add_deactivated_redirect: bool = True,
) -> None:
"""Changing a realm's subdomain is a highly disruptive operation,
because all existing clients will need to be updated to point to
the... |
This function implements overrides for the default configuration
for new organizations when the administrator selected specific
organization types.
This substantially simplifies our /help/ advice for folks setting
up new organizations of these types. | def set_realm_permissions_based_on_org_type(realm: Realm) -> None:
"""This function implements overrides for the default configuration
for new organizations when the administrator selected specific
organization types.
This substantially simplifies our /help/ advice for folks setting
up new organiza... |
Create this realm's internal bots.
This function is idempotent; it does nothing for a bot that
already exists. | def setup_realm_internal_bots(realm: Realm) -> None:
"""Create this realm's internal bots.
This function is idempotent; it does nothing for a bot that
already exists.
"""
internal_bots = [
(bot["name"], bot["email_template"] % (settings.INTERNAL_BOT_DOMAIN,))
for bot in settings.REA... |
Give the user some messages in their feed, so that they can learn how to
use the home view in a realistic way after finishing the tutorial.
Mark the very most recent messages as unread. | def add_new_user_history(user_profile: UserProfile, streams: Iterable[Stream]) -> None:
"""
Give the user some messages in their feed, so that they can learn how to
use the home view in a realistic way after finishing the tutorial.
Mark the very most recent messages as unread.
"""
# Find recip... |
Called to have a user "take over" a "mirror dummy" user
(i.e. is_mirror_dummy=True) account when they sign up with the
same email address.
Essentially, the result should be as though we had created the
UserProfile just now with do_create_user, except that the mirror
dummy user may appear as the recipient or sender of ... | def do_activate_mirror_dummy_user(
user_profile: UserProfile, *, acting_user: Optional[UserProfile]
) -> None:
"""Called to have a user "take over" a "mirror dummy" user
(i.e. is_mirror_dummy=True) account when they sign up with the
same email address.
Essentially, the result should be as though we... |
Reactivate a user that had previously been deactivated | def do_reactivate_user(user_profile: UserProfile, *, acting_user: Optional[UserProfile]) -> None:
"""Reactivate a user that had previously been deactivated"""
if user_profile.is_mirror_dummy:
raise JsonableError(
_("Cannot activate a placeholder account; ask the user to sign up, instead.")
... |
Deleting a field will also delete the user profile data
associated with it in CustomProfileFieldValue model. | def do_remove_realm_custom_profile_field(realm: Realm, field: CustomProfileField) -> None:
"""
Deleting a field will also delete the user profile data
associated with it in CustomProfileFieldValue model.
"""
field.delete()
notify_realm_custom_profile_fields(realm) |
Send the confirmation/welcome e-mail to an invited user. | def do_send_confirmation_email(
invitee: PreregistrationUser,
referrer: UserProfile,
email_language: str,
invite_expires_in_minutes: Union[Optional[int], UnspecifiedValue] = UnspecifiedValue(),
) -> str:
"""
Send the confirmation/welcome e-mail to an invited user.
"""
activation_url = cr... |
An upper bound on the number of invites sent in the last `days` days | def estimate_recent_invites(realms: Collection[Realm] | QuerySet[Realm], *, days: int) -> int:
"""An upper bound on the number of invites sent in the last `days` days"""
recent_invites = RealmCount.objects.filter(
realm__in=realms,
property="invites_sent::day",
end_time__gte=timezone_now... |
Discourage using invitation emails as a vector for carrying spam. | def check_invite_limit(realm: Realm, num_invitees: int) -> None:
"""Discourage using invitation emails as a vector for carrying spam."""
msg = _(
"To protect users, Zulip limits the number of invitations you can send in one day. Because you have reached the limit, no invitations were sent."
)
if... |
Returns a list of dicts representing invitations that can be controlled by user_profile.
This isn't necessarily the same as all the invitations generated by the user, as administrators
can control also invitations that they did not themselves create. | def do_get_invites_controlled_by_user(user_profile: UserProfile) -> List[Dict[str, Any]]:
"""
Returns a list of dicts representing invitations that can be controlled by user_profile.
This isn't necessarily the same as all the invitations generated by the user, as administrators
can control also invitati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.