_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q247000 | BaseGraph.diff_aff | train | def diff_aff(self):
"""Symmetric diffusion affinity matrix
Return or calculate the symmetric diffusion affinity matrix
.. math:: A(x,y) = K(x,y) (d(x) d(y))^{-1/2}
where :math:`d` is the degrees (row sums of the kernel.)
Returns
-------
diff_aff : array-like,... | python | {
"resource": ""
} |
q247001 | BaseGraph.to_pygsp | train | def to_pygsp(self, **kwargs):
"""Convert to a PyGSP graph
For use only when the user means to create the graph using
the flag `use_pygsp=True`, and doesn't wish to recompute the kernel.
Creates a graphtools.graphs.TraditionalGraph with a precomputed
affinity matrix which also in... | python | {
"resource": ""
} |
q247002 | BaseGraph.to_igraph | train | def to_igraph(self, attribute="weight", **kwargs):
"""Convert to an igraph Graph
Uses the igraph.Graph.Weighted_Adjacency constructor
Parameters
----------
attribute : str, optional (default: "weight")
kwargs : additional arguments for igraph.Graph.Weighted_Adjacency
... | python | {
"resource": ""
} |
q247003 | BaseGraph.to_pickle | train | def to_pickle(self, path):
"""Save the current Graph to a pickle.
Parameters
----------
path : str
File path where the pickled object will be stored.
"""
if int(sys.version.split(".")[1]) < 7 and isinstance(self, pygsp.graphs.Graph):
# python 3.5,... | python | {
"resource": ""
} |
q247004 | PyGSPGraph._build_weight_from_kernel | train | def _build_weight_from_kernel(self, kernel):
"""Private method to build an adjacency matrix from
a kernel matrix
Just puts zeroes down the diagonal in-place, since the
kernel matrix is ultimately not stored.
Parameters | python | {
"resource": ""
} |
q247005 | DataGraph._check_extension_shape | train | def _check_extension_shape(self, Y):
"""Private method to check if new data matches `self.data`
Parameters
----------
Y : array-like, shape=[n_samples_y, n_features_y]
Input data
Returns
-------
Y : array-like, shape=[n_samples_y, n_pca]
... | python | {
"resource": ""
} |
q247006 | get_stop_times | train | def get_stop_times(feed: "Feed", date: Optional[str] = None) -> DataFrame:
"""
Return a subset of ``feed.stop_times``.
Parameters
----------
feed : Feed
date : string
YYYYMMDD date string restricting the output to trips active
on | python | {
"resource": ""
} |
q247007 | valid_str | train | def valid_str(x: str) -> bool:
"""
Return ``True`` if ``x`` is a non-blank string;
otherwise return ``False``.
"""
if isinstance(x, | python | {
"resource": ""
} |
q247008 | valid_date | train | def valid_date(x: str) -> bool:
"""
Retrun ``True`` if ``x`` is a valid YYYYMMDD date;
otherwise return ``False``.
"""
try:
| python | {
"resource": ""
} |
q247009 | valid_url | train | def valid_url(x: str) -> bool:
"""
Return ``True`` if ``x`` is a valid URL; otherwise return | python | {
"resource": ""
} |
q247010 | valid_email | train | def valid_email(x: str) -> bool:
"""
Return ``True`` if ``x`` is a valid email address; otherwise return
``False``.
"""
if isinstance(x, str) | python | {
"resource": ""
} |
q247011 | valid_color | train | def valid_color(x: str) -> bool:
"""
Return ``True`` if ``x`` a valid hexadecimal color string without
the leading hash; otherwise return ``False``.
"""
| python | {
"resource": ""
} |
q247012 | check_for_required_columns | train | def check_for_required_columns(
problems: List, table: str, df: DataFrame
) -> List:
"""
Check that the given GTFS table has the required columns.
Parameters
----------
problems : list
A four-tuple containing
1. A problem type (string) equal to ``'error'`` or ``'warning'``;
... | python | {
"resource": ""
} |
q247013 | check_for_invalid_columns | train | def check_for_invalid_columns(
problems: List, table: str, df: DataFrame
) -> List:
"""
Check for invalid columns in the given GTFS DataFrame.
Parameters
----------
problems : list
A four-tuple containing
1. A problem type (string) equal to ``'error'`` or ``'warning'``;
... | python | {
"resource": ""
} |
q247014 | check_table | train | def check_table(
problems: List,
table: str,
df: DataFrame,
condition,
message: str,
type_: str = "error",
) -> List:
"""
Check the given GTFS table for the given problem condition.
Parameters
----------
problems : list
A four-tuple containing
1. A problem t... | python | {
"resource": ""
} |
q247015 | check_column | train | def check_column(
problems: List,
table: str,
df: DataFrame,
column: str,
checker,
type_: str = "error",
*,
column_required: bool = True,
) -> List:
"""
Check the given column of the given GTFS with the given problem
checker.
Parameters
----------
problems : list... | python | {
"resource": ""
} |
q247016 | format_problems | train | def format_problems(
problems: List, *, as_df: bool = False
) -> Union[List, DataFrame]:
"""
Format the given problems list as a DataFrame.
Parameters
----------
problems : list
A four-tuple containing
1. A problem type (string) equal to ``'error'`` or ``'warning'``;
... | python | {
"resource": ""
} |
q247017 | validate | train | def validate(
feed: "Feed", *, as_df: bool = True, include_warnings: bool = True
) -> Union[List, DataFrame]:
"""
Check whether the given feed satisfies the GTFS.
Parameters
----------
feed : Feed
as_df : boolean
If ``True``, then return the resulting report as a DataFrame;
... | python | {
"resource": ""
} |
q247018 | summarize | train | def summarize(feed: "Feed", table: str = None) -> DataFrame:
"""
Return a DataFrame summarizing all GTFS tables in the given feed
or in the given table if specified.
Parameters
----------
feed : Feed
table : string
A GTFS table name, e.g. ``'stop_times'``
Returns
-------
... | python | {
"resource": ""
} |
q247019 | compute_feed_stats | train | def compute_feed_stats(
feed: "Feed", trip_stats: DataFrame, dates: List[str]
) -> DataFrame:
"""
Compute some feed stats for the given dates and trip stats.
Parameters
----------
feed : Feed
trip_stats : DataFrame
Trip stats to consider in the format output by
:func:`.trips... | python | {
"resource": ""
} |
q247020 | compute_feed_time_series | train | def compute_feed_time_series(
feed: "Feed", trip_stats: DataFrame, dates: List[str], freq: str = "5Min"
) -> DataFrame:
"""
Compute some feed stats in time series form for the given dates
and trip stats.
Parameters
----------
feed : Feed
trip_stats : DataFrame
Trip stats to cons... | python | {
"resource": ""
} |
q247021 | create_shapes | train | def create_shapes(feed: "Feed", *, all_trips: bool = False) -> "Feed":
"""
Given a feed, create a shape for every trip that is missing a
shape ID.
Do this by connecting the stops on the trip with straight lines.
Return the resulting feed which has updated shapes and trips
tables.
If ``all_t... | python | {
"resource": ""
} |
q247022 | compute_convex_hull | train | def compute_convex_hull(feed: "Feed") -> Polygon:
"""
Return a Shapely Polygon representing the convex hull formed by
the stops of the given Feed.
| python | {
"resource": ""
} |
q247023 | restrict_to_routes | train | def restrict_to_routes(feed: "Feed", route_ids: List[str]) -> "Feed":
"""
Build a new feed by restricting this one to only the stops,
trips, shapes, etc. used by the routes with the given list of
route IDs.
Return the resulting feed.
"""
# Initialize the new feed as the old feed.
# Restr... | python | {
"resource": ""
} |
q247024 | restrict_to_polygon | train | def restrict_to_polygon(feed: "Feed", polygon: Polygon) -> "Feed":
"""
Build a new feed by restricting this one to only the trips
that have at least one stop intersecting the given Shapely polygon,
then restricting stops, routes, stop times, etc. to those
associated with that subset of trips.
Re... | python | {
"resource": ""
} |
q247025 | is_active_trip | train | def is_active_trip(feed: "Feed", trip_id: str, date: str) -> bool:
"""
Return ``True`` if the ``feed.calendar`` or ``feed.calendar_dates``
says that the trip runs on the given date; return ``False``
otherwise.
Note that a trip that starts on date d, ends after 23:59:59, and
does not start again... | python | {
"resource": ""
} |
q247026 | get_trips | train | def get_trips(
feed: "Feed", date: Optional[str] = None, time: Optional[str] = None
) -> DataFrame:
"""
Return a subset of ``feed.trips``.
Parameters
----------
feed : Feed
date : string
YYYYMMDD date string
time : string
HH:MM:SS time string, possibly with HH > 23
... | python | {
"resource": ""
} |
q247027 | compute_busiest_date | train | def compute_busiest_date(feed: "Feed", dates: List[str]) -> str:
"""
Given a list of dates, return the first date that has the
maximum number of active trips.
Notes | python | {
"resource": ""
} |
q247028 | locate_trips | train | def locate_trips(feed: "Feed", date: str, times: List[str]) -> DataFrame:
"""
Return the positions of all trips active on the
given date and times
Parameters
----------
feed : Feed
date : string
YYYYMMDD date string
times : list
HH:MM:SS time strings, possibly with HH > ... | python | {
"resource": ""
} |
q247029 | trip_to_geojson | train | def trip_to_geojson(
feed: "Feed", trip_id: str, *, include_stops: bool = False
) -> Dict:
"""
Return a GeoJSON representation of the given trip, optionally with
its stops.
Parameters
----------
feed : Feed
trip_id : string
ID of trip in ``feed.trips``
include_stops : boolea... | python | {
"resource": ""
} |
q247030 | clean_column_names | train | def clean_column_names(df: DataFrame) -> DataFrame:
"""
Strip the whitespace from all column names in the given DataFrame
and return the result.
""" | python | {
"resource": ""
} |
q247031 | drop_zombies | train | def drop_zombies(feed: "Feed") -> "Feed":
"""
In the given "Feed", drop stops with no stop times,
trips with no stop times, shapes with no trips,
routes with no trips, and services with no trips, in that order.
Return the resulting "Feed".
"""
feed = feed.copy()
# Drop stops of location... | python | {
"resource": ""
} |
q247032 | clean_ids | train | def clean_ids(feed: "Feed") -> "Feed":
"""
In the given "Feed", strip whitespace from all string IDs and
then replace every remaining whitespace chunk with an underscore.
Return the resulting "Feed".
"""
# Alter feed inputs only, and build a new feed from them.
# The derived feed attributes,... | python | {
"resource": ""
} |
q247033 | aggregate_routes | train | def aggregate_routes(
feed: "Feed", by: str = "route_short_name", route_id_prefix: str = "route_"
) -> "Feed":
"""
Aggregate routes by route short name, say, and assign new route IDs.
Parameters
----------
feed : "Feed"
by : string
A column of ``feed.routes``
route_id_prefix : s... | python | {
"resource": ""
} |
q247034 | drop_invalid_columns | train | def drop_invalid_columns(feed: "Feed") -> "Feed":
"""
Drop all DataFrame columns of the given "Feed" that are not
listed in the GTFS.
Return the resulting new "Feed".
"""
feed = feed.copy()
for table, group in cs.GTFS_REF.groupby("table"):
f = getattr(feed, table)
if f is Non... | python | {
"resource": ""
} |
q247035 | get_routes | train | def get_routes(
feed: "Feed", date: Optional[str] = None, time: Optional[str] = None
) -> DataFrame:
"""
Return a subset of ``feed.routes``
Parameters
-----------
feed : Feed
date : string
YYYYMMDD date string restricting routes to only those active on
the date
time : st... | python | {
"resource": ""
} |
q247036 | compute_route_stats | train | def compute_route_stats(
feed: "Feed",
trip_stats_subset: DataFrame,
dates: List[str],
headway_start_time: str = "07:00:00",
headway_end_time: str = "19:00:00",
*,
split_directions: bool = False,
) -> DataFrame:
"""
Compute route stats for all the trips that lie in the given subset
... | python | {
"resource": ""
} |
q247037 | compute_route_time_series | train | def compute_route_time_series(
feed: "Feed",
trip_stats_subset: DataFrame,
dates: List[str],
freq: str = "5Min",
*,
split_directions: bool = False,
) -> DataFrame:
"""
Compute route stats in time series form for the trips that lie in
the trip stats subset and that start on the given ... | python | {
"resource": ""
} |
q247038 | build_route_timetable | train | def build_route_timetable(
feed: "Feed", route_id: str, dates: List[str]
) -> DataFrame:
"""
Return a timetable for the given route and dates.
Parameters
----------
feed : Feed
route_id : string
ID of a route in ``feed.routes``
dates : string or list
A YYYYMMDD date stri... | python | {
"resource": ""
} |
q247039 | route_to_geojson | train | def route_to_geojson(
feed: "Feed",
route_id: str,
date: Optional[str] = None,
*,
include_stops: bool = False,
) -> Dict:
"""
Return a GeoJSON rendering of the route and, optionally, its stops.
Parameters
----------
feed : Feed
route_id : string
ID of a route in ``fe... | python | {
"resource": ""
} |
q247040 | build_geometry_by_shape | train | def build_geometry_by_shape(
feed: "Feed",
shape_ids: Optional[List[str]] = None,
*,
use_utm: bool = False,
) -> Dict:
"""
Return a dictionary with structure shape_id -> Shapely LineString
of shape.
Parameters
----------
feed : Feed
shape_ids : list
IDs of shapes in ... | python | {
"resource": ""
} |
q247041 | append_dist_to_shapes | train | def append_dist_to_shapes(feed: "Feed") -> "Feed":
"""
Calculate and append the optional ``shape_dist_traveled`` field in
``feed.shapes`` in terms of the distance units ``feed.dist_units``.
Return the resulting Feed.
Notes
-----
- As a benchmark, using this function on `this Portland feed
... | python | {
"resource": ""
} |
q247042 | geometrize_shapes | train | def geometrize_shapes(
shapes: DataFrame, *, use_utm: bool = False
) -> DataFrame:
"""
Given a GTFS shapes DataFrame, convert it to a GeoPandas
GeoDataFrame and return the result.
The result has a ``'geometry'`` column of WGS84 LineStrings
instead of the columns ``'shape_pt_sequence'``, ``'shape... | python | {
"resource": ""
} |
q247043 | get_segment_length | train | def get_segment_length(
linestring: LineString, p: Point, q: Optional[Point] = None
) -> float:
"""
Given a Shapely linestring and two Shapely points,
project the points onto the linestring, and return the distance
along the linestring between the two points.
If ``q is None``, then return the di... | python | {
"resource": ""
} |
q247044 | get_convert_dist | train | def get_convert_dist(
dist_units_in: str, dist_units_out: str
) -> Callable[[float], float]:
"""
Return a function of the form
distance in the units ``dist_units_in`` ->
distance in the units ``dist_units_out``
Only supports distance units in :const:`constants.DIST_UNITS`.
"""
di, ... | python | {
"resource": ""
} |
q247045 | almost_equal | train | def almost_equal(f: DataFrame, g: DataFrame) -> bool:
"""
Return ``True`` if and only if the given DataFrames are equal after
sorting their columns names, sorting their values, and
reseting their indices.
"""
if f.empty or g.empty:
return f.equals(g)
else:
# Put in canonical ... | python | {
"resource": ""
} |
q247046 | linestring_to_utm | train | def linestring_to_utm(linestring: LineString) -> LineString:
"""
Given a Shapely LineString in WGS84 coordinates,
convert it to the appropriate UTM coordinates.
If ``inverse``, then do the inverse. | python | {
"resource": ""
} |
q247047 | get_active_trips_df | train | def get_active_trips_df(trip_times: DataFrame) -> DataFrame:
"""
Count the number of trips in ``trip_times`` that are active
at any given time.
Parameters
----------
trip_times : DataFrame
Contains columns
- start_time: start time of the trip in seconds past midnight
- ... | python | {
"resource": ""
} |
q247048 | combine_time_series | train | def combine_time_series(
time_series_dict: Dict, kind: str, *, split_directions: bool = False
) -> DataFrame:
"""
Combine the many time series DataFrames in the given dictionary
into one time series DataFrame with hierarchical columns.
Parameters
----------
time_series_dict : dictionary
... | python | {
"resource": ""
} |
q247049 | compute_stop_stats_base | train | def compute_stop_stats_base(
stop_times_subset: DataFrame,
trip_subset: DataFrame,
headway_start_time: str = "07:00:00",
headway_end_time: str = "19:00:00",
*,
split_directions: bool = False,
) -> DataFrame:
"""
Given a subset of a stop times DataFrame and a subset of a trips
DataFra... | python | {
"resource": ""
} |
q247050 | compute_stop_time_series_base | train | def compute_stop_time_series_base(
stop_times_subset: DataFrame,
trip_subset: DataFrame,
freq: str = "5Min",
date_label: str = "20010101",
*,
split_directions: bool = False,
) -> DataFrame:
"""
Given a subset of a stop times DataFrame and a subset of a trips
DataFrame, return a DataF... | python | {
"resource": ""
} |
q247051 | get_stops | train | def get_stops(
feed: "Feed",
date: Optional[str] = None,
trip_id: Optional[str] = None,
route_id: Optional[str] = None,
*,
in_stations: bool = False,
) -> DataFrame:
"""
Return a section of ``feed.stops``.
Parameters
-----------
feed : Feed
date : string
YYYYMMDD... | python | {
"resource": ""
} |
q247052 | build_geometry_by_stop | train | def build_geometry_by_stop(
feed: "Feed",
stop_ids: Optional[List[str]] = None,
*,
use_utm: bool = False,
) -> Dict:
"""
Return a dictionary with the structure
stop_id -> Shapely Point with coordinates of the stop.
Parameters
----------
feed : Feed
use_utm : boolean
... | python | {
"resource": ""
} |
q247053 | compute_stop_stats | train | def compute_stop_stats(
feed: "Feed",
dates: List[str],
stop_ids: Optional[List[str]] = None,
headway_start_time: str = "07:00:00",
headway_end_time: str = "19:00:00",
*,
split_directions: bool = False,
) -> DataFrame:
"""
Compute stats for all stops for the given dates.
Optional... | python | {
"resource": ""
} |
q247054 | build_stop_timetable | train | def build_stop_timetable(
feed: "Feed", stop_id: str, dates: List[str]
) -> DataFrame:
"""
Return a DataFrame containing the timetable for the given stop ID
and dates.
Parameters
----------
feed : Feed
stop_id : string
ID of the stop for which to build the timetable
dates : ... | python | {
"resource": ""
} |
q247055 | get_stops_in_polygon | train | def get_stops_in_polygon(
feed: "Feed", polygon: Polygon, geo_stops=None
) -> DataFrame:
"""
Return the slice of ``feed.stops`` that contains all stops that lie
within the given Shapely Polygon object that is specified in
WGS84 coordinates.
Parameters
----------
feed : Feed
polygon ... | python | {
"resource": ""
} |
q247056 | geometrize_stops | train | def geometrize_stops(stops: List[str], *, use_utm: bool = False) -> DataFrame:
"""
Given a stops DataFrame, convert it to a GeoPandas GeoDataFrame
and return the result.
Parameters
----------
stops : DataFrame
A GTFS stops table
use_utm : boolean
If ``True``, then convert th... | python | {
"resource": ""
} |
q247057 | map_stops | train | def map_stops(
feed: "Feed", stop_ids: List[str], stop_style: Dict = STOP_STYLE
):
"""
Return a Folium map showing the given stops.
Parameters
----------
feed : Feed
stop_ids : list
IDs of trips in ``feed.stops``
stop_style: dictionary
Folium CircleMarker parameters to u... | python | {
"resource": ""
} |
q247058 | get_dates | train | def get_dates(feed: "Feed", *, as_date_obj: bool = False) -> List[str]:
"""
Return a list of dates for which the given "Feed" is valid, which
could be the empty list if the "Feed" has no calendar information.
Parameters
----------
feed : "Feed"
as_date_obj : boolean
If ``True``, the... | python | {
"resource": ""
} |
q247059 | write_gtfs | train | def write_gtfs(feed: "Feed", path: Path, ndigits: int = 6) -> None:
"""
Export the given feed to the given path.
If the path end in '.zip', then write the feed as a zip archive.
Otherwise assume the path is a directory, and write the feed as a
collection of CSV files to that directory, creating the ... | python | {
"resource": ""
} |
q247060 | Feed.trips | train | def trips(self, val):
"""
Update ``self._trips_i`` if ``self.trips`` changes.
"""
self._trips = val
if val is not None and not val.empty: | python | {
"resource": ""
} |
q247061 | Feed.calendar | train | def calendar(self, val):
"""
Update ``self._calendar_i``if ``self.calendar`` changes.
"""
self._calendar = val
if val is not None and not val.empty: | python | {
"resource": ""
} |
q247062 | Feed.calendar_dates | train | def calendar_dates(self, val):
"""
Update ``self._calendar_dates_g``
if ``self.calendar_dates`` changes.
"""
self._calendar_dates = val | python | {
"resource": ""
} |
q247063 | Feed.copy | train | def copy(self) -> "Feed":
"""
Return a copy of this feed, that is, a feed with all the same
attributes.
"""
other = Feed(dist_units=self.dist_units)
for key in set(cs.FEED_ATTRS) - set(["dist_units"]):
value = getattr(self, key)
| python | {
"resource": ""
} |
q247064 | DjangoCacheBackend._encode_content | train | def _encode_content(self, uri, content):
"""
Join node uri and content as string and convert to bytes to ensure no pickling in memcached.
"""
if content is None:
| python | {
"resource": ""
} |
q247065 | DjangoCacheBackend._decode_content | train | def _decode_content(self, content):
"""
Split node string to uri and content and convert back to unicode.
"""
content = smart_unicode(content)
| python | {
"resource": ""
} |
q247066 | render_node | train | def render_node(node, context=None, edit=True):
"""
Render node as html for templates, with edit tagging.
"""
output = node.render(**context or {}) or u''
if edit:
| python | {
"resource": ""
} |
q247067 | APIView.get_post_data | train | def get_post_data(self, request):
"""
Collect and merge post parameters with multipart files.
"""
params = dict(request.POST)
params.update(request.FILES)
data = defaultdict(dict)
# Split data and meta parameters
for param in sorted(params.keys()):
... | python | {
"resource": ""
} |
q247068 | NodeApi.get | train | def get(self, request, uri):
"""
Return published node or specified version.
JSON Response:
{uri: x, content: y}
"""
uri = self.decode_uri(uri)
node = cio.get(uri, lazy=False)
if node.content is None:
| python | {
"resource": ""
} |
q247069 | NodeApi.post | train | def post(self, request, uri):
"""
Set node data for uri, return rendered content.
JSON Response:
{uri: x, content: y}
"""
uri = self.decode_uri(uri)
data, meta = self.get_post_data(request)
meta['author'] = | python | {
"resource": ""
} |
q247070 | NodeApi.delete | train | def delete(self, request, uri):
"""
Delete versioned uri and return empty text response on success.
"""
uri = self.decode_uri(uri)
uris = cio.delete(uri)
| python | {
"resource": ""
} |
q247071 | PublishApi.put | train | def put(self, request, uri):
"""
Publish versioned uri.
JSON Response:
{uri: x, content: y}
| python | {
"resource": ""
} |
q247072 | RevisionsApi.get | train | def get(self, request, uri):
"""
List uri revisions.
JSON Response:
[[uri, state], ...]
"""
uri = self.decode_uri(uri)
revisions | python | {
"resource": ""
} |
q247073 | LoadApi.get | train | def get(self, request, uri):
"""
Load raw node source from storage.
JSON Response:
| python | {
"resource": ""
} |
q247074 | RenderApi.post | train | def post(self, request, ext):
"""
Render data for plugin and return text response.
"""
try:
plugin = plugins.get(ext)
data, meta = self.get_post_data(request)
data = plugin.load(data)
except UnknownPlugin: | python | {
"resource": ""
} |
q247075 | set_checklists_status | train | def set_checklists_status(auth, args):
"""Set display_checklist status, toggling from cli flag"""
global checklists_on
if auth['checklists'] == "true":
checklists_on = True
else:
checklists_on = False
# reverse | python | {
"resource": ""
} |
q247076 | build_wsgi_environ_from_event | train | def build_wsgi_environ_from_event(event):
"""Create a WSGI environment from the proxy integration event."""
params = event.get('queryStringParameters')
environ = EnvironBuilder(method=event.get('httpMethod') or 'GET',
path=event.get('path') or '/',
h... | python | {
"resource": ""
} |
q247077 | wsgi_handler | train | def wsgi_handler(event, context, app, logger):
"""lambda handler function.
This function runs the WSGI app with it and collects its response, then
translates the response back into the format expected by the API Gateway
proxy integration.
"""
environ = build_wsgi_environ_from_event(event)
w... | python | {
"resource": ""
} |
q247078 | assume_role | train | def assume_role(credentials, account, role):
"""Use FAWS provided credentials to assume defined role."""
sts = boto3.client(
'sts',
aws_access_key_id=credentials['accessKeyId'],
aws_secret_access_key=credentials['secretAccessKey'],
aws_session_token=credentials['sessionToken'],
... | python | {
"resource": ""
} |
q247079 | get_environment | train | def get_environment(config, stage):
"""Find default environment name in stage."""
stage_data = get_stage_data(stage, config.get('stages', {}))
if not stage_data:
sys.exit(NO_STAGE_DATA.format(stage))
| python | {
"resource": ""
} |
q247080 | get_account | train | def get_account(config, environment, stage=None):
"""Find environment name in config object and return AWS account."""
if environment is None and stage:
environment = get_environment(config, stage)
account = None
for env in config.get('environments', []):
if env.get('name') == environmen... | python | {
"resource": ""
} |
q247081 | get_aws_creds | train | def get_aws_creds(account, tenant, token):
"""Get AWS account credentials to enable access to AWS.
Returns a time bound set of AWS credentials.
"""
url = (FAWS_API_URL.format(account))
headers = {
'X-Auth-Token': token,
'X-Tenant-Id': tenant,
}
response = requests.post(url, ... | python | {
"resource": ""
} |
q247082 | get_config | train | def get_config(config_file):
"""Get config file and parse YAML into dict."""
config_path = os.path.abspath(config_file)
| python | {
"resource": ""
} |
q247083 | get_rackspace_token | train | def get_rackspace_token(username, apikey):
"""Get Rackspace Identity token.
Login to Rackspace with cloud account and api key from environment vars.
Returns dict of the token and tenant id.
"""
auth_params = {
"auth": {
"RAX-KSKEY:apiKeyCredentials": {
"username"... | python | {
"resource": ""
} |
q247084 | validate_args | train | def validate_args(args):
"""Validate command-line arguments."""
if not any([args.environment, args.stage, args.account]):
sys.exit(NO_ACCT_OR_ENV_ERROR)
if args.environment and args.account:
| python | {
"resource": ""
} |
q247085 | set_default_timeout | train | def set_default_timeout(timeout=None, connect_timeout=None, read_timeout=None):
"""
The purpose of this function is to install default socket timeouts and
retry policy for requests calls. Any requests issued through the requests
wrappers defined in this module will have these automatically set, unless
... | python | {
"resource": ""
} |
q247086 | Session.request | train | def request(self, method, url, **kwargs):
"""
Send a request.
If timeout is not explicitly given, use the default timeouts.
"""
if 'timeout' not in kwargs:
if self.timeout is not None:
kwargs['timeout'] = self.timeout
| python | {
"resource": ""
} |
q247087 | _has_streamhandler | train | def _has_streamhandler(logger, level=None, fmt=LOG_FORMAT,
stream=DEFAULT_STREAM):
"""Check the named logger for an appropriate existing StreamHandler.
This only returns True if a StreamHandler that exaclty matches
our specification is found. If other StreamHandlers are seen,
we ... | python | {
"resource": ""
} |
q247088 | inject_request_ids_into_environment | train | def inject_request_ids_into_environment(func):
"""Decorator for the Lambda handler to inject request IDs for logging."""
@wraps(func)
def wrapper(event, context):
# This might not always be an API Gateway event, so only log the
# request ID, if it looks like to be coming from there.
... | python | {
"resource": ""
} |
q247089 | add_request_ids_from_environment | train | def add_request_ids_from_environment(logger, name, event_dict):
"""Custom processor adding request IDs to the log event, if available."""
if ENV_APIG_REQUEST_ID in os.environ:
event_dict['api_request_id'] = os.environ[ENV_APIG_REQUEST_ID]
if | python | {
"resource": ""
} |
q247090 | get_logger | train | def get_logger(name=None, level=None, stream=DEFAULT_STREAM,
clobber_root_handler=True, logger_factory=None,
wrapper_class=None):
"""Configure and return a logger with structlog and stdlib."""
_configure_logger(
logger_factory=logger_factory,
wrapper_class=wrapper_c... | python | {
"resource": ""
} |
q247091 | validate | train | def validate(token):
"""Validate token and return auth context."""
token_url = TOKEN_URL_FMT.format(token=token)
headers = {
'x-auth-token': token,
'accept': 'application/json',
} | python | {
"resource": ""
} |
q247092 | _fullmatch | train | def _fullmatch(pattern, text, *args, **kwargs):
"""re.fullmatch is not available on Python<3.4."""
match = re.match(pattern, | python | {
"resource": ""
} |
q247093 | _read_config_file | train | def _read_config_file(args):
"""Decrypt config file, returns a tuple with stages and config."""
stage = args.stage
with open(args.config, 'rt') as f:
config = yaml.safe_load(f.read())
STATE['stages'] = config['stages']
| python | {
"resource": ""
} |
q247094 | get_trace_id | train | def get_trace_id():
"""Parse X-Ray Trace ID environment variable.
The value looks something like this:
Root=1-5901e3bc-8da3814a5f3ccbc864b66ecc;Parent=328f72132deac0ce;Sampled=1
`Root` is the main X-Ray Trace ID, `Parent` points to the top-level
segment, and `Sampled` shows whether the curren... | python | {
"resource": ""
} |
q247095 | get_xray_daemon | train | def get_xray_daemon():
"""Parse X-Ray Daemon address environment variable.
If the environment variable is not set, raise an exception to signal that
we're unable to send data | python | {
"resource": ""
} |
q247096 | send_segment_document_to_xray_daemon | train | def send_segment_document_to_xray_daemon(segment_document):
"""Format and send document to the X-Ray Daemon."""
try:
xray_daemon = get_xray_daemon()
except XRayDaemonNotFoundError:
LOGGER.error('X-Ray Daemon not running, skipping send')
return
message = u'{header}\n{document}'.f... | python | {
"resource": ""
} |
q247097 | send_subsegment_to_xray_daemon | train | def send_subsegment_to_xray_daemon(subsegment_id, parent_id,
start_time, end_time=None, name=None,
namespace='remote', extra_data=None):
"""High level function to send data to the X-Ray Daemon.
If `end_time` is set to `None` (which is the de... | python | {
"resource": ""
} |
q247098 | generic_xray_wrapper | train | def generic_xray_wrapper(wrapped, instance, args, kwargs, name, namespace,
metadata_extractor,
error_handling_type=ERROR_HANDLING_GENERIC):
"""Wrapper function around existing calls to send traces to X-Ray.
`wrapped` is the original function, `instance` is the ... | python | {
"resource": ""
} |
q247099 | extract_function_metadata | train | def extract_function_metadata(wrapped, instance, args, kwargs, return_value):
"""Stash the `args` and `kwargs` into the metadata of the subsegment."""
LOGGER.debug(
'Extracting function call metadata',
args=args,
kwargs=kwargs,
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.