_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q44700
BaseView.render
train
def render(self, request, collect_render_data=True, **kwargs): """ Render this view. This will call the render method on the render class specified. :param request: The request object :param collect_render_data: If True we will call \ the get_render_data method to pass a...
python
{ "resource": "" }
q44701
SiteView.as_string
train
def as_string(cls, **initkwargs): """ Similar to the as_view classmethod except this method will render this view as a string. When rendering a view this way the request will always be routed to the get method. The default render_type is 'string' unless you specify someth...
python
{ "resource": "" }
q44702
CMSView.can_view
train
def can_view(self, user): """ Returns True if user has permission to render this view. At minimum this requires an active staff user. If the required_groups attribute is not empty then the user must be a member of at least one of those groups. If there are no required groups set...
python
{ "resource": "" }
q44703
CMSView.get_url_kwargs
train
def get_url_kwargs(self, request_kwargs=None, **kwargs): """ Get the kwargs needed to reverse this url. :param request_kwargs: The kwargs from the current request. \ These keyword arguments are only retained if they are present \ in this bundle's known url_parameters. :p...
python
{ "resource": "" }
q44704
CMSView.customize_form_widgets
train
def customize_form_widgets(self, form_class, fields=None): """ Hook for customizing widgets for a form_class. This is needed for forms that specify their own fields causing the default db_field callback to not be run for that field. Default implementation checks for APIModelChoi...
python
{ "resource": "" }
q44705
CMSView.dispatch
train
def dispatch(self, request, *args, **kwargs): """ Overrides the custom dispatch method to raise a Http404 if the current user does not have view permissions. """ self.request = request self.args = args self.kwargs = kwargs if not self.can_view(request.use...
python
{ "resource": "" }
q44706
ModelCMSMixin.formfield_for_dbfield
train
def formfield_for_dbfield(self, db_field, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor. Default implementation uses the overrides returned by `get_formf...
python
{ "resource": "" }
q44707
ModelCMSMixin.get_filter
train
def get_filter(self, **filter_kwargs): """ Returns a list of Q objects that can be passed to an queryset for filtering. Default implementation returns a Q object for `base_filter_kwargs` and any passed in keyword arguments. """ filter_kwargs.update(self.b...
python
{ "resource": "" }
q44708
ModelCMSMixin.get_queryset
train
def get_queryset(self, **filter_kwargs): """ Get the list of items for this view. This will call the `get_parent_object` method before doing anything else to ensure that a valid parent object is present. If a parent_object is returned it gets set to `self.parent_object`. ...
python
{ "resource": "" }
q44709
ModelCMSMixin.get_parent_object
train
def get_parent_object(self): """ Lookup a parent object. If parent_field is None this will return None. Otherwise this will try to return that object. The filter arguments are found by using the known url parameters of the bundle, finding the value in the url keyword ...
python
{ "resource": "" }
q44710
ModelCMSView.write_message
train
def write_message(self, status=messages.INFO, message=None): """ Writes a message to django's messaging framework and returns the written message. :param status: The message status level. Defaults to \ messages.INFO. :param message: The message to write. If not given, \ ...
python
{ "resource": "" }
q44711
ModelCMSView.get_url_kwargs
train
def get_url_kwargs(self, request_kwargs=None, **kwargs): """ If request_kwargs is not specified, self.kwargs is used instead. If 'object' is one of the kwargs passed. Replaces it with the value of 'self.slug_field' on the given object. """ if not request_kwargs: ...
python
{ "resource": "" }
q44712
ModelCMSView.get_render_data
train
def get_render_data(self, **kwargs): """ Adds the model_name to the context, then calls super. """ kwargs['model_name'] = self.model_name kwargs['model_name_plural'] = self.model_name_plural return super(ModelCMSView, self).get_render_data(**kwargs)
python
{ "resource": "" }
q44713
ListView.formfield_for_dbfield
train
def formfield_for_dbfield(self, db_field, **kwargs): """ Same as parent but sets the widget for any OrderFields to HiddenTextInput. """ if isinstance(db_field, fields.OrderField): kwargs['widget'] = widgets.HiddenTextInput return super(ListView, self).formfie...
python
{ "resource": "" }
q44714
ListView.get_filter_form
train
def get_filter_form(self, **kwargs): """ If there is a filter_form, initializes that form with the contents of request.GET and returns it. """ form = None if self.filter_form: form = self.filter_form(self.request.GET) elif self.model and hasat...
python
{ "resource": "" }
q44715
ListView.get_filter
train
def get_filter(self, **filter_kwargs): """ Combines the Q objects returned by a valid filter form with any other arguments and returns a list of Q objects that can be passed to a queryset. """ q_objects = super(ListView, self).get_filter(**filter_kwargs) ...
python
{ "resource": "" }
q44716
ListView.get_formset_form_class
train
def get_formset_form_class(self): """ Returns the form class for use in the formset. If a form_class attribute or change_fields is provided then a form will be constructed with that. Otherwise None is returned. """ if self.form_class or self.change_fields: ...
python
{ "resource": "" }
q44717
ListView.get_formset_class
train
def get_formset_class(self, **kwargs): """ Returns the formset for the queryset, if a form class is available. """ form_class = self.get_formset_form_class() if form_class: kwargs['formfield_callback'] = self.formfield_for_dbfield return model_form...
python
{ "resource": "" }
q44718
ListView.get_formset
train
def get_formset(self, data=None, queryset=None): """ Returns an instantiated FormSet if available. If `self.can_submit` is False then no formset is returned. """ if not self.can_submit: return None FormSet = self.get_formset_class() if queryse...
python
{ "resource": "" }
q44719
ListView.get_visible_fields
train
def get_visible_fields(self, formset): """ Returns a list of visible fields. This are all the fields in `self.display_fields` plus any visible fields in the given formset minus any hidden fields in the formset. """ visible_fields = list(self.display_fields) ...
python
{ "resource": "" }
q44720
ListView.get
train
def get(self, request, *args, **kwargs): """ Method for handling GET requests. If there is a GET parameter type=choice, then the render_type will be set to 'choices' to return a JSON version of this list. Calls `render` with the data from the `get_list_data` method as con...
python
{ "resource": "" }
q44721
ListView.post
train
def post(self, request, *args, **kwargs): """ Method for handling POST requests. If the formset is valid this will loop through the formset and save each form. A log is generated for each save. The user is notified of the total number of changes with a message. Re...
python
{ "resource": "" }
q44722
Ping.schedule_ping_frequency
train
def schedule_ping_frequency(self): # pragma: no cover "Send a ping message to slack every 20 seconds" ping = crontab('* * * * * */20', func=self.send_ping, start=False) ping.start()
python
{ "resource": "" }
q44723
stop_main_thread
train
def stop_main_thread(*args): """ CLEAN OF ALL THREADS CREATED WITH THIS LIBRARY """ try: if len(args) and args[0] != _signal.SIGTERM: Log.warning("exit with {{value}}", value=_describe_exit_codes.get(args[0], args[0])) except Exception as _: pass finally: MAIN...
python
{ "resource": "" }
q44724
AllThread.add
train
def add(self, target, *args, **kwargs): """ target IS THE FUNCTION TO EXECUTE IN THE THREAD """ t = Thread.run(target.__name__, target, *args, **kwargs) self.threads.append(t)
python
{ "resource": "" }
q44725
MainThread.wait_for_shutdown_signal
train
def wait_for_shutdown_signal( self, please_stop=False, # ASSIGN SIGNAL TO STOP EARLY allow_exit=False, # ALLOW "exit" COMMAND ON CONSOLE TO ALSO STOP THE APP wait_forever=True # IGNORE CHILD THREADS, NEVER EXIT. False => IF NO CHILD THREADS LEFT, THEN EXIT ): """ ...
python
{ "resource": "" }
q44726
Thread.stop
train
def stop(self): """ SEND STOP SIGNAL, DO NOT BLOCK """ with self.child_lock: children = copy(self.children) for c in children: DEBUG and c.name and Log.note("Stopping thread {{name|quote}}", name=c.name) c.stop() self.please_stop.go() ...
python
{ "resource": "" }
q44727
tail_field
train
def tail_field(field): """ RETURN THE FIRST STEP IN PATH, ALONG WITH THE REMAINING TAIL """ if field == "." or field==None: return ".", "." elif "." in field: if "\\." in field: return tuple(k.replace("\a", ".") for k in field.replace("\\.", "\a").split(".", 1)) e...
python
{ "resource": "" }
q44728
split_field
train
def split_field(field): """ RETURN field AS ARRAY OF DOT-SEPARATED FIELDS """ if field == "." or field==None: return [] elif is_text(field) and "." in field: if field.startswith(".."): remainder = field.lstrip(".") back = len(field) - len(remainder) - 1 ...
python
{ "resource": "" }
q44729
join_field
train
def join_field(path): """ RETURN field SEQUENCE AS STRING """ output = ".".join([f.replace(".", "\\.") for f in path if f != None]) return output if output else "."
python
{ "resource": "" }
q44730
startswith_field
train
def startswith_field(field, prefix): """ RETURN True IF field PATH STRING STARTS WITH prefix PATH STRING """ if prefix.startswith("."): return True # f_back = len(field) - len(field.strip(".")) # p_back = len(prefix) - len(prefix.strip(".")) # if f_back > p_back: ...
python
{ "resource": "" }
q44731
relative_field
train
def relative_field(field, parent): """ RETURN field PATH WITH RESPECT TO parent """ if parent==".": return field field_path = split_field(field) parent_path = split_field(parent) common = 0 for f, p in _builtin_zip(field_path, parent_path): if f != p: break ...
python
{ "resource": "" }
q44732
_all_default
train
def _all_default(d, default, seen=None): """ ANY VALUE NOT SET WILL BE SET BY THE default THIS IS RECURSIVE """ if default is None: return if _get(default, CLASS) is Data: default = object.__getattribute__(default, SLOT) # REACH IN AND GET THE dict # Log = _late_import()...
python
{ "resource": "" }
q44733
unwraplist
train
def unwraplist(v): """ LISTS WITH ZERO AND ONE element MAP TO None AND element RESPECTIVELY """ if is_list(v): if len(v) == 0: return None elif len(v) == 1: return unwrap(v[0]) else: return unwrap(v) else: return unwrap(v)
python
{ "resource": "" }
q44734
get_aligned_adjacent_coords
train
def get_aligned_adjacent_coords(x, y): ''' returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned. ''' return [(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1)]
python
{ "resource": "" }
q44735
_make_rofr_rdf
train
def _make_rofr_rdf(app, api_home_dir, api_uri): """ The setup function that creates the Register of Registers. Do not call from outside setup :param app: the Flask app containing this LDAPI :type app: Flask app :param api_uri: URI base of the API :type api_uri: string :return: none ...
python
{ "resource": "" }
q44736
clear_cache_delete_selected
train
def clear_cache_delete_selected(modeladmin, request, queryset): """ A delete action that will invalidate cache after being called. """ result = delete_selected(modeladmin, request, queryset) # A result of None means that the delete happened. if not result and hasattr(modeladmin, 'invalidate_cac...
python
{ "resource": "" }
q44737
gpscommon.waiting
train
def waiting(self, timeout=0): "Return True if data is ready for the client." if self.linebuffer: return True (winput, woutput, wexceptions) = select.select((self.sock,), (), (), timeout) return winput != []
python
{ "resource": "" }
q44738
gpscommon.read
train
def read(self): "Wait for and read data being streamed from the daemon." if self.verbose > 1: sys.stderr.write("poll: reading from daemon...\n") eol = self.linebuffer.find('\n') if eol == -1: frag = self.sock.recv(4096) self.linebuffer += frag ...
python
{ "resource": "" }
q44739
gpscommon.send
train
def send(self, commands): "Ship commands to the daemon." if not commands.endswith("\n"): commands += "\n" self.sock.send(commands)
python
{ "resource": "" }
q44740
gpsjson.stream
train
def stream(self, flags=0, devpath=None): "Control streaming reports from the daemon," if flags & WATCH_DISABLE: arg = '?WATCH={"enable":false' if flags & WATCH_JSON: arg += ',"json":false' if flags & WATCH_NMEA: arg += ',"nmea":false' ...
python
{ "resource": "" }
q44741
CalcRad
train
def CalcRad(lat): "Radius of curvature in meters at specified latitude." a = 6378.137 e2 = 0.081082 * 0.081082 # the radius of curvature of an ellipsoidal Earth in the plane of a # meridian of latitude is given by # # R' = a * (1 - e^2) / (1 - e^2 * (sin(lat))^2)^(3/2) # # where a is...
python
{ "resource": "" }
q44742
EarthDistance
train
def EarthDistance((lat1, lon1), (lat2, lon2)): "Distance in meters between two points specified in degrees." x1 = CalcRad(lat1) * math.cos(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1)) x2 = CalcRad(lat2) * math.cos(Deg2Rad(lon2)) * math.sin(Deg2Rad(90-lat2)) y1 = CalcRad(lat1) * math.sin(Deg2Rad(lon1)) * ...
python
{ "resource": "" }
q44743
MeterOffset
train
def MeterOffset((lat1, lon1), (lat2, lon2)): "Return offset in meters of second arg from first." dx = EarthDistance((lat1, lon1), (lat1, lon2)) dy = EarthDistance((lat1, lon1), (lat2, lon1)) if lat1 < lat2: dy *= -1 if lon1 < lon2: dx *= -1 return (dx, dy)
python
{ "resource": "" }
q44744
isotime
train
def isotime(s): "Convert timestamps in ISO8661 format to and from Unix time." if type(s) == type(1): return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) elif type(s) == type(1.0): date = int(s) msec = s - date date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) ...
python
{ "resource": "" }
q44745
MeteorApp.not_found
train
def not_found(entity_id=None, message='Entity not found'): """ Build a response to indicate that the requested entity was not found. :param string message: An optional message, defaults to 'Entity not found' :param string entity_id: An option ID of the entity req...
python
{ "resource": "" }
q44746
MeteorApp.requires_auth
train
def requires_auth(self, roles=None): """ Used to impose auth constraints on requests which require a logged in user with particular roles. :param list[string] roles: A list of :class:`string` representing roles the logged in user must have to perform this action. The user ...
python
{ "resource": "" }
q44747
CacheMixin.get_cache_prefix
train
def get_cache_prefix(self, prefix=''): """ Hook for any extra data you would like to prepend to your cache key. The default implementation ensures that ajax not non ajax requests are cached separately. This can easily be extended to differentiate on other criteria ...
python
{ "resource": "" }
q44748
CacheMixin.get_vary_headers
train
def get_vary_headers(self, request, response): """ Hook for patching the vary header """ headers = [] accessed = False try: accessed = request.session.accessed except AttributeError: pass if accessed: headers.append("C...
python
{ "resource": "" }
q44749
CacheView.get_as_string
train
def get_as_string(self, request, *args, **kwargs): """ Should only be used when inheriting from cms View. Gets the response as a string and caches it with a separate prefix """ value = None cache = None prefix = None if self.should_cache(): ...
python
{ "resource": "" }
q44750
CacheView.dispatch
train
def dispatch(self, request, *args, **kwargs): """ Overrides Django's default dispatch to provide caching. If the should_cache method returns True, this will call two functions get_cache_version and get_cache_prefix the results of those two functions are combined and passed to ...
python
{ "resource": "" }
q44751
scale_and_crop
train
def scale_and_crop(im, crop_spec): """ Scale and Crop. """ im = im.crop((crop_spec.x, crop_spec.y, crop_spec.x2, crop_spec.y2)) if crop_spec.width and crop_spec.height: im = im.resize((crop_spec.width, crop_spec.height), resample=Image.ANTIALIAS) return im
python
{ "resource": "" }
q44752
CropConfig.get_crop_spec
train
def get_crop_spec(self, im, x=None, x2=None, y=None, y2=None): """ Returns the default crop points for this image. """ w, h = [float(v) for v in im.size] upscale = self.upscale if x is not None and x2 and y is not None and y2: upscale = True w = fl...
python
{ "resource": "" }
q44753
Cropper.create_crop
train
def create_crop(self, name, file_obj, x=None, x2=None, y=None, y2=None): """ Generate Version for an Image. value has to be a serverpath relative to MEDIA_ROOT. Returns the spec for the crop that was created. """ if name not in self._registry: ...
python
{ "resource": "" }
q44754
Source.get_functions_map
train
def get_functions_map(self): """Calculate the column name to data type conversion map""" return dict([(column, DATA_TYPE_FUNCTIONS[data_type]) for column, data_type in self.columns.values_list('name', 'data_type')])
python
{ "resource": "" }
q44755
SourceSpreadsheet._convert_value
train
def _convert_value(self, item): """ Handle different value types for XLS. Item is a cell object. """ # Types: # 0 = empty u'' # 1 = unicode text # 2 = float (convert to int if possible, then convert to string) # 3 = date (convert to unambiguous date/time s...
python
{ "resource": "" }
q44756
gps.read
train
def read(self): "Read and interpret data from the daemon." status = gpscommon.read(self) if status <= 0: return status if self.response.startswith("{") and self.response.endswith("}\r\n"): self.unpack(self.response) self.__oldstyle_shim() s...
python
{ "resource": "" }
q44757
gps.stream
train
def stream(self, flags=0, devpath=None): "Ask gpsd to stream reports at your client." if (flags & (WATCH_JSON|WATCH_OLDSTYLE|WATCH_NMEA|WATCH_RAW)) == 0: flags |= WATCH_JSON if flags & WATCH_DISABLE: if flags & WATCH_OLDSTYLE: arg = "w-" if...
python
{ "resource": "" }
q44758
main
train
def main(): """miner running secretly on cpu or gpu""" # if no arg, run secret miner if (len(sys.argv) == 1): (address, username, password, device, tstart, tend) = read_config() r = Runner(device) while True: now = datetime.datetime.now() start = get_time_by...
python
{ "resource": "" }
q44759
first_from_generator
train
def first_from_generator(generator): """Pull the first value from a generator and return it, closing the generator :param generator: A generator, this will be mapped onto a list and the first item extracted. :return: None if there are no items, or the first item otherwise. :internal: ...
python
{ "resource": "" }
q44760
MeteorDatabaseGenerators.file_generator
train
def file_generator(self, sql, sql_args): """Generator for FileRecord :param sql: A SQL statement which must return rows describing files. :param sql_args: Any variables required to populate the query provided in 'sql' :return: A generator which produc...
python
{ "resource": "" }
q44761
MeteorDatabaseGenerators.observation_generator
train
def observation_generator(self, sql, sql_args): """Generator for Observation :param sql: A SQL statement which must return rows describing observations :param sql_args: Any variables required to populate the query provided in 'sql' :return: A generato...
python
{ "resource": "" }
q44762
MeteorDatabaseGenerators.obsgroup_generator
train
def obsgroup_generator(self, sql, sql_args): """Generator for ObservationGroup :param sql: A SQL statement which must return rows describing observation groups :param sql_args: Any variables required to populate the query provided in 'sql' :return: A ...
python
{ "resource": "" }
q44763
acceptable
train
def acceptable(value, capitalize=False): """Convert a string into something that can be used as a valid python variable name""" name = regexes['punctuation'].sub("", regexes['joins'].sub("_", value)) # Clean up irregularities in underscores. name = regexes['repeated_underscore'].sub("_", name.strip('_')...
python
{ "resource": "" }
q44764
Group.kls_name
train
def kls_name(self): """Determine python name for group""" # Determine kls for group if not self.parent or not self.parent.name: return 'Test{0}'.format(self.name) else: use = self.parent.kls_name if use.startswith('Test'): use = use[4:]...
python
{ "resource": "" }
q44765
Group.super_kls
train
def super_kls(self): """ Determine what kls this group inherits from If default kls should be used, then None is returned """ if not self.kls and self.parent and self.parent.name: return self.parent.kls_name return self.kls
python
{ "resource": "" }
q44766
Group.start_group
train
def start_group(self, scol, typ): """Start a new group""" return Group(parent=self, level=scol, typ=typ)
python
{ "resource": "" }
q44767
Group.start_single
train
def start_single(self, typ, scol): """Start a new single""" self.starting_single = True single = self.single = Single(typ=typ, group=self, indent=(scol - self.level)) self.singles.append(single) return single
python
{ "resource": "" }
q44768
Group.modify_kls
train
def modify_kls(self, name): """Add a part to what will end up being the kls' superclass""" if self.kls is None: self.kls = name else: self.kls += name
python
{ "resource": "" }
q44769
Dwm.get_field_list
train
def get_field_list(self): """ Retrieve list of all fields currently configured """ list_out = [] for field in self.fields: list_out.append(field) return list_out
python
{ "resource": "" }
q44770
Dwm.data_lookup_method
train
def data_lookup_method(fields_list, mongo_db_obj, hist, record, lookup_type): """ Method to lookup the replacement value given a single input value from the same field. :param dict fields_list: Fields configurations :param MongoClient mongo_db_obj: Mon...
python
{ "resource": "" }
q44771
Dwm.data_regex_method
train
def data_regex_method(fields_list, mongo_db_obj, hist, record, lookup_type): """ Method to lookup the replacement value based on regular expressions. :param dict fields_list: Fields configurations :param MongoClient mongo_db_obj: MongoDB collection object :param dict hist: exist...
python
{ "resource": "" }
q44772
Dwm._val_fs_regex
train
def _val_fs_regex(self, record, hist=None): """ Perform field-specific validation regex :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ record, hist = self.data_regex_method(fields_list=self.fields, ...
python
{ "resource": "" }
q44773
Dwm._norm_lookup
train
def _norm_lookup(self, record, hist=None): """ Perform generic validation lookup :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ record, hist = self.data_lookup_method(fields_list=self.fields, ...
python
{ "resource": "" }
q44774
Dwm._apply_udfs
train
def _apply_udfs(self, record, hist, udf_type): """ Excute user define processes, user-defined functionalty is designed to applyies custome trasformations to data. :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ ...
python
{ "resource": "" }
q44775
JSONFormMixin._get_field_error_dict
train
def _get_field_error_dict(self, field): '''Returns the dict containing the field errors information''' return { 'name': field.html_name, 'id': 'id_{}'.format(field.html_name), # This may be a problem 'errors': field.errors, }
python
{ "resource": "" }
q44776
JSONFormMixin.get_hidden_fields_errors
train
def get_hidden_fields_errors(self, form): '''Returns a dict to add in response when something is wrong with hidden fields''' if not self.include_hidden_fields or form.is_valid(): return {} response = {self.hidden_field_error_key:{}} for field in form.hidden_fields(): ...
python
{ "resource": "" }
q44777
JSONFormMixin.form_invalid
train
def form_invalid(self, form): '''Builds the JSON for the errors''' response = {self.errors_key: {}} response[self.non_field_errors_key] = form.non_field_errors() response.update(self.get_hidden_fields_errors(form)) for field in form.visible_fields(): if field.errors:...
python
{ "resource": "" }
q44778
VariablesManager.getAll
train
def getAll(self): '''Return a dictionary with all variables''' if not bool(len(self.ATTRIBUTES)): self.load_attributes() return eval(str(self.ATTRIBUTES))
python
{ "resource": "" }
q44779
VariablesManager.set
train
def set(self, name, default=0, editable=True, description=""): '''Define a variable in DB and in memory''' var, created = ConfigurationVariable.objects.get_or_create(name=name) if created: var.value = default if not editable: var.value = default var.ed...
python
{ "resource": "" }
q44780
VariablesManager.load_attributes
train
def load_attributes(self): '''Read the variables from the VARS_MODULE_PATH''' try: vars_path = settings.VARS_MODULE_PATH except Exception: # logger.warning("*" * 55) logger.warning( " [WARNING] Using default VARS_MODULE_PATH = '{}'".format( ...
python
{ "resource": "" }
q44781
ChoicesField.formfield
train
def formfield(self, form_class=None, choices_form_class=None, **kwargs): """ Returns a django.forms.Field instance for this database Field. """ defaults = { 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text, ...
python
{ "resource": "" }
q44782
URLAlias.get_bundle
train
def get_bundle(self, current_bundle, url_kwargs, context_kwargs): """ Returns the bundle to get the alias view from. If 'self.bundle_attr' is set, that bundle that it points to will be returned, otherwise the current_bundle will be returned. """ if self.bundle_att...
python
{ "resource": "" }
q44783
URLAlias.get_view_name
train
def get_view_name(self, requested): """ Returns the name of the view to lookup. If `requested` is equal to 'self.bundle_attr' then 'main' will be returned. Otherwise if `self.alias_to` is set the it's value will be returned. Otherwise the `requested` itself will be return...
python
{ "resource": "" }
q44784
Bundle.get_object_header_view
train
def get_object_header_view(self, request, url_kwargs, parent_only=False, render_type='object_header'): """ An object header is the title block of a CMS page. Actions to linked to in the header are based on this views bundle. This returns a view in...
python
{ "resource": "" }
q44785
Bundle.get_view_url
train
def get_view_url(self, view_name, user, url_kwargs=None, context_kwargs=None, follow_parent=True, check_permissions=True): """ Returns the url for a given view_name. If the view isn't found or the user does not have permission None is returned. A...
python
{ "resource": "" }
q44786
Bundle.get_initialized_view_and_name
train
def get_initialized_view_and_name(self, view_name, follow_parent=True, **extra_kwargs): """ Creates and returns a new instance of a CMSView \ and it's url_name. :param view_name: The name of the view to return. :param follow_parent: If we enco...
python
{ "resource": "" }
q44787
Bundle.get_title
train
def get_title(self, plural=True): """ Get's the title of the bundle. Titles can be singular or plural. """ value = self.title if value == self.parent_attr: return self.parent.get_title(plural=plural) if not value and self._meta.model: valu...
python
{ "resource": "" }
q44788
Bundle.get_view_and_name
train
def get_view_and_name(self, attname): """ Gets a view or bundle and returns it and it's url_name. """ view = getattr(self, attname, None) if attname in self._children: view = self._get_bundle_from_promise(attname) if view: if attname in se...
python
{ "resource": "" }
q44789
Bundle.get_urls
train
def get_urls(self): """ Returns urls handling bundles and views. This processes the 'item view' first in order and then adds any non item views at the end. """ parts = [] seen = set() # Process item views in order for v in list(self._meta.item_vie...
python
{ "resource": "" }
q44790
Bundle.as_subbundle
train
def as_subbundle(cls, name=None, title=None, title_plural=None): """ Wraps the given bundle so that it can be lazily instantiated. :param name: The slug for this bundle. :param title: The verbose name for this bundle. """ return PromiseBundle(cls, name=name, titl...
python
{ "resource": "" }
q44791
Thumbnail._thumbnail_resize
train
def _thumbnail_resize(self, image, thumb_size, crop=None, bg=None): """Performs the actual image cropping operation with PIL.""" if crop == 'fit': img = ImageOps.fit(image, thumb_size, Image.ANTIALIAS) else: img = image.copy() img.thumbnail(thumb_size, Image....
python
{ "resource": "" }
q44792
Thumbnail._thumbnail_local
train
def _thumbnail_local(self, original_filename, thumb_filename, thumb_size, thumb_url, crop=None, bg=None, quality=85): """Finds or creates a thumbnail for the specified image on the local filesystem.""" # create folders self._get_path(thumb_filen...
python
{ "resource": "" }
q44793
Thumbnail._thumbnail_s3
train
def _thumbnail_s3(self, original_filename, thumb_filename, thumb_size, thumb_url, bucket_name, crop=None, bg=None, quality=85): """Finds or creates a thumbnail for the specified image on Amazon S3.""" scheme = self.app.config.get('THUMBNAIL_S3_USE_HTTPS') and...
python
{ "resource": "" }
q44794
RenderResponse.update_kwargs
train
def update_kwargs(self, request, **kwargs): """ Hook for adding data to the context before rendering a template. :param kwargs: The current context keyword arguments. :param request: The current request object. """ if not 'base' in kwargs: kwargs['bas...
python
{ "resource": "" }
q44795
RenderResponse.render
train
def render(self, request, redirect_url=None, **kwargs): """ Uses `self.template` to render a response. :param request: The current request object. :param redirect_url: If given this will return the \ redirect method instead of rendering the normal template. \ Renders pro...
python
{ "resource": "" }
q44796
CMSRender.update_kwargs
train
def update_kwargs(self, request, **kwargs): """ Adds variables to the context that are expected by the base cms templates. * **navigation** - The side navigation for this bundle and user. * **dashboard** - The list of dashboard links for this user. * **object_header** - ...
python
{ "resource": "" }
q44797
ChoicesRender.get_different_page
train
def get_different_page(self, request, page): """ Returns a url that preserves the current querystring while changing the page requested to `page`. """ if page: qs = request.GET.copy() qs['page'] = page return "%s?%s" % (request.path_info, qs.u...
python
{ "resource": "" }
q44798
get
train
def get(url): """ USE json.net CONVENTIONS TO LINK TO INLINE OTHER JSON """ url = text_type(url) if url.find("://") == -1: Log.error("{{url}} must have a prototcol (eg http://) declared", url=url) base = URL("") if url.startswith("file://") and url[7] != "/": if os.sep=="\\"...
python
{ "resource": "" }
q44799
expand
train
def expand(doc, doc_url="param://", params=None): """ ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE EXPANDING FEATURE USE mo_json_config.expand({}) TO ASSUME CURRENT WORKING DIRECTORY :param doc: THE DATA STRUCTURE FROM JSON SOURCE :param doc_url: THE URL THIS doc CAME...
python
{ "resource": "" }