code
stringlengths
1
18.2k
def reset_crops(self): """ Reset all known crops to the default crop. If settings.ASSET_CELERY is specified then the task will be run async """ if self._can_crop(): if settings.CELERY or settings.USE_CELERY_DECORATOR: # this means that we are using celery tasks.reset_crops.apply_async(args=[self.pk], countdown=5) else:...
def ensure_crops(self, *required_crops): """ Make sure a crop exists for each crop in required_crops. Existing crops will not be changed. If settings.ASSET_CELERY is specified then the task will be run async """ if self._can_crop(): if settings.CELERY or settings.USE_CELERY_DECORATOR: # this means that we are using cel...
def create_crop(self, name, x, x2, y, y2): """ Create a crop for this asset. """ if self._can_crop(): spec = get_image_cropper().create_crop(name, self.file, x=x, x2=x2, y=y, y2=y2) ImageDetail.save_crop_spec(self, spec)
def save(self, *args, **kwargs): """ For new assets, creates a new slug. For updates, deletes the old file from storage. Calls super to actually save the object. """ if not self.pk and not self.slug: self.slug = self.generate_slug() if self.__original_file and self.file != self.__original_file: self.delete_real_file(se...
def delete(self, *args, **kwargs): """ Deletes the actual file from storage after the object is deleted. Calls super to actually delete the object. """ file_obj = self.file super(AssetBase, self).delete(*args, **kwargs) self.delete_real_file(file_obj)
def _get_not_annotated(func, annotations=None): """Return non-optional parameters that are not annotated.""" argspec = inspect.getfullargspec(func) args = argspec.args if argspec.defaults is not None: args = args[:-len(argspec.defaults)] if inspect.isclass(func) or inspect.ismethod(func): args = args[1:] # Strip off ``...
def _parse_args(func, variables, annotations=None): """Return a list of arguments with the variable it reads. NOTE: Multiple arguments may read the same variable. """ arg_read_var = [] for arg_name, anno in (annotations or func.__annotations__).items(): if arg_name == 'return': continue var, read = _parse_arg(func, var...
def _parse_arg(func, variables, arg_name, anno): """Parse an argument's annotation.""" if isinstance(anno, str): var = variables[anno] return var, var.read_latest elif (isinstance(anno, list) and len(anno) == 1 and isinstance(anno[0], str)): var = variables[anno[0]] return var, var.read_all # For now, be very strict ab...
def _parse_ret(func, variables, annotations=None): """Parse func's return annotation and return either None, a variable, or a tuple of variables. NOTE: * _parse_ret() also notifies variables about will-writes. * A variable can be written multiple times per return annotation. """ anno = (annotations or func.__annotation...
def _write_values(kwargs, variables): """Write values of kwargs and return thus-satisfied closures.""" writeto = [] for var_name, value in kwargs.items(): var = variables[var_name] var.notify_will_write() var.write(value) writeto.append(var) return _notify_reader_writes(writeto)
def _notify_reader_writes(writeto): """Notify reader closures about these writes and return a sorted list of thus-satisfied closures. """ satisfied = [] for var in writeto: if var.readable: for reader in var.readers: reader.notify_read_ready() if reader.satisfied: satisfied.append(reader) return Closure.sort(satisfied)
def _release(self): """Destroy self since closures cannot be called again.""" del self.funcs del self.variables del self.variable_values del self.satisfied
def set(self, name, value): """Set a variable before ``call()``.""" if not hasattr(self, 'funcs'): raise StartupError('startup cannot be called again') self.variable_values[name] = value
def call(self, **kwargs): """Call all the functions that have previously been added to the dependency graph in topological and lexicographical order, and then return variables in a ``dict``. You may provide variable values with keyword arguments. These values will be written and can satisfy dependencies. NOTE: This obj...
normal exit only; otherwise keep the dead body for # forensic analysis. self._release() return values
def write(self, value): """Write a (new) value to this variable.""" assert self.num_write_waits > 0, self self.num_write_waits -= 1 self.values.append(value) if self.readable: LOG.debug('%s is now readable', self.name)
def call(self): """Call the closure and return variable(s) that is written.""" assert self.satisfied, self LOG.debug('call %s.%s', self.func.__module__, self.func.__qualname__) kwargs = {arg.name: arg.read() for arg in self.args} out_value = self.func(**kwargs) if self.writeto is None: writeto = set() elif isinstance(s...
def update(self, command): """ EXPECTING command == {"set":term, "where":where} THE set CLAUSE IS A DICT MAPPING NAMES TO VALUES THE where CLAUSE IS AN ES FILTER """ command = wrap(command) table = self.get_table(command['update']) es_index = self.es.cluster.get_index(read_only=False, alias=None, kwargs=self.es.setting...
timeout=self.settings.timeout, params={"wait_for_active_shards": self.settings.wait_for_active_shards} ) if response.errors: Log.error("could not update: {{error}}", error=[e.error for i in response["items"] for e in i.values() if e.status not in (200, 201)]) # DELETE BY QUERY, IF NEEDED if "." in listwrap(command.clea...
def extract_tonnikala(fileobj, keywords, comment_tags, options): """Extract messages from Tonnikala files. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list o...
def _clear_char(self): ''' Clears the current character and makes the machine ready to accept the next character. ''' self.lvmarker_count = 0 self.geminate_count = 0 self.next_char_info = None self.next_char_type = None self.active_vowel = None self.active_vowel_info = None self.active_vowel_ro = None self.active_xvowe...
def _append_unknown_char(self): ''' Appends the unknown character, in case one was encountered. ''' if self.unknown_strategy == UNKNOWN_INCLUDE and \ self.unknown_char is not None: self._append_to_stack(self.unknown_char) self.unknown_char = None
def _flush_char(self): ''' Appends the rōmaji characters that represent the current state of the machine. For example, if the state includes the character ト, plus a geminate marker and a long vowel marker, this causes the characters "ttō" to be added to the output. ''' # Ignore in case there's no active character, only...
found, we'll replace the # rōmaji character we were planning on flushing. if char_type == VOWEL and len(char_info) >= 3 and xv is not None: try: exc = char_info[2]['xv'][xv[0]] # Found a special combination. Replace the rōmaji character. char_ro = exc except (IndexError, KeyError): # IndexError: no 'xv' exceptions list...
is None and gem == lvm == 0 and char_ro != 'n': self._append_to_stack(char_ro) self._append_unknown_char() self._clear_char() return # At this point, we're considering two main factors: the currently # active character, and possibly a small vowel character if one is set. # For example, if the active character is テ and ...
info object for clarity. char_gem_cons = char_info[1] # the extra geminate consonant char_cons = char_info[2] # the consonant part char_lv = char_info[4] # the long vowel part # If this flushed character is an 'n', and precedes a vowel or # a 'y' consonant, it must be followed by an apostrophe. char_apostrophe = '' if ...
full digraph. if self.active_dgr_a_info is not None and \ self.active_dgr_b_info is not None: char_cons = self.active_dgr_a_info[0] # Determine the geminate consonant part (which can be # arbitrarily long). gem_cons = char_gem_cons * gem if xv is not None: # Combine the consonant of the character with the small vowel. ...
got a special vowel part, combine it with the # main consonant. char_main = char_cons + char_apostrophe + vowel else: # If not, process the main character and add the long vowels # if applicable. if lvm > 0: char_main = char_cons + char_apostrophe + char_lv * lvm else: char_main = char_ro + char_apostrophe self._append...
def _promote_solitary_xvowel(self): ''' "Promotes" the current xvowel to a regular vowel, in case it is not otherwise connected to a character. Used to print small vowels that would otherwise get lost; normally small vowels always form a pair, but in case one is by itself it should basically act like a regular vowel. '...
def _add_unknown_char(self, string): ''' Adds an unknown character to the stack. ''' if self.has_xvowel: # Ensure an xvowel gets printed if we've got an active # one right now. self._promote_solitary_xvowel() self.unknown_char = string self._flush_char()
def _set_digraph_a(self, char): ''' Sets the currently active character, in case it is (potentially) the first part of a digraph. ''' self._set_char(char, CV) self.active_dgr_a_info = di_a_lt[char]
def _set_digraph_b(self, char): ''' Sets the second part of a digraph. ''' self.has_digraph_b = True # Change the active vowel to the one provided by the second part # of the digraph. self.active_vowel_ro = di_b_lt[char][0] self.active_dgr_b_info = di_b_lt[char]
def _char_ro_vowel(self, char_info, type): ''' Returns the vowel part of a character in rōmaji. ''' if type == CV: return char_info[3] if type == VOWEL or type == XVOWEL: return char_info[0] return None
def _set_char(self, char, type): ''' Sets the currently active character, e.g. ト. We save some information about the character as well. active_char_info contains the full tuple of rōmaji info, and active_ro_vowel contains e.g. 'o' for ト. We also set the character type: either a consonant-vowel pair or a vowel. This aff...
def _set_vowel(self, vowel): ''' Sets the currently active vowel, e.g. ア. Vowels act slightly differently from other characters. If one succeeds the same vowel (or consonant-vowel pair with the same vowel) then it acts like a long vowel marker. E.g. おねえ becomes onē. Hence, either we increment the long vowel marker coun...
backtrack later on in case the 'u' # turns into 'w' when ウ is coupled with a small vowel. if vowel_ro == 'u': self.has_u_lvm = True self._inc_lvmarker() else: # Not the same, so flush the active character and continue. self._set_char(vowel, VOWEL) self.active_vowel_info = vowel_info self.active_vowel = vowel
def _set_xvowel(self, xvowel): ''' Sets the currently active small vowel, e.g. ァ. If an active small vowel has already been set, the current character must be flushed. (Double small vowels don't occur in dictionary words.) After that, we'll set the current character to this small vowel; in essence, it will act like a r...
the currently active character is 'n', we must # flush the character and set this small vowel as the active character. # This is because small vowels cannot affect 'n' like regular # consonant-vowel pairs. curr_is_n = self.active_vowel_ro == 'n' # Special case: if we've got an active vowel with special cases # attached...
> 2 and \ vowel_info[2].get('xv') is not None and \ vowel_info[2]['xv'].get(xvowel_info[0]) is not None: # Decrement the long vowel marker, which was added on the # assumption that the 'u' is a vowel. self._dec_lvmarker() # Save the current vowel. We'll flush the current character, # without this vowel, and then set it...
dgr_b_info = self.active_dgr_b_info if curr_is_n: self._set_char(xvowel, XVOWEL) return if dgr_b_info is not None: if self._is_long_vowel(self.active_vowel_ro, dgr_b_info[0]) or \ self._is_long_vowel(self.active_dgr_b_info[0], dgr_b_info[0]): # Same vowel as the one that's currently active. self._inc_lvmarker() else: #...
def _postprocess_output(self, output): ''' Performs the last modifications before the output is returned. ''' # Replace long vowels with circumflex characters. if self.vowel_style == CIRCUMFLEX_STYLE: try: output = output.translate(vowels_to_circumflexes) except TypeError: # Python 2 will error out here if there are no...
def _flush_stack(self): ''' Returns the final output and resets the machine's state. ''' output = self._postprocess_output(''.join(self.stack)) self._clear_char() self._empty_stack() if not PYTHON_2: return output else: return unicode(output)
def _preprocess_input(self, input): ''' Preprocesses the input before it's split into a list. ''' if not re.search(preprocess_chars, input): # No characters that we need to preprocess, so continue without. return input input = self._add_punctuation_spacing(input) return input
def _preprocess_chars(self, chars): ''' Performs string preprocessing before the main conversion algorithm is used. Simple string replacements (for example, fullwidth rōmaji to regular rōmaji) are performed at this point. ''' chars = self._normalize_dakuten(chars) chars = self._process_repeaters(chars) chars = self._pe...
def _add_punctuation_spacing(self, input): ''' Adds additional spacing to punctuation characters. For example, this puts an extra space after a fullwidth full stop. ''' for replacement in punct_spacing: input = re.sub(replacement[0], replacement[1], input) return input
def _perform_replacements(self, chars): ''' Performs simple key/value string replacements that require no logic. This is used to convert the fullwidth rōmaji, several ligatures, and the punctuation characters. ''' for n in range(len(chars)): char = chars[n] if char in repl: chars[n] = repl[char] # Some replacements mig...
def _normalize_dakuten(self, chars): ''' Replaces the dakuten and handakuten modifier character combinations with single characters. For example, か\u3099か becomes がけ, or は゜は becomes ぱは. ''' prev = None prev_n = None # Set all repeater characters to 0 initially, # then go through the list and remove them all. for n in r...
def _process_repeaters(self, chars): ''' Replace all repeater characters (e.g. turn サヾエ into サザエ). ''' prev = None for n in range(len(chars)): char = chars[n] if char in rpts: # The character is a repeater. chars[n] = prev if char in drpts: # The character is a repeater with dakuten. # If the previous character can hav...
def to_romaji(self, input): ''' Converts kana input to rōmaji and returns the result. ''' input = self._preprocess_input(input) # Preprocess the input, making string replacements where needed. chars = list(input) chars = self._preprocess_chars(chars) chars.append(END_CHAR) for char in chars: if char in di_a: self._set_...
# the machine can't deal with. if self.unknown_strategy == UNKNOWN_DISCARD: continue if self.unknown_strategy == UNKNOWN_RAISE: raise UnexpectedCharacterError if self.unknown_strategy == UNKNOWN_INCLUDE: # The default strategy. self._add_unknown_char(char) return self._flush_stack()
def get_render_data(self, **kwargs): """ Because of the way mixin inheritance works we can't have a default implementation of get_context_data on the this class, so this calls that method if available and returns the resulting context. """ if hasattr(self, 'get_context_data'): data = self.get_context_data(**kwargs) els...
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 complete context \ to the renderer. :param kwarg...
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 something else. If you provide your own render_type be...
self.args = args self.kwargs = kwargs return self.get_as_string(request, *args, **kwargs) except http.Http404: return "" # take name and docstring from class update_wrapper(view, cls, updated=()) return view
def get_tags(self, view_object=None): """ This method return a list of tags to use in the template :return: list of tags """ tags = [force_unicode(self.bundle.get_title())] back_bundle = self.get_back_bundle() if back_bundle and back_bundle != self.bundle: tags.append(force_unicode(back_bundle.get_title())) if view_obj...
def get_render_data(self, **kwargs): """ Returns all data that should be passed to the renderer. By default adds the following arguments: * **bundle** - The bundle that is attached to this view instance. * **url_params** - The url keyword arguments. i.e.: self.kwargs. * **user** - The user attached to this request. * *...
pointed to by the `main_list` attribute of this view's bundle. \ If this is not set, the template's back link will point to the \ admin_site's home page. """ obj = getattr(self, 'object', None) data = dict(self.extra_render_data) data.update(kwargs) data.update({ 'bundle': self.bundle, 'navigation': self.get_navigation...
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 for the view but required groups are set...
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. :param kwargs: Keyword arguments that will always b...
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 APIModelChoiceWidgets or APIManyChoiceWidgets and run...
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.user): raise http.Http404 return super(CMSView, self).dispatch(reque...
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_formfield_overrides`. If a widget is an instance of AP...
override the defaults. for klass in db_field.__class__.mro(): if klass in overides: kwargs = dict(overides[klass], **kwargs) break # Our custom widgets need special init mbundle = None extra = kwargs.pop('widget_kwargs', {}) widget = kwargs.get('widget') if kwargs.get('widget'): if widget and isinstance(widget, type) a...
def log_action(self, instance, action, action_date=None, url="", update_parent=True): """ Store an action in the database using the CMSLog model. The following attributes are calculated and set on the log entry: * **model_repr** - A unicode representation of the instance. * **object_repr** - The verbose_name of the ins...
object pointed to by this bundle's object_view. \ Defaults to True. """ section = None if self.bundle: bundle = self.bundle while bundle.parent: bundle = bundle.parent section = bundle.name # if we have a object view that comes from somewhere else # save it too to update it. changed_object = instance bundle = self.bund...
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.base_filter_kwargs) if filter_kwargs: return [models.Q(**filter_kw...
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`. If a queryset has been set then that queryset wi...
q_objects: queryset = queryset.filter(q) return queryset
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 arguments and matching them with the arguments in `s...
on the gallery model will be: * pk = 3 if parent_lookups is ('pk', 'post__pk') then the filter on the queryset will be: * pk = 3 * post__pk = 2 The model to filter on is found by finding the relationship in self.parent_field and filtering on that model. If a match is found, 'self.queryset` is changed to filter on the p...
else: # 1.8 and 1.9 field, mod, direct, m2m = self.model._meta.get_field(self.parent_field) to = None field_name = None if self.parent_lookups is None: self.parent_lookups = ('pk',) url_params = list(self.bundle.url_params) if url_params and getattr(self.bundle, 'delegated', False): url_params = url_params[:-1] offset ...
'object_id' else: to_field = main_key kwargs[to_field] = main_arg # Build the list of arguments try: obj = to.objects.get(**kwargs) if self.queryset is None: if m2m: self.queryset = getattr(obj, field_name) else: self.queryset = self.model.objects.filter( **{self.parent_field: obj}) return obj except to.DoesNotExist: r...
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, \ defaults to appending 'saved' to the unicode repr...
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: request_kwargs = getattr(self, 'kwargs', {}) kwargs = sup...
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)
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).formfield_for_dbfield(db_field, **kwargs)
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 hasattr(self.model._meta, '_is_view'): form = VersionFilterForm(self.request.GET) ...
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) form = self.get_filter_form() if form: q_objects.extend(form.get_...
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: params = {'formfield_callback': self.formfield_for_dbfield} if ...
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_forms.modelformset_factory(self.model, form_class, fields=self.change_fields...
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 queryset is None: queryset = self.get_queryset() if FormSet: if data: queryset = sel...
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) if formset: for x in formset.empty_form.visible_fields(): if n...
def get_list_data(self, request, **kwargs): """ Returns the data needed for displaying the list. Returns a dictionary that should be treating as context with the following arguments: * **list** - The list of data to be displayed. This is \ an instance of a wrapper class that combines the queryset \ and formset and prov...
default = self.object_list.query.order_by[0] else: default = self.object_list.model._meta.ordering[0] if default.startswith('-'): default = default[1:] default_order = helpers.AdminList.DESC sort_field = request.GET.get('sf', default) order_type = request.GET.get('ot', default_order) queryset = self._sort_queryset(self...
def get_context_data(self, **kwargs): """ Get the context for this view. Adds the following values: * **query_string** - The querystring minus the current page. * **action_links** - The results of the `get_actions` method. """ origin_qs = self._get_query_string(self.request, False) context = { 'query_string': self._get...
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 context. """ if request.GET.get('type') == 'choices...
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. Returns a 'render redirect' to the current url. TODO: Thes...
= self.get_list_data(request, **kwargs) l = data.get('list') formset = None if l and l.formset: formset = l.formset url = self.request.build_absolute_uri() if formset: # Normally calling validate on a formset. # will result in a db call for each pk in # the formset regardless if the form has # changed or not. # To try ...
url=url, update_parent=changecount == 1) return self.render(request, redirect_url=url, message="%s items updated" % changecount, collect_render_data=False) else: return self.render(request, message = msg, **data)
def get_user_modified_lines(self): """ Output: {file_path: [(line_a_start, line_a_end), (line_b_start, line_b_end)]} Lines ranges are sorted and not overlapping """ # I assume that git diff: # - doesn't mix diffs from different files, # - diffs are not overlapping # - diffs are sorted based on line numbers output = {} ...
def prepare_files(self, target_dir): """ Proper version of file needs to be moved to external directory. Because: 1. local files can differ from commited, 2. we can push man branches """ diff_names = self.git_wrapper.get_diff_names(self.remote_sha1, self.local_sha1) files_modified = diff_names.split('\n') extensions = ...
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()
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_THREAD.stop()
def _wait_for_exit(please_stop): """ /dev/null PIPED TO sys.stdin SPEWS INFINITE LINES, DO NOT POLL AS OFTEN """ try: import msvcrt _wait_for_exit_on_windows(please_stop) except: pass cr_count = 0 # COUNT NUMBER OF BLANK LINES while not please_stop: # DEBUG and Log.note("inside wait-for-shutdown loop") if cr_count > 30...
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)
def stop(self): """ BLOCKS UNTIL ALL THREADS HAVE STOPPED THEN RUNS sys.exit(0) """ global DEBUG self_thread = Thread.current() if self_thread != MAIN_THREAD or self_thread != self: Log.error("Only the main thread can call stop() on main thread") DEBUG = True self.please_stop.go() join_errors = [] with self.child_lock:...
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 ): """ FOR USE BY PROCESSES THAT NEVER DIE UNLESS EXTERNAL SHUT...
CHILDREN THEADS ARE DONE with self_thread.child_lock: pending = copy(self_thread.children) children_done = AndSignals(please_stop, len(pending)) children_done.signal.on_go(self.please_stop.go) for p in pending: p.stopped.on_go(children_done.done) try: if allow_exit: _wait_for_exit(please_stop) else: _wait_for_interrupt...
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() DEBUG and Log.note("Thread {{name|quote}} got request to stop", name=self.name)
def join(self, till=None): """ RETURN THE RESULT {"response":r, "exception":e} OF THE THREAD EXECUTION (INCLUDING EXCEPTION, IF EXISTS) """ if self is Thread: Log.error("Thread.join() is not a valid call, use t.join()") with self.child_lock: children = copy(self.children) for c in children: c.join(till=till) DEBUG and ...