_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q249800 | action_findip | train | def action_findip(reader, *args):
"""Find Flow Log records involving a specific IP or IPs."""
target_ips = set(args)
for record in reader:
| python | {
"resource": ""
} |
q249801 | action_aggregate | train | def action_aggregate(reader, *args):
"""Aggregate flow records by 5-tuple and print a tab-separated stream"""
all_aggregated = aggregated_records(reader)
first_row = next(all_aggregated)
keys = sorted(first_row.keys())
print(*keys, sep='\t')
| python | {
"resource": ""
} |
q249802 | get_poly_area_geo | train | def get_poly_area_geo(poly):
"""
Calculates the area in meters squared of the individual polygon
"""
minx, miny, maxx, maxy = poly.bounds
# reproject polygon to get area
reprojected_for_area = Proj("+proj=aea +lat_1={0} +lat_1={1} "
"+lat_0={2} +lon_0={3}"
... | python | {
"resource": ""
} |
q249803 | CreateWeightTableECMWF | train | def CreateWeightTableECMWF(in_ecmwf_nc,
in_catchment_shapefile,
river_id,
in_connectivity_file,
out_weight_table,
area_id=None,
file_geodatabase=None):
""... | python | {
"resource": ""
} |
q249804 | CreateWeightTableLDAS | train | def CreateWeightTableLDAS(in_ldas_nc,
in_nc_lon_var,
in_nc_lat_var,
in_catchment_shapefile,
river_id,
in_connectivity_file,
out_weight_table,
... | python | {
"resource": ""
} |
q249805 | generate_single_seasonal_average | train | def generate_single_seasonal_average(args):
"""
This function calculates the seasonal average for a single day of the year
for all river segments
"""
qout_file = args[0]
seasonal_average_file = args[1]
day_of_year = args[2]
mp_lock = args[3]
min_day = day_of_year - 3
max_day = d... | python | {
"resource": ""
} |
q249806 | generate_seasonal_averages | train | def generate_seasonal_averages(qout_file, seasonal_average_file,
num_cpus=multiprocessing.cpu_count()):
"""
This function loops through a CF compliant rapid streamflow
file to produce a netCDF file with a seasonal average for
365 days a year
"""
with RAPIDDataset(q... | python | {
"resource": ""
} |
q249807 | open_shapefile | train | def open_shapefile(shapefile_path, file_geodatabase=None):
"""Opens a shapefile using either a shapefile path
or a file geodatabase
"""
if file_geodatabase:
gdb_driver = ogr.GetDriverByName("OpenFileGDB")
ogr_shapefile = gdb_driver.Open(file_geodatabase)
| python | {
"resource": ""
} |
q249808 | RAPID._get_cygwin_path | train | def _get_cygwin_path(self, windows_path):
"""
Convert windows path to cygpath
"""
conv_cmd = [os.path.join(self._cygwin_bin_location, "cygpath.exe"),
"-u", windows_path]
process = Popen(conv_cmd,
| python | {
"resource": ""
} |
q249809 | RAPID._create_symlink_cygwin | train | def _create_symlink_cygwin(self, initial_path, final_path):
"""
Use cygqin to generate symbolic link
"""
symlink_cmd = [os.path.join(self._cygwin_bin_location, "ln.exe"),
"-s", self._get_cygwin_path(initial_path),
self._get_cygwin_path(final_... | python | {
"resource": ""
} |
q249810 | RAPID._dos2unix_cygwin | train | def _dos2unix_cygwin(self, file_path):
"""
Use cygwin to convert file to unix format
"""
dos2unix_cmd = \
[os.path.join(self._cygwin_bin_location, "dos2unix.exe"),
self._get_cygwin_path(file_path)]
| python | {
"resource": ""
} |
q249811 | RAPID.update_reach_number_data | train | def update_reach_number_data(self):
"""
Update the reach number data for the namelist based on input files.
.. warning:: You need to make sure you set *rapid_connect_file*
and *riv_bas_id_file* before running this function.
Example:
.. code:: python
... | python | {
"resource": ""
} |
q249812 | RAPID.generate_namelist_file | train | def generate_namelist_file(self, rapid_namelist_file):
"""
Generate rapid_namelist file.
Parameters
----------
rapid_namelist_file: str
Path of namelist file to generate from
parameters added to the RAPID manager.
"""
log("Generating RAPID... | python | {
"resource": ""
} |
q249813 | RAPID.update_namelist_file | train | def update_namelist_file(self, rapid_namelist_file,
new_namelist_file=None):
"""
Update existing namelist file with new parameters
Parameters
----------
rapid_namelist_file: str
Path of namelist file to use in the simulation. It will be
... | python | {
"resource": ""
} |
q249814 | RAPID.generate_qinit_from_past_qout | train | def generate_qinit_from_past_qout(self, qinit_file, time_index=-1,
out_datetime=None):
"""
Generate qinit from a RAPID qout file
Parameters
----------
qinit_file: str
Path to output qinit_file.
time_index: int, optional
... | python | {
"resource": ""
} |
q249815 | RAPID.generate_seasonal_intitialization | train | def generate_seasonal_intitialization(
self,
qinit_file,
datetime_start_initialization=datetime.datetime.utcnow()
):
"""This creates a seasonal qinit file from a RAPID qout file. This
requires a simulation Qout file with a longer time period of record and
to be CF com... | python | {
"resource": ""
} |
q249816 | CreateInflowFileFromGriddedRunoff.read_in_weight_table | train | def read_in_weight_table(self, in_weight_table):
"""
Read in weight table
"""
print("Reading the weight table...")
with open_csv(in_weight_table, "r") as csvfile:
reader = csv.reader(csvfile)
header_row = next(reader)
# check number of ... | python | {
"resource": ""
} |
q249817 | CreateInflowFileFromGriddedRunoff._write_lat_lon | train | def _write_lat_lon(data_out_nc, rivid_lat_lon_z_file):
"""Add latitude and longitude each netCDF feature
Lookup table is a CSV file with rivid, Lat, Lon, columns.
Columns must be in that order and these must be the first
three columns.
"""
# only add if user adds
... | python | {
"resource": ""
} |
q249818 | filter_nan | train | def filter_nan(s, o):
"""
this functions removed the data from simulated and observed data
whereever the observed data contains nan
this is used by all other functions, otherwise they will produce nan as
output
"""
data = | python | {
"resource": ""
} |
q249819 | find_goodness_of_fit | train | def find_goodness_of_fit(rapid_qout_file, reach_id_file, observed_file,
out_analysis_file, daily=False):
"""
Finds the goodness of fit comparing observed streamflow in a rapid Qout
file with simulated flows in a csv file.
Parameters
----------
rapid_qout_file: str
... | python | {
"resource": ""
} |
q249820 | find_goodness_of_fit_csv | train | def find_goodness_of_fit_csv(observed_simulated_file, out_file=None):
"""
Finds the goodness of fit comparing observed and simulated flows
In the file, the first column is the observed flows and the
second column is the simulated flows.
Example::
33.5, 77.2
34.7, 73.0
Paramete... | python | {
"resource": ""
} |
q249821 | log | train | def log(message, severity="INFO", print_debug=True):
"""Logs, prints, or raises a message.
Arguments:
message -- message to report
severity -- string of one of these values:
CRITICAL|ERROR|WARNING|INFO|DEBUG
| python | {
"resource": ""
} |
q249822 | csv_to_list | train | def csv_to_list(csv_file, delimiter=','):
"""
Reads in a CSV file and returns the contents as list,
where every row is stored as a sublist, and each element
in the sublist represents 1 cell in the table.
"""
with open_csv(csv_file) as csv_con:
| python | {
"resource": ""
} |
q249823 | add_latlon_metadata | train | def add_latlon_metadata(lat_var, lon_var):
"""Adds latitude and longitude metadata"""
lat_var.long_name = 'latitude'
lat_var.standard_name = 'latitude'
lat_var.units = 'degrees_north'
lat_var.axis = 'Y'
| python | {
"resource": ""
} |
q249824 | generate_inflows_from_runoff | train | def generate_inflows_from_runoff(args):
"""
prepare runoff inflow file for rapid
"""
runoff_file_list = args[0]
file_index_list = args[1]
weight_table_file = args[2]
grid_type = args[3]
rapid_inflow_file = args[4]
rapid_inflow_tool = args[5]
mp_lock = args[6]
time_start_all ... | python | {
"resource": ""
} |
q249825 | determine_start_end_timestep | train | def determine_start_end_timestep(lsm_file_list,
file_re_match=None,
file_datetime_pattern=None,
expected_time_step=None,
lsm_grid_info=None):
"""
Determine the start and end date f... | python | {
"resource": ""
} |
q249826 | _get_voronoi_centroid_array | train | def _get_voronoi_centroid_array(lsm_lat_array, lsm_lon_array, extent):
"""
This function generates a voronoi centroid point
list from arrays of latitude and longitude
"""
YMin = extent[2]
YMax = extent[3]
XMin = extent[0]
XMax = extent[1]
ptList = []
if (lsm_lat_array.ndim == 2)... | python | {
"resource": ""
} |
q249827 | _get_voronoi_poly_points | train | def _get_voronoi_poly_points(vert_index_list, voronoi_vertices,
voronoi_centroid):
"""
This function returns the corner points for a
polygon from scipy voronoi information
"""
voronoi_poly_points = []
if -1 not in vert_index_list and len(vert_index_list) > 3:
... | python | {
"resource": ""
} |
q249828 | pointsToVoronoiGridShapefile | train | def pointsToVoronoiGridShapefile(lat, lon, vor_shp_path, extent=None):
"""
Converts points to shapefile grid via voronoi
"""
voronoi_centroids = _get_voronoi_centroid_array(lat, lon, extent)
# set-up output polygon shp
log("Creating output polygon shp {0}"
.format(os.path.basename(vor_s... | python | {
"resource": ""
} |
q249829 | pointsToVoronoiGridArray | train | def pointsToVoronoiGridArray(lat, lon, extent=None):
"""
Converts points to grid array via voronoi
"""
voronoi_centroids = _get_voronoi_centroid_array(lat, lon, extent)
# find nodes surrounding polygon centroid
# sort nodes in counterclockwise order
# create polygon perimeter through nodes
... | python | {
"resource": ""
} |
q249830 | ConvertRAPIDOutputToCF._generate_time_values | train | def _generate_time_values(self):
"""
Generates time values for out nc file
"""
# Populate time values
log('writing times', 'INFO')
d1970 = datetime(1970, 1, 1, tzinfo=utc)
time_array = [[int((self.start_datetime - d1970).total_seconds())]]
dateti... | python | {
"resource": ""
} |
q249831 | ConvertRAPIDOutputToCF.convert | train | def convert(self):
"""
Copies data from RAPID netCDF output to a CF-compliant netCDF file.
"""
try:
log('Processing %s ...' % self.rapid_output_file_list[0])
time_start_conversion = datetime.utcnow()
# Validate the raw netCDF file
... | python | {
"resource": ""
} |
q249832 | CreateMuskingumKFile | train | def CreateMuskingumKFile(lambda_k,
in_kfac_file,
out_k_file):
"""
Creates muskingum k file from kfac file.
Parameters
----------
lambda_k: float
The value for lambda given from RAPID after the calibration process.
If no calibration h... | python | {
"resource": ""
} |
q249833 | CreateMuskingumXFileFromDranageLine | train | def CreateMuskingumXFileFromDranageLine(in_drainage_line,
x_id,
out_x_file,
file_geodatabase=None):
"""
Create muskingum X file from drainage line.
Parameters
----------
in_draina... | python | {
"resource": ""
} |
q249834 | CreateConstMuskingumXFile | train | def CreateConstMuskingumXFile(x_value,
in_connectivity_file,
out_x_file):
"""
Create muskingum X file from value that is constant all the way through
for each river segment.
Parameters
----------
x_value: float
Value for the mu... | python | {
"resource": ""
} |
q249835 | StreamIDNextDownIDToConnectivity | train | def StreamIDNextDownIDToConnectivity(stream_id_array,
next_down_id_array,
out_csv_file):
"""
Creates RAPID connect file from stream_id array and next down id array
"""
list_all = []
max_count_upstream = 0
for hydroid in n... | python | {
"resource": ""
} |
q249836 | CreateNetworkConnectivity | train | def CreateNetworkConnectivity(in_drainage_line,
river_id,
next_down_id,
out_connectivity_file,
file_geodatabase=None):
"""
Creates Network Connectivity input CSV file for RAPID
based on th... | python | {
"resource": ""
} |
q249837 | CreateNetworkConnectivityTauDEMTree | train | def CreateNetworkConnectivityTauDEMTree(network_connectivity_tree_file,
out_csv_file):
"""
Creates Network Connectivity input CSV file for RAPID
based on the TauDEM network connectivity tree file
"""
stream_id_array = []
next_down_id_array = []
with op... | python | {
"resource": ""
} |
q249838 | CreateNetworkConnectivityNHDPlus | train | def CreateNetworkConnectivityNHDPlus(in_drainage_line,
out_connectivity_file,
file_geodatabase=None):
"""
Creates Network Connectivity input CSV file for RAPID
based on the NHDPlus drainage lines with
COMID, FROMNODE, TONODE, and ... | python | {
"resource": ""
} |
q249839 | CreateSubsetFile | train | def CreateSubsetFile(in_drainage_line,
river_id,
out_riv_bas_id_file,
file_geodatabase=None):
"""
Creates River Basin ID subset input CSV file for RAPID
based on the Drainage Line shapefile with river ID and
next downstream ID fields
Pa... | python | {
"resource": ""
} |
q249840 | CreateAllStaticECMWFFiles | train | def CreateAllStaticECMWFFiles(in_catchment,
catchment_river_id,
rapid_output_folder,
rapid_connect_file,
file_geodatabase=None
):
"""
This creates all of the ECMW... | python | {
"resource": ""
} |
q249841 | CreateAllStaticECMWFRAPIDFiles | train | def CreateAllStaticECMWFRAPIDFiles(in_drainage_line,
river_id,
length_id,
slope_id,
next_down_id,
in_catchment,
... | python | {
"resource": ""
} |
q249842 | compare_qout_files | train | def compare_qout_files(dataset1_path, dataset2_path):
"""
This function compares the output of RAPID Qout and tells you where
they are different.
"""
qout_same = False
d1 = RAPIDDataset(dataset1_path)
d2 = RAPIDDataset(dataset2_path)
if len(d1.get_river_id_array()) != len(d2.get_river_... | python | {
"resource": ""
} |
q249843 | RAPIDDataset.is_time_variable_valid | train | def is_time_variable_valid(self):
"""
This function returns whether or not the time variable
is valid.
Returns
-------
boolean
True if the time variable is valid, otherwise false.
Example::
from RAPIDpy import RAPIDDataset
... | python | {
"resource": ""
} |
q249844 | RAPIDDataset.get_time_array | train | def get_time_array(self,
datetime_simulation_start=None,
simulation_time_step_seconds=None,
return_datetime=False,
time_index_array=None):
"""
This method extracts or generates an array of time.
The new v... | python | {
"resource": ""
} |
q249845 | RAPIDDataset.get_time_index_range | train | def get_time_index_range(self,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None):
"""
Generates a time... | python | {
"resource": ""
} |
q249846 | RAPIDDataset.get_river_index | train | def get_river_index(self, river_id):
"""
This method retrieves the river index in the netCDF
dataset corresponding to the river ID.
Parameters
----------
river_id: int
The ID of the river segment.
Returns
-------
int:
The ... | python | {
"resource": ""
} |
q249847 | RAPIDDataset.get_subset_riverid_index_list | train | def get_subset_riverid_index_list(self, river_id_list):
"""
Gets the subset riverid_list from the netcdf file
Optional returns include the list of valid river ids in the dataset
as well as a list of missing rive rids
Parameters
----------
river_id_list: list or :... | python | {
"resource": ""
} |
q249848 | RAPIDDataset.get_qout | train | def get_qout(self,
river_id_array=None,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None,
time_index_array=None,
daily=False,
... | python | {
"resource": ""
} |
q249849 | RAPIDDataset.get_qout_index | train | def get_qout_index(self,
river_index_array=None,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None,
tim... | python | {
"resource": ""
} |
q249850 | RAPIDDataset.write_flows_to_csv | train | def write_flows_to_csv(self, path_to_output_file,
river_index=None,
river_id=None,
date_search_start=None,
date_search_end=None,
daily=False,
filter_mode="mea... | python | {
"resource": ""
} |
q249851 | RAPIDDataset.write_flows_to_gssha_time_series_xys | train | def write_flows_to_gssha_time_series_xys(self,
path_to_output_file,
series_name,
series_id,
river_index=None,
... | python | {
"resource": ""
} |
q249852 | RAPIDDataset.write_flows_to_gssha_time_series_ihg | train | def write_flows_to_gssha_time_series_ihg(self,
path_to_output_file,
connection_list_file,
date_search_start=None,
date_search_end=None,
... | python | {
"resource": ""
} |
q249853 | case_insensitive_file_search | train | def case_insensitive_file_search(directory, pattern):
"""
Looks for file with pattern with case insensitive search
"""
try:
return os.path.join(
directory,
[filename for filename in os.listdir(directory)
| python | {
"resource": ""
} |
q249854 | partition | train | def partition(lst, n):
"""
Divide list into n equal parts
"""
q, r = divmod(len(lst), n)
indices = | python | {
"resource": ""
} |
q249855 | get_valid_directory_list | train | def get_valid_directory_list(input_directory):
"""
Get a list of folders
"""
valid_input_directories = []
for directory in os.listdir(input_directory):
if os.path.isdir(os.path.join(input_directory, directory)):
| python | {
"resource": ""
} |
q249856 | TauDEM._run_mpi_cmd | train | def _run_mpi_cmd(self, cmd):
"""
This runs the command you send in
"""
log("Number of Processes: {0}".format(self.num_processors))
time_start = datetime.utcnow()
# Construct the taudem command line.
cmd = [self.mpiexec_path, '-n', str(self.num_processors)] + cmd
... | python | {
"resource": ""
} |
q249857 | TauDEM._add_prj_file | train | def _add_prj_file(original_gis_file, new_gis_file):
"""
Adds projection file
"""
out_prj_file = "{0}.prj".format(os.path.splitext(new_gis_file)[0])
if original_gis_file.endswith(".shp"):
dataset = ogr.Open(original_gis_file)
| python | {
"resource": ""
} |
q249858 | TauDEM.extractSubNetwork | train | def extractSubNetwork(network_file,
out_subset_network_file,
outlet_ids,
river_id_field,
next_down_id_field,
river_magnitude_field,
safe_mode=True):
"""
... | python | {
"resource": ""
} |
q249859 | TauDEM.extractLargestSubNetwork | train | def extractLargestSubNetwork(cls,
network_file,
out_subset_network_file,
river_id_field,
next_down_id_field,
river_magnitude_field,
... | python | {
"resource": ""
} |
q249860 | TauDEM.rasterToPolygon | train | def rasterToPolygon(raster_file, polygon_file):
"""
Converts watershed raster to polygon and then dissolves it.
It dissolves features based on the LINKNO attribute.
"""
log("Process: Raster to Polygon ...")
time_start = datetime.utcnow()
temp_polygon_file = \
... | python | {
"resource": ""
} |
q249861 | TauDEM.pitRemove | train | def pitRemove(self,
elevation_grid,
pit_filled_elevation_grid,
input_depression_mask_grid=None,
consider4way=False,
):
"""
Remove low spots from DEM.
"""
log("PROCESS: PitRemove")
self.pit_f... | python | {
"resource": ""
} |
q249862 | TauDEM.dinfFlowDirection | train | def dinfFlowDirection(self,
flow_dir_grid,
slope_grid,
pit_filled_elevation_grid=None):
"""
Calculates flow direction with Dinf method
"""
log("PROCESS: DinfFlowDirection")
if pit_filled_elevation_grid:... | python | {
"resource": ""
} |
q249863 | TauDEM.dinfContributingArea | train | def dinfContributingArea(self,
contributing_area_grid,
flow_dir_grid,
outlet_shapefile=None,
weight_grid=None,
edge_contamination=False,
):
... | python | {
"resource": ""
} |
q249864 | TauDEM.streamDefByThreshold | train | def streamDefByThreshold(self,
stream_raster_grid,
threshold,
contributing_area_grid,
mask_grid=None,
):
"""
Calculates the stream definition by threshold.
... | python | {
"resource": ""
} |
q249865 | TauDEM.streamReachAndWatershed | train | def streamReachAndWatershed(self,
delineate,
out_stream_order_grid,
out_network_connectivity_tree,
out_network_coordinates,
out_stream_reach_file,
... | python | {
"resource": ""
} |
q249866 | TauDEM.demToStreamNetwork | train | def demToStreamNetwork(self,
output_directory,
raw_elevation_dem="",
pit_filled_elevation_grid="",
flow_dir_grid_d8="",
contributing_area_grid_d8="",
flow_dir... | python | {
"resource": ""
} |
q249867 | build_iiif_file_storage_path | train | def build_iiif_file_storage_path(url_path, ik_image, iiif_storage):
"""
Return the file storage path for a given IIIF Image API URL path.
NOTE: The returned file storage path includes the given ``Image``
instance's ID to ensure the path is unique and identifiable, and its
modified timestamp to act ... | python | {
"resource": ""
} |
q249868 | CreatorBase.get_roles | train | def get_roles(self):
"""Return the m2m relations connecting me to works"""
work_ids = self.get_works().values_list('id', flat=True)
return self.works.through.objects.filter(
| python | {
"resource": ""
} |
q249869 | WorkBase.derive_and_set_slug | train | def derive_and_set_slug(self, set_name_sort=True, set_slug=True):
"""
Derive `slug` field from `title` unless it is set in its own right.
This method is called during `save()`
"""
# `title` is the primary required name field. It must be set.
if is_empty(self.title):
... | python | {
"resource": ""
} |
q249870 | WorkBase.get_roles | train | def get_roles(self):
"""
Return the m2m relations connecting me to creators.
There's some publishing-related complexity here. The role relations
(self.creators.through) connect to draft objects, which then need to
be modified to point to visible() objects.
"""
| python | {
"resource": ""
} |
q249871 | EventAdmin.get_urls | train | def get_urls(self):
"""
Add a calendar URL.
"""
from django.conf.urls import patterns, url
urls = super(EventAdmin, self).get_urls()
my_urls = patterns(
'',
url(
r'^calendar/$',
self.admin_site.admin_view(self.calend... | python | {
"resource": ""
} |
q249872 | EventAdmin.calendar | train | def calendar(self, request):
"""
Return a calendar page to be loaded in an iframe.
"""
context = { | python | {
"resource": ""
} |
q249873 | EventAdmin.calendar_data | train | def calendar_data(self, request):
"""
Return event data in JSON format for AJAX requests, or a calendar page
to be loaded in an iframe.
"""
# mutable copy
request.GET = request.GET.copy()
if 'timezone' in request.GET:
tz = djtz.get(request.GET.pop('t... | python | {
"resource": ""
} |
q249874 | EventAdmin._calendar_json_for_occurrence | train | def _calendar_json_for_occurrence(self, occurrence):
"""
Return JSON for a single Occurrence
"""
# Slugify the plugin's verbose name for use as a class name.
if occurrence.is_all_day:
start = occurrence.start
# `end` is exclusive according to the doc in
... | python | {
"resource": ""
} |
q249875 | EventAdmin._calendar_classes_for_occurrence | train | def _calendar_classes_for_occurrence(self, occurrence):
"""
Return css classes to be used in admin calendar JSON
"""
classes = [slugify(occurrence.event.polymorphic_ctype.name)]
# Add a class name for the type of event.
if occurrence.is_all_day:
classes.appen... | python | {
"resource": ""
} |
q249876 | RecurrenceRuleAdmin.get_urls | train | def get_urls(self):
"""
Add a preview URL.
"""
from django.conf.urls import patterns, url
urls = super(RecurrenceRuleAdmin, self).get_urls()
| python | {
"resource": ""
} |
q249877 | RecurrenceRuleAdmin.preview | train | def preview(self, request):
"""
Return a occurrences in JSON format up until the configured limit.
"""
recurrence_rule = request.POST.get('recurrence_rule')
limit = int(request.POST.get('limit', 10))
try:
rruleset = rrule.rrulestr(
recurrence_r... | python | {
"resource": ""
} |
q249878 | AbstractAdvancedEventListingPage.parse_primary_types | train | def parse_primary_types(self, request):
"""
Return primary event types that occurrences must belong to, or `None`
if there is no constraint on primary type.
"""
if request.GET.getlist('primary_types'):
| python | {
"resource": ""
} |
q249879 | AbstractAdvancedEventListingPage.parse_secondary_types | train | def parse_secondary_types(self, request):
"""
Return secondary event types that occurrences must belong to, or `None`
if there is no constraint on secondary type.
"""
if request.GET.getlist('secondary_types'):
| python | {
"resource": ""
} |
q249880 | PasswordResetForm.get_users | train | def get_users(self, email):
"""
Make sure users are staff users.
Additionally to the other PasswordResetForm conditions ensure
that the user is a staff user before sending them a password
reset email.
:param email: Textual email address.
:return: List of users.
... | python | {
"resource": ""
} |
q249881 | send_email_notifications_for_workflow_state_change | train | def send_email_notifications_for_workflow_state_change(
sender, instance, *args, **kwargs
):
"""
Send email notifications for save events on ``WorkflowState`` based on
settings in this module's `appsettings`.
"""
# Short-circuit processing if we have no notification targets
if not appsetting... | python | {
"resource": ""
} |
q249882 | _get_image_or_404 | train | def _get_image_or_404(identifier, load_image=False):
"""
Return image matching `identifier`.
The `identifier` is expected to be a raw image ID for now, but may be
more complex later.
"""
try:
image_id = int(identifier)
except ValueError:
raise Http404()
ik_image = get_o... | python | {
"resource": ""
} |
q249883 | iiif_image_api | train | def iiif_image_api(request, identifier_param, region_param, size_param,
rotation_param, quality_param, format_param):
""" Image repurposing endpoint for IIIF Image API 2.1 """
ik_image, image = _get_image_or_404(identifier_param, load_image=True)
is_transparent = et_utils.is_transparent(... | python | {
"resource": ""
} |
q249884 | InstagramEmbedAdminForm.clean_url | train | def clean_url(self):
"""
Make sure the URL provided matches the instagram URL format.
"""
url = self.cleaned_data['url']
| python | {
"resource": ""
} |
q249885 | RedirectViewset.retrieve | train | def retrieve(self, request, *args, **kwargs):
"""
If the URL slug doesn't match an object, try slugifying the URL param
and searching alt_url for that.
If found, redirect to the canonical URL.
If still not found, raise 404.
"""
try:
instance = self.ge... | python | {
"resource": ""
} |
q249886 | forwards | train | def forwards(apps, schema_editor):
"""
Create sample events.
"""
starts = timeutils.round_datetime(
when=timezone.now(),
precision=timedelta(days=1),
rounding=timeutils.ROUND_DOWN)
ends = starts + appsettings.DEFAULT_ENDS_DELTA
recurrence_rules = dict(
Recurrence... | python | {
"resource": ""
} |
q249887 | backwards | train | def backwards(apps, schema_editor):
"""
Delete sample events, including derivative repeat and variation events.
"""
titles = [
'Daily Event',
'Weekday Event',
'Weekend Event',
'Weekly Event',
| python | {
"resource": ""
} |
q249888 | dump_viewset | train | def dump_viewset(viewset_class, root_folder, folder_fn=lambda i: ".", sample_size=None):
"""
Dump the contents of a rest-api queryset to a folder structure.
:param viewset_class: A rest-api viewset to iterate through
:param root_folder: The root folder to write results to.
:param folder_fn: A funct... | python | {
"resource": ""
} |
q249889 | concatenate_json | train | def concatenate_json(source_folder, destination_file):
"""
Concatenate all the json files in a folder to one big JSON file.
"""
matches = []
for root, dirnames, filenames in os.walk(source_folder):
for filename in fnmatch.filter(filenames, '*.json'):
matches.append(os.path.join(r... | python | {
"resource": ""
} |
q249890 | TitleSlugMixin.validate_unique_slug | train | def validate_unique_slug(self):
"""
Ensure slug is unique for this model. This check is aware of publishing
but is otherwise fairly basic and will need to be customised for
situations where models with slugs are not in a flat hierarchy etc.
"""
clashes_qs = type(self).obj... | python | {
"resource": ""
} |
q249891 | AbstractCollectedContent.get_absolute_url | train | def get_absolute_url(self):
"""
The majority of the time, the URL is the parent's URL plus the slug.
If not, override this function.
"""
# Get the appropriate draft or published parent object for the current
# item, otherwise we risk mixing the draft parent URL with a pub... | python | {
"resource": ""
} |
q249892 | AbstractCollectedContent.get_response | train | def get_response(self, request, parent, *args, **kwargs):
"""
Render this collected content to a response.
:param request: the request
:param parent: the parent collection
:param args:
:param kwargs:
:return:
"""
context = {
'page': se... | python | {
"resource": ""
} |
q249893 | forwards_migration | train | def forwards_migration(apps, schema_editor):
"""
"0002_recurrence_rules" added malformed recurrence with trailing
semi-colons. While the JS parser on the front-end handles them,
the python parser will crash | python | {
"resource": ""
} |
q249894 | get_response_page | train | def get_response_page(request, return_type, template_location, response_page_type):
"""
Helper function to get an appropriate response page if it exists.
This function is not designed to be used directly as a view. It is
a helper function which can be called to check if a ResponsePage
exists for a ... | python | {
"resource": ""
} |
q249895 | server_error | train | def server_error(request, template_name='500.html'):
"""
Custom 500 error handler.
The exception clause is so broad to capture any 500 errors that
may have been generated from getting the response page e.g. if the
database was down. If they were not handled they would cause a 500
themselves and... | python | {
"resource": ""
} |
q249896 | allowed_to_preview | train | def allowed_to_preview(user):
"""
Is the user allowed to view the preview?
Users are only allowed to view the preview if they are authenticated, active and staff.
:param user: A User object instance.
:return: Boolean.
"""
if (
| python | {
"resource": ""
} |
q249897 | ChildModelPluginPolymorphicParentModelAdmin.get_child_type_choices | train | def get_child_type_choices(self, request, action):
"""
Override choice labels with ``verbose_name`` from plugins and sort.
"""
# Get choices from the super class to check permissions.
choices = super(ChildModelPluginPolymorphicParentModelAdmin, self) \
.get_child_type... | python | {
"resource": ""
} |
q249898 | ChildModelPluginPolymorphicParentModelAdmin.get_child_models | train | def get_child_models(self):
"""
Get child models from registered plugins. Fallback to the child model
admin and its base model if no plugins are registered.
"""
child_models = []
for plugin in self.child_model_plugin_class.get_plugins():
child_models.append((p... | python | {
"resource": ""
} |
q249899 | PolymorphicAdminRawIdFix._get_child_admin_site | train | def _get_child_admin_site(self, rel):
"""
Returns the separate AdminSite instance that django-polymorphic
maintains for child models.
This admin site needs to be passed to the widget so that it passes the
check of whether the field is pointing to a model that's registered
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.