Search is not available for this dataset
text
stringlengths
75
104k
def parse_select(cls, text: str) -> Set: """ get columns from select text :param text: col1, col2 :return: ALL_COLUMNS or ['col1', 'col2'] """ if text == '*': return ALL_COLUMNS # None means ALL selected_columns = set(filter(lambda x: x, map(str.strip...
def parse_load_fk(cls, data: Dict[str, List[Dict[str, object]]]) -> Dict[str, List[Dict[str, object]]]: """ :param data:{ <column>: role, <column2>: role, <column>: { 'role': role, 'loadfk': { ... }, }, :return: { ...
def add_condition(self, field_name, op, value): """ Add a query condition and validate it. raise ParamsException if failed. self.view required :param field_name: :param op: :param value: :return: None """ if not isinstance(op, SQL_OP): ...
def _packb2(obj, **options): """ Serialize a Python object into MessagePack bytes. Args: obj: a Python object Kwargs: ext_handlers (dict): dictionary of Ext handlers, mapping a custom type to a callable that packs an instance of the type ...
def _packb3(obj, **options): """ Serialize a Python object into MessagePack bytes. Args: obj: a Python object Kwargs: ext_handlers (dict): dictionary of Ext handlers, mapping a custom type to a callable that packs an instance of the type ...
def _unpackb2(s, **options): """ Deserialize MessagePack bytes into a Python object. Args: s: a 'str' or 'bytearray' containing serialized MessagePack bytes Kwargs: ext_handlers (dict): dictionary of Ext handlers, mapping integer Ext type to a callable that...
def _unpackb3(s, **options): """ Deserialize MessagePack bytes into a Python object. Args: s: a 'bytes' or 'bytearray' containing serialized MessagePack bytes Kwargs: ext_handlers (dict): dictionary of Ext handlers, mapping integer Ext type to a callable th...
def view_bind(app, cls_url, view_cls: Type['BaseView']): """ 将 API 绑定到 web 服务上 :param view_cls: :param app: :param cls_url: :return: """ if view_cls._no_route: return cls_url = cls_url or view_cls.__class__.__name__.lower() def add_route(name, route_info, beacon_info): f...
def add_static(self, prefix, path, **kwargs): """ :param prefix: URL prefix :param path: file directory :param kwargs: :return: """ self.statics.append((prefix, path, kwargs),)
def parse_query_by_json(data): """ ['and', ['==', 't1', 'col1', val1], ['!=', 't1', 'col2', 't2', 'col2'], ['and', ['==', 't1', 'col3', val3], ['!=', 't2', 'col4', val4], ] ] :return: :param data: :return: """ data = json.loads(da...
def validate(method): """ Config option name value validator decorator. """ # Name error template name_error = 'configuration option "{}" is not supported' @functools.wraps(method) def validator(self, name, *args): if name not in self.allowed_opts: raise ValueError(name_...
def run(self, ctx): """ Runs the current phase. """ # Reverse engine assertion if needed if ctx.reverse: self.engine.reverse() if self.engine.empty: raise AssertionError('grappa: no assertions to run') try: # Run assertion in ...
def observe(matcher): """ Internal decorator to trigger operator hooks before/after matcher execution. """ @functools.wraps(matcher) def observer(self, subject, *expected, **kw): # Trigger before hook, if present if hasattr(self, 'before'): ...
def run_matcher(self, subject, *expected, **kw): """ Runs the operator matcher test function. """ # Update assertion expectation self.expected = expected _args = (subject,) if self.kind == OperatorTypes.MATCHER: _args += expected try: ...
def run(self, *args, **kw): """ Runs the current operator with the subject arguments to test. This method is implemented by matchers only. """ log.debug('[operator] run "{}" with arguments: {}'.format( self.__class__.__name__, args )) if self.kind ==...
def operator(name=None, operators=None, aliases=None, kind=None): """ Registers a new operator function in the test engine. Arguments: *args: variadic arguments. **kw: variadic keyword arguments. Returns: function """ def delegator(assertion, subject, expected, *args, *...
def attribute(*args, **kw): """ Registers a new attribute only operator function in the test engine. Arguments: *args: variadic arguments. **kw: variadic keyword arguments. Returns: function """ return operator(kind=Operator.Type.ATTRIBUTE, *args, **kw)
def use(plugin): """ Register plugin in grappa. `plugin` argument can be a function or a object that implement `register` method, which should accept one argument: `grappa.Engine` instance. Arguments: plugin (function|module): grappa plugin object to register. Raises: ValueErr...
def load(): """ Loads the built-in operators into the global test engine. """ for operator in operators: module, symbols = operator[0], operator[1:] path = 'grappa.operators.{}'.format(module) # Dynamically import modules operator = __import__(path, None, None, symbols) ...
def register_operators(*operators): """ Registers one or multiple operators in the test engine. """ def validate(operator): if isoperator(operator): return True raise NotImplementedError('invalid operator: {}'.format(operator)) def register(operator): # Register...
def find_address_file(self): """ Finds the OMXPlayer DBus connection Assumes there is an alive OMXPlayer process. :return: """ possible_address_files = [] while not possible_address_files: # filter is used here as glob doesn't support regexp :( ...
def load(self, source, pause=False): """ Loads a new source (as a file) from ``source`` (a file path or URL) by killing the current ``omxplayer`` process and forking a new one. Args: source (string): Path to the file to play or URL """ self._source = source ...
def set_volume(self, volume): """ Args: float: volume in the interval [0, 10] """ # 0 isn't handled correctly so we have to set it to a very small value to achieve the same purpose if volume == 0: volume = 1e-10 return self._player_interface_proper...
def set_rate(self, rate): """ Set the playback rate of the video as a multiple of the default playback speed Examples: >>> player.set_rate(2) # Will play twice as fast as normal speed >>> player.set_rate(0.5) # Will play half speed """ ...
def pause(self): """ Pause playback """ self._player_interface.Pause() self._is_playing = False self.pauseEvent(self)
def play_pause(self): """ Pause playback if currently playing, otherwise start playing if currently paused. """ self._player_interface.PlayPause() self._is_playing = not self._is_playing if self._is_playing: self.playEvent(self) else: self....
def seek(self, relative_position): """ Seek the video by `relative_position` seconds Args: relative_position (float): The position in seconds to seek to. """ self._player_interface.Seek(Int64(1000.0 * 1000 * relative_position)) self.seekEvent(self, relative_p...
def set_position(self, position): """ Set the video to playback position to `position` seconds from the start of the video Args: position (float): The position in seconds. """ self._player_interface.SetPosition(ObjectPath("/not/used"), Int64(position * 1000.0 * 1000)...
def set_video_pos(self, x1, y1, x2, y2): """ Set the video position on the screen Args: x1 (int): Top left x coordinate (px) y1 (int): Top left y coordinate (px) x2 (int): Bottom right x coordinate (px) y2 (int): Bottom right y coordinate (px) ...
def video_pos(self): """ Returns: (int, int, int, int): Video spatial position (x1, y1, x2, y2) where (x1, y1) is top left, and (x2, y2) is bottom right. All values in px. """ position_string = self._player_interface.VideoPos(ObjectPath('/not...
def set_video_crop(self, x1, y1, x2, y2): """ Args: x1 (int): Top left x coordinate (px) y1 (int): Top left y coordinate (px) x2 (int): Bottom right x coordinate (px) y2 (int): Bottom right y coordinate (px) """ crop = "%s %s %s %s" % (str(...
def is_playing(self): """ Returns: bool: Whether the player is playing """ self._is_playing = (self.playback_status() == "Playing") logger.info("Playing?: %s" % self._is_playing) return self._is_playing
def play_sync(self): """ Play the video and block whilst the video is playing """ self.play() logger.info("Playing synchronously") try: time.sleep(0.05) logger.debug("Wait for playing to start") while self.is_playing(): ...
def play(self): """ Play the video asynchronously returning control immediately to the calling code """ if not self.is_playing(): self.play_pause() self._is_playing = True self.playEvent(self)
def quit(self): """ Quit the player, blocking until the process has died """ if self._process is None: logger.debug('Quit was called after self._process had already been released') return try: logger.debug('Quitting OMXPlayer') proc...
def render_to_response(self, context, **response_kwargs): """ Returns a response with a template depending if the request is ajax or not and it renders with the given context. """ if self.request.is_ajax(): template = self.page_template else: temp...
def translate_value(document_field, form_value): """ Given a document_field and a form_value this will translate the value to the correct result for mongo to use. """ value = form_value if isinstance(document_field, ReferenceField): value = document_field.document_type.objects.get(id=for...
def trim_field_key(document, field_key): """ Returns the smallest delimited version of field_key that is an attribute on document. return (key, left_over_array) """ trimming = True left_over_key_values = [] current_key = field_key while trimming and current_key: if hasattr(d...
def has_edit_permission(self, request): """ Can edit this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_staff
def has_add_permission(self, request): """ Can add this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_staff
def has_delete_permission(self, request): """ Can delete this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_superuser
def get_form_field_dict(self, model_dict): """ Takes a model dictionary representation and creates a dictionary keyed by form field. Each value is a keyed 4 tuple of: (widget, mode_field_instance, model_field_type, field_key) """ return_dict = OrderedDict() # Wo...
def set_form_fields(self, form_field_dict, parent_key=None, field_type=None): """ Set the form fields for every key in the form_field_dict. Params: form_field_dict -- a dictionary created by get_form_field_dict parent_key -- the key for the previous key in the recursive call...
def set_form_field(self, widget, model_field, field_key, default_value): """ Parmams: widget -- the widget to use for displyaing the model_field model_field -- the field on the model to create a form field with field_key -- the name for the field on the form ...
def get_field_value(self, field_key): """ Given field_key will return value held at self.model_instance. If model_instance has not been provided will return None. """ def get_value(document, field_key): # Short circuit the function if we do not have a document ...
def has_digit(string_or_list, sep="_"): """ Given a string or a list will return true if the last word or element is a digit. sep is used when a string is given to know what separates one word from another. """ if isinstance(string_or_list, (tuple, list)): list_length = len(string_or_li...
def make_key(*args, **kwargs): """ Given any number of lists and strings will join them in order as one string separated by the sep kwarg. sep defaults to u"_". Add exclude_last_string=True as a kwarg to exclude the last item in a given string after being split by sep. Note if you only have one w...
def set_fields(self): """Sets existing data to form fields.""" # Get dictionary map of current model if self.is_initialized: self.model_map_dict = self.create_document_dictionary(self.model_instance) else: self.model_map_dict = self.create_document_dictionary(sel...
def set_post_data(self): """ Need to set form data so that validation on all post data occurs and places newly entered form data on the form object. """ self.form.data = self.post_data_dict # Specifically adding list field keys to the form so they are included ...
def get_form(self): """ Generate the form for view. """ self.set_fields() if self.post_data_dict is not None: self.set_post_data() return self.form
def create_doc_dict(self, document, doc_key=None, owner_document=None): """ Generate a dictionary representation of the document. (no recursion) DO NOT CALL DIRECTLY """ # Get doc field for top level documents if owner_document: doc_field = owner_document._f...
def create_list_dict(self, document, list_field, doc_key): """ Genereates a dictionary representation of the list field. Document should be the document the list_field comes from. DO NOT CALL DIRECTLY """ list_dict = {"_document": document} if isinstance(list_fi...
def create_document_dictionary(self, document, document_key=None, owner_document=None): """ Given document generates a dictionary representation of the document. Includes the widget for each for each field in the document. """ ...
def get_widget(model_field, disabled=False): """Choose which widget to display for a field.""" attrs = get_attrs(model_field, disabled) if hasattr(model_field, "max_length") and not model_field.max_length: return forms.Textarea(attrs=attrs) elif isinstance(model_field, DateTimeField): ...
def get_attrs(model_field, disabled=False): """Set attributes on the display widget.""" attrs = {} attrs['class'] = 'span6 xlarge' if disabled or isinstance(model_field, ObjectIdField): attrs['class'] += ' disabled' attrs['readonly'] = 'readonly' return attrs
def get_form_field_class(model_field): """Gets the default form field for a mongoenigne field.""" FIELD_MAPPING = { IntField: forms.IntegerField, StringField: forms.CharField, FloatField: forms.FloatField, BooleanField: forms.BooleanField, DateTimeField: forms.DateTimeF...
def get_document_value(document, key): ''' Returns the display value of a field for a particular MongoDB document. ''' value = getattr(document, key) if isinstance(value, ObjectId): return value if isinstance(document._fields.get(key), URLField): return mark_safe("""<a href="{0}...
def get_qset(self, queryset, q): """Performs filtering against the default queryset returned by mongoengine. """ if self.mongoadmin.search_fields and q: params = {} for field in self.mongoadmin.search_fields: if field == 'id': ...
def get_queryset(self): """Replicates Django CBV `get_queryset()` method, but for MongoEngine. """ if hasattr(self, "queryset") and self.queryset: return self.queryset self.set_mongonaut_base() self.set_mongoadmin() self.document = getattr(self.models, self.d...
def get_initial(self): """Used during adding/editing of data.""" self.query = self.get_queryset() mongo_ids = {'mongo_id': [str(x.id) for x in self.query]} return mongo_ids
def get_context_data(self, **kwargs): """Injects data into the context to replicate CBV ListView.""" context = super(DocumentListView, self).get_context_data(**kwargs) context = self.set_permissions_in_context(context) if not context['has_view_permission']: return HttpRespon...
def post(self, request, *args, **kwargs): """Creates new mongoengine records.""" # TODO - make sure to check the rights of the poster #self.get_queryset() # TODO - write something that grabs the document class better form_class = self.get_form_class() form = self.get_form(form_cl...
def get_context_data(self, **kwargs): """ TODO - possibly inherit this from DocumentEditFormView. This is same thing minus: self.ident = self.kwargs.get('id') self.document = self.document_type.objects.get(pk=self.ident) """ context = super(DocumentAddFormView, self).get_...
def get_mongoadmins(self): """ Returns a list of all mongoadmin implementations for the site """ apps = [] for app_name in settings.INSTALLED_APPS: mongoadmin = "{0}.mongoadmin".format(app_name) try: module = import_module(mongoadmin) except Im...
def set_mongonaut_base(self): """ Sets a number of commonly used attributes """ if hasattr(self, "app_label"): # prevents us from calling this multiple times return None self.app_label = self.kwargs.get('app_label') self.document_name = self.kwargs.get('document_n...
def set_mongoadmin(self): """ Returns the MongoAdmin object for an app_label/document_name style view """ if hasattr(self, "mongoadmin"): return None if not hasattr(self, "document_name"): self.set_mongonaut_base() for mongoadmin in self.get_mongoadmins(...
def set_permissions_in_context(self, context={}): """ Provides permissions for mongoadmin for use in the context""" context['has_view_permission'] = self.mongoadmin.has_view_permission(self.request) context['has_edit_permission'] = self.mongoadmin.has_edit_permission(self.request) conte...
def process_post_form(self, success_message=None): """ As long as the form is set on the view this method will validate the form and save the submitted data. Only call this if you are posting data. The given success_message will be used with the djanog messages framework if the ...
def process_document(self, document, form_key, passed_key): """ Given the form_key will evaluate the document and set values correctly for the document given. """ if passed_key is not None: current_key, remaining_key_array = trim_field_key(document, passed_key) ...
def set_embedded_doc(self, document, form_key, current_key, remaining_key): """Get the existing embedded document if it exists, else created it.""" embedded_doc = getattr(document, current_key, False) if not embedded_doc: embedded_doc = document._fields[current_key].document_type_ob...
def set_list_field(self, document, form_key, current_key, remaining_key, key_array_digit): """1. Figures out what value the list ought to have 2. Sets the list """ document_field = document._fields.get(current_key) # Figure out what value the list ought to have # Non...
def with_tz(request): """ Get the time with TZ enabled """ dt = datetime.now() t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}') c = RequestContext(request) response = t.render(c) return HttpResponse(response)
def without_tz(request): """ Get the time without TZ enabled """ t = Template('{% load tz %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}') c = RequestContext(request) response = t.render(c) return HttpResponse(response)
def is_valid_ip(ip_address): """ Check Validity of an IP address """ try: ip = ipaddress.ip_address(u'' + ip_address) return True except ValueError as e: return False
def is_local_ip(ip_address): """ Check if IP is local """ try: ip = ipaddress.ip_address(u'' + ip_address) return ip.is_loopback except ValueError as e: return None
def process_request(self, request): """ If we can get a valid IP from the request, look up that address in the database to get the appropriate timezone and activate it. Else, use the default. """ if not request: return if not db_loaded: ...
def elastic_query(model, query, session=None, enabled_fields=None): """ Public method for init the class ElasticQuery :model: SQLAlchemy model :query: valid string like a ElasticSearch :session: SQLAlchemy session *optional :enabled_fields: Fields allowed for make a query *optional ...
def search(self): """ This is the most important method """ try: filters = json.loads(self.query) except ValueError: return False result = self.model_query if 'filter'in filters.keys(): result = self.parse_filter(filters['filter']) if ...
def parse_filter(self, filters): """ This method process the filters """ for filter_type in filters: if filter_type == 'or' or filter_type == 'and': conditions = [] for field in filters[filter_type]: if self.is_field_allowed(field): ...
def parse_field(self, field, field_value): """ Parse the operators and traduce: ES to SQLAlchemy operators """ if type(field_value) is dict: # TODO: check operators and emit error operator = list(field_value)[0] if self.verify_operator(operator) is False: ...
def create_query(self, attr): """ Mix all values and make the query """ field = attr[0] operator = attr[1] value = attr[2] model = self.model if '.' in field: field_items = field.split('.') field_name = getattr(model, field_items[0], None) ...
def sort(self, sort_list): """ Sort """ order = [] for sort in sort_list: if sort_list[sort] == "asc": order.append(asc(getattr(self.model, sort, None))) elif sort_list[sort] == "desc": order.append(desc(getattr(self.model, sort, None))) ...
def sendmail(self, msg_from, msg_to, msg): """Remember the recipients.""" SMTP_dummy.msg_from = msg_from SMTP_dummy.msg_to = msg_to SMTP_dummy.msg = msg
def parsemail(raw_message): """Parse message headers, then remove BCC header.""" message = email.parser.Parser().parsestr(raw_message) # Detect encoding detected = chardet.detect(bytearray(raw_message, "utf-8")) encoding = detected["encoding"] print(">>> encoding {}".format(encoding)) for p...
def _create_boundary(message): """Add boundary parameter to multipart message if they are not present.""" if not message.is_multipart() or message.get_boundary() is not None: return message # HACK: Python2 lists do not natively have a `copy` method. Unfortunately, # due to a bug in the Backport ...
def make_message_multipart(message): """Convert a message into a multipart message.""" if not message.is_multipart(): multipart_message = email.mime.multipart.MIMEMultipart('alternative') for header_key in set(message.keys()): # Preserve duplicate headers values = message...
def convert_markdown(message): """Convert markdown in message text to HTML.""" assert message['Content-Type'].startswith("text/markdown") del message['Content-Type'] # Convert the text from markdown and then make the message multipart message = make_message_multipart(message) for payload_item in...
def addattachments(message, template_path): """Add the attachments from the message from the commandline options.""" if 'attachment' not in message: return message, 0 message = make_message_multipart(message) attachment_filepaths = message.get_all('attachment', failobj=[]) template_parent_...
def sendmail(message, sender, recipients, config_filename): """Send email message using Python SMTP library.""" # Read config file from disk to get SMTP server host, port, username if not hasattr(sendmail, "host"): config = configparser.RawConfigParser() config.read(config_filename) ...
def create_sample_input_files(template_filename, database_filename, config_filename): """Create sample template email and database.""" print("Creating sample template email {}".format(template_filename)) if os.path.exists(template_filename): ...
def main(sample=False, dry_run=True, limit=1, no_limit=False, database_filename=DATABASE_FILENAME_DEFAULT, template_filename=TEMPLATE_FILENAME_DEFAULT, config_filename=CONFIG_FILENAME_DEFAULT): """Python API for mailmerge. mailmerge 0.1 by Andrew DeOrio <aw...
def cli(sample, dry_run, limit, no_limit, database_filename, template_filename, config_filename): """Command line interface.""" # pylint: disable=too-many-arguments mailmerge.api.main( sample=sample, dry_run=dry_run, limit=limit, no_limit=no_limit, database_fi...
def _tailCallback(f, uid): """ This is the "callable" version of the continuation, which sould only be accessible from the inside of the function to be continued. An attribute called "C" can be used in order to get back the public version of the continuation (for passing the continuation to another ...
def with_continuations(**c): """ A decorator for defining tail-call optimized functions. Example ------- @with_continuations() def factorial(n, k, self=None): return self(n-1, k*n) if n > 1 else k @with_continuations() def identity(x, self=None): ...
def parse_int_list(string): """ Parses a string of numbers and ranges into a list of integers. Ranges are separated by dashes and inclusive of both the start and end number. Example: parse_int_list("8 9 10,11-13") == [8,9,10,11,12,13] """ integers = [] for comma_part in string.split...
def sanitize_params(method, **kwargs): """ Request params can be extracted from the ``**kwargs`` Arguments starting with `_` will be stripped from it, so they can be used as an argument for the request (eg. "_headers" → "headers" in the kwargs returned by this functi...
def _get_base_url(base_url, api, version): """ create the base url for the api Parameters ---------- base_url : str format of the base_url using {api} and {version} api : str name of the api to use version : str version of ...
async def request(self, method, url, future, headers=None, session=None, encoding=None, **kwargs): """ Make requests to the REST API Parameters ---------- future : asyncio.Future ...
def stream_request(self, method, url, headers=None, _session=None, *args, **kwargs): """ Make requests to the Streaming API Parameters ---------- method : str Method to be used by the request url : str URL of the resourc...
def get_tasks(self): """ Get the tasks attached to the instance Returns ------- list List of tasks (:class:`asyncio.Task`) """ tasks = self._get_tasks() tasks.extend(self._streams.get_tasks(self)) return tasks