INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns the device at the specified index
def device_at_index(self, index): """ Returns the device at the specified index """ if index >= len(self.__xid_cons): raise ValueError("Invalid device index") return self.__xid_cons[index]
gets the value from the device s base timer
def query_base_timer(self): """ gets the value from the device's base timer """ (_, _, time) = unpack('<ccI', self.con.send_xid_command("e3", 6)) return time
Polls the device for user input
def poll_for_response(self): """ Polls the device for user input If there is a keymapping for the device, the key map is applied to the key reported from the device. If a response is waiting to be processed, the response is appended to the internal response_queue ...
Sets the pulse duration for events in miliseconds when activate_line is called
def set_pulse_duration(self, duration): """ Sets the pulse duration for events in miliseconds when activate_line is called """ if duration > 4294967295: raise ValueError('Duration is too long. Please choose a value ' 'less than 4294967296....
Triggers an output line on StimTracker.
def activate_line(self, lines=None, bitmask=None, leave_remaining_lines=False): """ Triggers an output line on StimTracker. There are 8 output lines on StimTracker that can be raised in any combination. To raise lines 1 and 7, for example, you pass in the ...
The inverse of activate_line. If a line is active it deactivates it.
def clear_line(self, lines=None, bitmask=None, leave_remaining_lines=False): """ The inverse of activate_line. If a line is active, it deactivates it. This has the same parameters as activate_line() """ if lines is None and bitmask is None: raise ...
Initializes the device with the proper keymaps and name
def init_device(self): """ Initializes the device with the proper keymaps and name """ try: product_id = int(self._send_command('_d2', 1)) except ValueError: product_id = self._send_command('_d2', 1) if product_id == 0: self._impl = Re...
Send an XID command to the device
def _send_command(self, command, expected_bytes): """ Send an XID command to the device """ response = self.con.send_xid_command(command, expected_bytes) return response
Returns a list of all Xid devices connected to your computer.
def get_xid_devices(): """ Returns a list of all Xid devices connected to your computer. """ devices = [] scanner = XidScanner() for i in range(scanner.device_count()): com = scanner.device_at_index(i) com.open() device = XidDevice(com) devices.append(device) ...
returns device at a given index.
def get_xid_device(device_number): """ returns device at a given index. Raises ValueError if the device at the passed in index doesn't exist. """ scanner = XidScanner() com = scanner.device_at_index(device_number) com.open() return XidDevice(com)
Append receiver.
def connect(self, receiver): """Append receiver.""" if not callable(receiver): raise ValueError('Invalid receiver: %s' % receiver) self.receivers.append(receiver)
Remove receiver.
def disconnect(self, receiver): """Remove receiver.""" try: self.receivers.remove(receiver) except ValueError: raise ValueError('Unknown receiver: %s' % receiver)
Send signal.
def send(self, instance, *args, **kwargs): """Send signal.""" for receiver in self.receivers: receiver(instance, *args, **kwargs)
Support read slaves.
def select(cls, *args, **kwargs): """Support read slaves.""" query = super(Model, cls).select(*args, **kwargs) query.database = cls._get_read_database() return query
Send signals.
def save(self, force_insert=False, **kwargs): """Send signals.""" created = force_insert or not bool(self.pk) self.pre_save.send(self, created=created) super(Model, self).save(force_insert=force_insert, **kwargs) self.post_save.send(self, created=created)
Send signals.
def delete_instance(self, *args, **kwargs): """Send signals.""" self.pre_delete.send(self) super(Model, self).delete_instance(*args, **kwargs) self.post_delete.send(self)
Get database from given URI/ Object.
def get_database(obj, **params): """Get database from given URI/Object.""" if isinstance(obj, string_types): return connect(obj, **params) return obj
Initialize application.
def init_app(self, app, database=None): """Initialize application.""" # Register application if not app: raise RuntimeError('Invalid application.') self.app = app if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['peewee'] = se...
Close connection to database.
def close(self, response): """Close connection to database.""" LOGGER.info('Closing [%s]', os.getpid()) if not self.database.is_closed(): self.database.close() return response
Bind model to self database.
def Model(self): """Bind model to self database.""" Model_ = self.app.config['PEEWEE_MODELS_CLASS'] meta_params = {'database': self.database} if self.slaves and self.app.config['PEEWEE_USE_READ_SLAVES']: meta_params['read_slaves'] = self.slaves Meta = type('Meta', ()...
Return self. application models.
def models(self): """Return self.application models.""" Model_ = self.app.config['PEEWEE_MODELS_CLASS'] ignore = self.app.config['PEEWEE_MODELS_IGNORE'] models = [] if Model_ is not Model: try: mod = import_module(self.app.config['PEEWEE_MODELS_MODULE...
Create a new migration.
def cmd_create(self, name, auto=False): """Create a new migration.""" LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIG...
Run migrations.
def cmd_migrate(self, name=None, fake=False): """Run migrations.""" from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], ...
Rollback migrations.
def cmd_rollback(self, name): """Rollback migrations.""" from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], ...
List migrations.
def cmd_list(self): """List migrations.""" from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('DEBUG') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_ta...
Merge migrations.
def cmd_merge(self): """Merge migrations.""" from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('DEBUG') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_...
Integrate a Flask - Script.
def manager(self): """Integrate a Flask-Script.""" from flask_script import Manager, Command manager = Manager(usage="Migrate database.") manager.add_command('create', Command(self.cmd_create)) manager.add_command('migrate', Command(self.cmd_migrate)) manager.add_command...
DOES NOT WORK WELL WITH MOPIDY Hack from https:// www. daniweb. com/ software - development/ python/ code/ 260268/ restart - your - python - program to support updating the settings since mopidy is not able to do that yet Restarts the current program Note: this function does not return. Any cleanup action ( like saving...
def restart_program(): """ DOES NOT WORK WELL WITH MOPIDY Hack from https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program to support updating the settings, since mopidy is not able to do that yet Restarts the current program Note: this function does not ...
load liac - arff to pandas DataFrame: param dict arff: arff dict created liac - arff: rtype: DataFrame: return: pandas DataFrame
def __load(arff): """ load liac-arff to pandas DataFrame :param dict arff:arff dict created liac-arff :rtype: DataFrame :return: pandas DataFrame """ attrs = arff['attributes'] attrs_t = [] for attr in attrs: if isinstance(attr[1], list): attrs_t.append("%s@{%s}" ...
dump DataFrame to liac - arff: param DataFrame df:: param str relation:: param str description:: rtype: dict: return: liac - arff dict
def __dump(df,relation='data',description=''): """ dump DataFrame to liac-arff :param DataFrame df: :param str relation: :param str description: :rtype: dict :return: liac-arff dict """ attrs = [] for col in df.columns: attr = col.split('@') if attr[1].count('...
dump DataFrame to file: param DataFrame df:: param file fp:
def dump(df,fp): """ dump DataFrame to file :param DataFrame df: :param file fp: """ arff = __dump(df) liacarff.dump(arff,fp)
Insert marker at offset into text and return the marked line.
def markup_line(text, offset, marker='>>!<<'): """Insert `marker` at `offset` into `text`, and return the marked line. .. code-block:: python >>> markup_line('0\\n1234\\n56', 3) 1>>!<<234 """ begin = text.rfind('\n', 0, offset) begin += 1 end = text.find('\n', offset) ...
Initialize a tokenizer. Should only be called by the: func: ~textparser. Parser. tokenize method in the parser.
def tokenize_init(spec): """Initialize a tokenizer. Should only be called by the :func:`~textparser.Parser.tokenize` method in the parser. """ tokens = [Token('__SOF__', '__SOF__', 0)] re_token = '|'.join([ '(?P<{}>{})'.format(name, regex) for name, regex in spec ]) return tokens,...
Tokenize given string text and return a list of tokens. Raises: class: ~textparser. TokenizeError on failure.
def tokenize(self, text): """Tokenize given string `text`, and return a list of tokens. Raises :class:`~textparser.TokenizeError` on failure. This method should only be called by :func:`~textparser.Parser.parse()`, but may very well be overridden if the default implementation do...
Parse given string text and return the parse tree. Raises: class: ~textparser. ParseError on failure.
def parse(self, text, token_tree=False, match_sof=False): """Parse given string `text` and return the parse tree. Raises :class:`~textparser.ParseError` on failure. Returns a parse tree of tokens if `token_tree` is ``True``. .. code-block:: python >>> MyParser().parse('Hell...
Calculates inverse profile - for given y returns x such that f ( x ) = y If given y is not found in the self. y then interpolation is used. By default returns first result looking from left if reverse argument set to True looks from right. If y is outside range of self. y then np. nan is returned.
def x_at_y(self, y, reverse=False): """ Calculates inverse profile - for given y returns x such that f(x) = y If given y is not found in the self.y, then interpolation is used. By default returns first result looking from left, if reverse argument set to True, looks from ...
Width at given level: param level:: return:
def width(self, level): """ Width at given level :param level: :return: """ return self.x_at_y(level, reverse=True) - self.x_at_y(level)
Normalize to 1 over [ - dt + dt ] area if allow_cast is set to True division not in place and casting may occur. If division in place is not possible and allow_cast is False an exception is raised.
def normalize(self, dt, allow_cast=True): """ Normalize to 1 over [-dt, +dt] area, if allow_cast is set to True, division not in place and casting may occur. If division in place is not possible and allow_cast is False an exception is raised. >>> a = Profile([[0, 0], [1,...
Rescales self. y by given factor if allow_cast is set to True and division in place is impossible - casting and not in place division may occur occur. If in place is impossible and allow_cast is set to False - an exception is raised.
def rescale(self, factor=1.0, allow_cast=True): """ Rescales self.y by given factor, if allow_cast is set to True and division in place is impossible - casting and not in place division may occur occur. If in place is impossible and allow_cast is set to False - an exception is ra...
Creating new Curve object in memory with domain passed as a parameter. New domain must include in the original domain. Copies values from original curve and uses interpolation to calculate values for new points in domain.
def change_domain(self, domain): """ Creating new Curve object in memory with domain passed as a parameter. New domain must include in the original domain. Copies values from original curve and uses interpolation to calculate values for new points in domain. Calculate y ...
Provides effective way to compute new domain basing on step and fixp parameters. Then using change_domain () method to create new object with calculated domain and returns it.
def rebinned(self, step=0.1, fixp=0): """ Provides effective way to compute new domain basing on step and fixp parameters. Then using change_domain() method to create new object with calculated domain and returns it. fixp doesn't have to be inside original domain. Retur...
Returns Y value at arg of self. Arg can be a scalar but also might be np. array or other iterable ( like list ). If domain of self is not wide enough to interpolate the value of Y method will return def_val for those arguments instead.
def evaluate_at_x(self, arg, def_val=0): """ Returns Y value at arg of self. Arg can be a scalar, but also might be np.array or other iterable (like list). If domain of self is not wide enough to interpolate the value of Y, method will return def_val for those arguments i...
Method that calculates difference between 2 curves ( or subclasses of curves ). Domain of self must be in domain of curve2 what means min ( self. x ) > = min ( curve2. x ) and max ( self. x ) < = max ( curve2. x ). Might modify self and can return the result or None
def subtract(self, curve2, new_obj=False): """ Method that calculates difference between 2 curves (or subclasses of curves). Domain of self must be in domain of curve2 what means min(self.x) >= min(curve2.x) and max(self.x) <= max(curve2.x). Might modify self, and can ret...
Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.
def alert(text='', title='', button='OK'): """Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.""" messageBoxFunc(0, text, title, MB_OK | MB_SETFOREGROUND | MB_TOPMOST) return button
Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.
def confirm(text='', title='', buttons=['OK', 'Cancel']): """Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.""" retVal = messageBoxFunc(0, text, title, MB_OKCANCEL | MB_ICONQUESTION | MB_SETFOREGROUND | MB_TOPMOST) i...
Function calculates difference between curve1 and curve2 and returns new object which domain is an union of curve1 and curve2 domains Returned object is of type type ( curve1 ) and has same metadata as curve1 object
def subtract(curve1, curve2, def_val=0): """ Function calculates difference between curve1 and curve2 and returns new object which domain is an union of curve1 and curve2 domains Returned object is of type type(curve1) and has same metadata as curve1 object :param curve1: first curve to cal...
Apply a window - length median filter to a 1D array vector.
def medfilt(vector, window): """ Apply a window-length median filter to a 1D array vector. Should get rid of 'spike' value 15. >>> print(medfilt(np.array([1., 15., 1., 1., 1.]), 3)) [1. 1. 1. 1. 1.] The 'edge' case is a bit tricky... >>> print(medfilt(np.array([15., 1., 1., 1., 1.]), 3)) ...
Interpolation on N - D.
def interpn(*args, **kw): """Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi, ...) where the arrays x, y, z, ... define a rectangular grid and a.shape == (len(x), len(y), len(z), ...) are the values interpolate at xi, yi, zi, ... """ method = kw.pop('method', 'cubic') if kw: raise ValueError(...
Interpolation on N - D.
def npinterpn(*args, **kw): """Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi, ...) where the arrays x, y, z, ... define a rectangular grid and a.shape == (len(x), len(y), len(z), ...) are the values interpolate at xi, yi, zi, ... """ method = kw.pop('method', 'cubic') if kw: raise ValueErro...
Generate a dictionary of fields for a given Peewee model.
def model_fields(model, allow_pk=False, only=None, exclude=None, field_args=None, converter=None): """ Generate a dictionary of fields for a given Peewee model. See `model_form` docstring for description of parameters. """ converter = converter or ModelConverter() field_args = ...
Create a wtforms Form for a given Peewee model class::
def model_form(model, base_class=Form, allow_pk=False, only=None, exclude=None, field_args=None, converter=None): """ Create a wtforms Form for a given Peewee model class:: from wtfpeewee.orm import model_form from myproject.myapp.models import User UserForm = model_form(...
Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.
def alert(text='', title='', button=OK_TEXT, root=None, timeout=None): """Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.""" assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox' return _buttonbox(msg=text, title=title, choices=[str(bu...
Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.
def confirm(text='', title='', buttons=[OK_TEXT, CANCEL_TEXT], root=None, timeout=None): """Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.""" assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox' retur...
Displays a message box with text input and OK & Cancel buttons. Returns the text entered or None if Cancel was clicked.
def prompt(text='', title='' , default='', root=None, timeout=None): """Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked.""" assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox' return __fillablebox(text, title, default=d...
Display a msg a title and a set of buttons. The buttons are defined by the members of the choices list. Return the text of the button that the user selected.
def _buttonbox(msg, title, choices, root=None, timeout=None): """ Display a msg, a title, and a set of buttons. The buttons are defined by the members of the choices list. Return the text of the button that the user selected. @arg msg: the msg to be displayed. @arg title: the window title @...
Put the buttons in the buttons frame
def __put_buttons_in_buttonframe(choices): """Put the buttons in the buttons frame""" global __widgetTexts, __firstWidget, buttonsFrame __firstWidget = None __widgetTexts = {} i = 0 for buttonText in choices: tempButton = tk.Button(buttonsFrame, takefocus=1, text=buttonText) _...
Show a box in which a user can enter some text. You may optionally specify some default text which will appear in the enterbox when it is displayed. Returns the text that the user entered or None if he cancels the operation.
def __fillablebox(msg, title='', default='', mask=None, root=None, timeout=None): """ Show a box in which a user can enter some text. You may optionally specify some default text, which will appear in the enterbox when it is displayed. Returns the text that the user entered, or None if he cancels th...
Parse the login xml response: param response: the login response from the RETS server: return: None
def parse(self, response): """ Parse the login xml response :param response: the login response from the RETS server :return: None """ self.headers = response.headers if 'xml' in self.headers.get('Content-Type'): # Got an XML response, likely an error...
Reads lines of XML and delimits strips and returns.
def read_line(line): """Reads lines of XML and delimits, strips, and returns.""" name, value = '', '' if '=' in line: name, value = line.split('=', 1) return [name.strip(), value.strip()]
Takes a response socket connection and iteratively parses and yields the results as python dictionaries.: param response: a Requests response object with stream = True: return:
def generator(self, response): """ Takes a response socket connection and iteratively parses and yields the results as python dictionaries. :param response: a Requests response object with stream=True :return: """ delim = '\t' # Default to tab delimited columns ...
Takes a urlinfo object and returns a flat dictionary.
def flatten_urlinfo(urlinfo, shorter_keys=True): """ Takes a urlinfo object and returns a flat dictionary.""" def flatten(value, prefix=""): if is_string(value): _result[prefix[1:]] = value return try: len(value) except (AttributeError, TypeError): # ...
Create URI and signature headers based on AWS V4 signing process. Refer to https:// docs. aws. amazon. com/ AlexaWebInfoService/ latest/ ApiReferenceArticle. html for request params.: param request_params: dictionary of request parameters: return: URL and header to be passed to requests. get
def create_v4_signature(self, request_params): ''' Create URI and signature headers based on AWS V4 signing process. Refer to https://docs.aws.amazon.com/AlexaWebInfoService/latest/ApiReferenceArticle.html for request params. :param request_params: dictionary of request parameters ...
Provide information about supplied domain as specified by the response group: param domain: Any valid URL: param response_group: Any valid urlinfo response group: return: Traffic and/ or content data of the domain in XML format
def urlinfo(self, domain, response_group = URLINFO_RESPONSE_GROUPS): ''' Provide information about supplied domain as specified by the response group :param domain: Any valid URL :param response_group: Any valid urlinfo response group :return: Traffic and/or content data of the d...
Provide traffic history of supplied domain: param domain: Any valid URL: param response_group: Any valid traffic history response group: return: Traffic and/ or content data of the domain in XML format
def traffichistory(self, domain, response_group=TRAFFICINFO_RESPONSE_GROUPS, myrange=31, start=20070801): ''' Provide traffic history of supplied domain :param domain: Any valid URL :param response_group: Any valid traffic history response group :return: Traffic and/or content da...
Provide category browse information of specified domain: param domain: Any valid URL: param path: Valid category path: param response_group: Any valid traffic history response group: return: Traffic and/ or content data of the domain in XML format
def cat_browse(self, domain, path, response_group=CATEGORYBROWSE_RESPONSE_GROUPS, descriptions='True'): ''' Provide category browse information of specified domain :param domain: Any valid URL :param path: Valid category path :param response_group: Any valid traffic history respo...
Add a capability of the RETS board: param name: The name of the capability: param uri: The capability URI given by the RETS board: return: None
def add_capability(self, name, uri): """ Add a capability of the RETS board :param name: The name of the capability :param uri: The capability URI given by the RETS board :return: None """ parse_results = urlparse(uri) if parse_results.hostname is None: ...
Login to the RETS board and return an instance of Bulletin: return: Bulletin instance
def login(self): """ Login to the RETS board and return an instance of Bulletin :return: Bulletin instance """ response = self._request('Login') parser = OneXLogin() parser.parse(response) self.session_id = response.cookies.get(self.session_id_cookie_name...
Get resource metadata: param resource: The name of the resource to get metadata for: return: list
def get_resource_metadata(self, resource=None): """ Get resource metadata :param resource: The name of the resource to get metadata for :return: list """ result = self._make_metadata_request(meta_id=0, metadata_type='METADATA-RESOURCE') if resource: re...
Get metadata for a given resource: class: param resource: The name of the resource: param resource_class: The name of the class to get metadata from: return: list
def get_table_metadata(self, resource, resource_class): """ Get metadata for a given resource: class :param resource: The name of the resource :param resource_class: The name of the class to get metadata from :return: list """ return self._make_metadata_request(me...
Get possible lookup values for a given field: param resource: The name of the resource: param lookup_name: The name of the the field to get lookup values for: return: list
def get_lookup_values(self, resource, lookup_name): """ Get possible lookup values for a given field :param resource: The name of the resource :param lookup_name: The name of the the field to get lookup values for :return: list """ return self._make_metadata_reque...
Get the Metadata. The Session initializes with COMPACT - DECODED as the format type. If that returns a DTD error then we change to the STANDARD - XML format and try again.: param meta_id: The name of the resource class or lookup to get metadata for: param metadata_type: The RETS metadata type: return: list
def _make_metadata_request(self, meta_id, metadata_type=None): """ Get the Metadata. The Session initializes with 'COMPACT-DECODED' as the format type. If that returns a DTD error then we change to the 'STANDARD-XML' format and try again. :param meta_id: The name of the resource, class, ...
Get the first object from a Resource: param resource: The name of the resource: param object_type: The type of object to fetch: param content_id: The unique id of the item to get objects for: param location: The path to get Objects from: return: Object
def get_preferred_object(self, resource, object_type, content_id, location=0): """ Get the first object from a Resource :param resource: The name of the resource :param object_type: The type of object to fetch :param content_id: The unique id of the item to get objects for ...
Get a list of Objects from a resource: param resource: The resource to get objects from: param object_type: The type of object to fetch: param content_ids: The unique id of the item to get objects for: param object_ids: ids of the objects to download: param location: The path to get Objects from: return: list
def get_object(self, resource, object_type, content_ids, object_ids='*', location=0): """ Get a list of Objects from a resource :param resource: The resource to get objects from :param object_type: The type of object to fetch :param content_ids: The unique id of the item to get o...
Preform a search on the RETS board: param resource: The resource that contains the class to search: param resource_class: The class to search: param search_filter: The query as a dict: param dmql_query: The query in dmql format: param limit: Limit search values count: param offset: Offset for RETS request. Useful when ...
def search(self, resource, resource_class, search_filter=None, dmql_query=None, limit=9999999, offset=0, optional_parameters=None, auto_offset=True, query_type='DMQL2', standard_names=0, response_format='COMPACT-DECODED'): """ Preform a search on the RETS board :par...
Make a _request to the RETS server: param capability: The name of the capability to use to get the URI: param options: Options to put into the _request: return: Response
def _request(self, capability, options=None, stream=False): """ Make a _request to the RETS server :param capability: The name of the capability to use to get the URI :param options: Options to put into the _request :return: Response """ if options is None: ...
Hash the user agent and user agent password Section 3. 10 of https:// www. nar. realtor/ retsorg. nsf/ retsproto1. 7d6. pdf: return: md5
def _user_agent_digest_hash(self): """ Hash the user agent and user agent password Section 3.10 of https://www.nar.realtor/retsorg.nsf/retsproto1.7d6.pdf :return: md5 """ if not self.version: raise MissingVersion("A version is required for user agent auth. The...
minify response html to decrease traffic
def response_minify(self, response): """ minify response html to decrease traffic """ if response.content_type == u'text/html; charset=utf-8': endpoint = request.endpoint or '' view_func = current_app.view_functions.get(endpoint, None) name = ( ...
decorator to mark a view as exempt from htmlmin.
def exempt(self, obj): """ decorator to mark a view as exempt from htmlmin. """ name = '%s.%s' % (obj.__module__, obj.__name__) @wraps(obj) def __inner(*a, **k): return obj(*a, **k) self._exempt_routes.add(name) return __inner
Client supplied raw DMQL ensure quote wrap.
def dmql(query): """Client supplied raw DMQL, ensure quote wrap.""" if isinstance(query, dict): raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required." " Did you mean to pass this to the search_filter parameter? ") ...
Converts the filter dictionary into DMQL
def filter_to_dmql(filter_dict): """Converts the filter dictionary into DMQL""" if not isinstance(filter_dict, (dict, collections.OrderedDict)): raise TypeError('Expected a dictionary type buy got {} instead.'.format(type(filter_dict))) def is_date_time_type(val): """Re...
Get attributes of xml tags in input_dict and creates a dictionary with the attribute name as the key and the attribute value as the value: param input_dict: The xml tag with the attributes and values: return: dict
def get_attributes(input_dict): """ Get attributes of xml tags in input_dict and creates a dictionary with the attribute name as the key and the attribute value as the value :param input_dict: The xml tag with the attributes and values :return: dict """ return {k....
Turns column names in a single string into a dictionary with the key being the column name and the value being the value in that column for each row: param columns_string: A string of column names: param dict_string: A string of values: param delimiter: The delimiter to use to split the column and values: return: dict
def data_columns_to_dict(columns_string, dict_string, delimiter=None): """ Turns column names in a single string into a dictionary with the key being the column name and the value being the value in that column for each row :param columns_string: A string of column names :param d...
Checks the RETS Response Code and handles non - zero answers.: param xml_response_dict:: return: None
def analyze_reply_code(self, xml_response_dict): """ Checks the RETS Response Code and handles non-zero answers. :param xml_response_dict: :return: None """ if 'RETS-STATUS' in xml_response_dict: attributes = self.get_attributes(xml_response_dict['RETS-STATUS'...
Appends the content and object ids how RETS expects them
def ids(self, content_ids, object_ids): """Appends the content and object ids how RETS expects them""" result = [] content_ids = self.split(content_ids, False) object_ids = self.split(object_ids) for cid in content_ids: result.append('{}:{}'.format(cid, ':'.join(obj...
Splits
def split(value, dash_ranges=True): """Splits """ if isinstance(value, list): value = [str(v) for v in value] else: str_value = str(value) dash_matches = re.match(pattern='(\d+)\-(\d+)', string=str_value) if ':' in str_value or ',' in str_value: ...
Set key value to the file.
def set_value(self, key, value): """ Set key value to the file. The fuction will be make the key and value to dictinary formate. If its exist then it will update the current new key value to the file. Arg: key : cache key value : cache value """ ...
Delete the key if the token is expired.
def delete_value(self, key): """ Delete the key if the token is expired. Arg: key : cache key """ response = {} response['status'] = False response['msg'] = "key does not exist" file_cache = self.read_file() if key in file_cache: ...
Open the file and assiging the permission to read/ write and return the content in json formate.
def read_file(self): """ Open the file and assiging the permission to read/write and return the content in json formate. Return : json data """ file_obj = open(self.file, 'r') content = file_obj.read() file_obj.close() if content: cont...
It will convert json content to json string and update into file.
def update_file(self, content): """ It will convert json content to json string and update into file. Return: Boolean True/False """ updated_content = json.dumps(content) file_obj = open(self.file, 'r+') file_obj.write(str(updated_content)) file_o...
Parses RETS metadata using the COMPACT - DECODED format: param response:: param metadata_type:: return:
def parse(self, response, metadata_type): """ Parses RETS metadata using the COMPACT-DECODED format :param response: :param metadata_type: :return: """ xml = xmltodict.parse(response.text) self.analyze_reply_code(xml_response_dict=xml) base = xml.g...
Parses RETS metadata using the STANDARD - XML format: param response: requests Response object: param metadata_type: string: return parsed: list
def parse(self, response, metadata_type): """ Parses RETS metadata using the STANDARD-XML format :param response: requests Response object :param metadata_type: string :return parsed: list """ xml = xmltodict.parse(response.text) self.analyze_reply_code(xm...
From this multipart/ parallel ; boundary = 874e43d27ec6d83f30f37841bdaf90c7 ; charset = utf - 8 get this -- 874e43d27ec6d83f30f37841bdaf90c7
def _get_multiparts(response): """ From this 'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8' get this --874e43d27ec6d83f30f37841bdaf90c7 """ boundary = None for part in response.headers.get('Content-Type', '').split(';'): ...
Parse multiple objects from the RETS feed. A lot of string methods are used to handle the response before encoding it back into bytes for the object.: param response: The response from the feed: return: list of SingleObjectParser
def parse_image_response(self, response): """ Parse multiple objects from the RETS feed. A lot of string methods are used to handle the response before encoding it back into bytes for the object. :param response: The response from the feed :return: list of SingleObjectParser ...
Parse a single object from the RETS feed: param response: The response from the RETS server: return: Object
def parse_image_response(self, response): """ Parse a single object from the RETS feed :param response: The response from the RETS server :return: Object """ if 'xml' in response.headers.get('Content-Type'): # Got an XML response, likely an error code. ...
Auth is used to call the AUTH API of CricketAPI. Access token required for every request call to CricketAPI. Auth functional will post user Cricket API app details to server and return the access token.
def auth(self): """ Auth is used to call the AUTH API of CricketAPI. Access token required for every request call to CricketAPI. Auth functional will post user Cricket API app details to server and return the access token. Return: Access token ...
It will return json response based on given url params and methods. Arg: params: dictionary url: url format method: default get support method post Return: json data
def get_response(self, url, params={}, method="get"): """ It will return json response based on given url, params and methods. Arg: params: 'dictionary' url: 'url' format method: default 'get', support method 'post' Return: json data ...
Getting the valid access token.
def get_active_token(self): """ Getting the valid access token. Access token expires every 24 hours, It will expires then it will generate a new token. Return: active access token """ expire_time = self.store_handler.has_value("expires") ...
Calling the Match API. Arg: match_key: key of the match card_type: optional default to full_card. Accepted values are micro_card summary_card & full_card. Return: json data
def get_match(self, match_key, card_type="full_card"): """ Calling the Match API. Arg: match_key: key of the match card_type: optional, default to full_card. Accepted values are micro_card, summary_card & full_card. Return: json data ...
Calling the Recent Matches API.
def get_recent_matches(self, card_type="micro_card"): """ Calling the Recent Matches API. Arg: card_type: optional, default to micro_card. Accepted values are micro_card & summary_card. Return: json data """ recent_matches_url = self.api...
Calling the Player Stats API Args: player_key: Key of the player board_key: key of the board Return: json data
def get_player_stats(self, player_key, board_key): """ Calling the Player Stats API Args: player_key: Key of the player board_key: key of the board Return: json data """ player_stats_url = self.api_path + 'player/' + player_key + '/leag...