sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def search_read_all(self, domain, order, fields, batch_size=500, context=None, offset=0, limit=None): """ An endless iterator that iterates over records. :param domain: A search domain :param order: The order clause for search read :param fields: The fiel...
An endless iterator that iterates over records. :param domain: A search domain :param order: The order clause for search read :param fields: The fields argument for search_read :param batch_size: The optimal batch size when sending paginated requests
entailment
def find(self, filter=None, page=1, per_page=10, fields=None, context=None): """ Find records that match the filter. Pro Tip: The fields could have nested fields names if the field is a relationship type. For example if you were looking up an order and also want to get the shipp...
Find records that match the filter. Pro Tip: The fields could have nested fields names if the field is a relationship type. For example if you were looking up an order and also want to get the shipping address country then fields would be: `['shipment_address', 'shipment_address.co...
entailment
def attach(self, id, filename, url): """Add an attachmemt to record from url :param id: ID of record :param filename: File name of attachment :param url: Public url to download file from. """ Attachment = self.client.model('ir.attachment') return Attachment.add_a...
Add an attachmemt to record from url :param id: ID of record :param filename: File name of attachment :param url: Public url to download file from.
entailment
def refresh_if_needed(self): """ Refresh the status of the task from server if required. """ if self.state in (self.PENDING, self.STARTED): try: response, = self._fetch_result()['tasks'] except (KeyError, ValueError): raise Exceptio...
Refresh the status of the task from server if required.
entailment
def get_product_inventory(product_id, warehouse_ids): """ Return the product inventory in each location. The returned response will look like:: { 12: { // Product ID 4: { // Location ID 'quantity_on_hand': 12.0, 'quantity_...
Return the product inventory in each location. The returned response will look like:: { 12: { // Product ID 4: { // Location ID 'quantity_on_hand': 12.0, 'quantity_available': 8.0 }, 5: { // Loca...
entailment
def get_customer(code): """ Fetch a customer with the code. Returns None if the customer is not found. """ Party = client.model('party.party') results = Party.find([('code', '=', code)]) if results: return results[0]['id']
Fetch a customer with the code. Returns None if the customer is not found.
entailment
def get_address(customer_id, data): """ Easier to fetch the addresses of customer and then check one by one. You can get fancy by using some validation mechanism too """ Address = client.model('party.address') addresses = Address.find( [('party', '=', customer_id)], fields=[ ...
Easier to fetch the addresses of customer and then check one by one. You can get fancy by using some validation mechanism too
entailment
def create_address(customer_id, data): """ Create an address and return the id """ Address = client.model('party.address') Country = client.model('country.country') Subdivision = client.model('country.subdivision') country, = Country.find([('code', '=', data['country'])]) state, = Subdi...
Create an address and return the id
entailment
def create_customer(name, email, phone): """ Create a customer with the name. Then attach the email and phone as contact methods """ Party = client.model('party.party') ContactMechanism = client.model('party.contact_mechanism') party, = Party.create([{'name': name}]) # Bulk create the ...
Create a customer with the name. Then attach the email and phone as contact methods
entailment
def create_order(order): """ Create an order on fulfil from order_details. See the calling function below for an example of the order_details """ SaleOrder = client.model('sale.sale') SaleOrderLine = client.model('sale.line') # Check if customer exists, if not create one customer_id = g...
Create an order on fulfil from order_details. See the calling function below for an example of the order_details
entailment
def model_base(fulfil_client, cache_backend=None, cache_expire=10 * 60): """ Return a Base Model class that binds to the fulfil client instance and the cache instance. This design is inspired by the declarative base pattern in SQL Alchemy. """ return type( 'BaseModel', (Model,),...
Return a Base Model class that binds to the fulfil client instance and the cache instance. This design is inspired by the declarative base pattern in SQL Alchemy.
entailment
def all(self): """ Return the results represented by this Query as a list. .. versionchanged:: 0.10.0 Returns an iterator that lazily loads records instead of fetching thousands of records at once. """ return self.rpc_model.search_read_all( ...
Return the results represented by this Query as a list. .. versionchanged:: 0.10.0 Returns an iterator that lazily loads records instead of fetching thousands of records at once.
entailment
def count(self): "Return a count of rows this Query would return." return self.rpc_model.search_count( self.domain, context=self.context )
Return a count of rows this Query would return.
entailment
def exists(self): """ A convenience method that returns True if a record satisfying the query exists """ return self.rpc_model.search_count( self.domain, context=self.context ) > 0
A convenience method that returns True if a record satisfying the query exists
entailment
def show_active_only(self, state): """ Set active only to true or false on a copy of this query """ query = self._copy() query.active_only = state return query
Set active only to true or false on a copy of this query
entailment
def filter_by(self, **kwargs): """ Apply the given filtering criterion to a copy of this Query, using keyword expressions. """ query = self._copy() for field, value in kwargs.items(): query.domain.append( (field, '=', value) ) ...
Apply the given filtering criterion to a copy of this Query, using keyword expressions.
entailment
def filter_by_domain(self, domain): """ Apply the given domain to a copy of this query """ query = self._copy() query.domain = domain return query
Apply the given domain to a copy of this query
entailment
def first(self): """ Return the first result of this Query or None if the result doesn't contain any row. """ results = self.rpc_model.search_read( self.domain, None, 1, self._order_by, self.fields, context=self.context ) return results and...
Return the first result of this Query or None if the result doesn't contain any row.
entailment
def get(self, id): """ Return an instance based on the given primary key identifier, or None if not found. This returns a record whether active or not. """ ctx = self.context.copy() ctx['active_test'] = False results = self.rpc_model.search_read( ...
Return an instance based on the given primary key identifier, or None if not found. This returns a record whether active or not.
entailment
def limit(self, limit): """ Apply a LIMIT to the query and return the newly resulting Query. """ query = self._copy() query._limit = limit return query
Apply a LIMIT to the query and return the newly resulting Query.
entailment
def offset(self, offset): """ Apply an OFFSET to the query and return the newly resulting Query. """ query = self._copy() query._offset = offset return query
Apply an OFFSET to the query and return the newly resulting Query.
entailment
def one(self): """ Return exactly one result or raise an exception. Raises fulfil_client.exc.NoResultFound if the query selects no rows. Raises fulfil_client.exc.MultipleResultsFound if multiple rows are found. """ results = self.rpc_model.search_read( ...
Return exactly one result or raise an exception. Raises fulfil_client.exc.NoResultFound if the query selects no rows. Raises fulfil_client.exc.MultipleResultsFound if multiple rows are found.
entailment
def order_by(self, *criterion): """ apply one or more ORDER BY criterion to the query and return the newly resulting Query All existing ORDER BY settings can be suppressed by passing None - this will suppress any ORDER BY configured on mappers as well. """ query ...
apply one or more ORDER BY criterion to the query and return the newly resulting Query All existing ORDER BY settings can be suppressed by passing None - this will suppress any ORDER BY configured on mappers as well.
entailment
def delete(self): """ Delete all records matching the query. Warning: This is a desctructive operation. Not every model allows deletion of records and several models even restrict based on status. For example, deleting products that have been transacted is restricted. A...
Delete all records matching the query. Warning: This is a desctructive operation. Not every model allows deletion of records and several models even restrict based on status. For example, deleting products that have been transacted is restricted. Another example is sales orders...
entailment
def archive(self): """ Archives (soft delete) all the records matching the query. This assumes that the model allows archiving (not many do - especially transactional documents). Internal implementation sets the active field to False. """ ids = self.rpc_model.se...
Archives (soft delete) all the records matching the query. This assumes that the model allows archiving (not many do - especially transactional documents). Internal implementation sets the active field to False.
entailment
def _logged_in_successful(data): """ Test the login status from the returned communication of the server. :param data: bytes received from server during login :type data: list of bytes :return boolean, True when you are logged in. """ if re.match(r'^:(te...
Test the login status from the returned communication of the server. :param data: bytes received from server during login :type data: list of bytes :return boolean, True when you are logged in.
entailment
def connect(self): """ Connect to Twitch """ # Do not use non-blocking stream, they are not reliably # non-blocking # s.setblocking(False) # s.settimeout(1.0) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connect_host = "irc.twitch.tv" ...
Connect to Twitch
entailment
def _push_from_buffer(self): """ Push a message on the stack to the IRC stream. This is necessary to avoid Twitch overflow control. """ if len(self.buffer) > 0: if time.time() - self.last_sent_time > 5: try: message = self.buffer.po...
Push a message on the stack to the IRC stream. This is necessary to avoid Twitch overflow control.
entailment
def join_channel(self, channel): """ Join a different chat channel on Twitch. Note, this function returns immediately, but the switch might take a moment :param channel: name of the channel (without #) """ self.s.send(('JOIN #%s\r\n' % channel).encode('utf-8')) ...
Join a different chat channel on Twitch. Note, this function returns immediately, but the switch might take a moment :param channel: name of the channel (without #)
entailment
def _parse_message(self, data): """ Parse the bytes received from the socket. :param data: the bytes received from the socket :return: """ if TwitchChatStream._check_has_ping(data): self._send_pong() if TwitchChatStream._check_has_channel(data): ...
Parse the bytes received from the socket. :param data: the bytes received from the socket :return:
entailment
def twitch_receive_messages(self): """ Call this function to process everything received by the socket This needs to be called frequently enough (~10s) Twitch logs off users not replying to ping commands. :return: list of chat messages received. Each message is a dict ...
Call this function to process everything received by the socket This needs to be called frequently enough (~10s) Twitch logs off users not replying to ping commands. :return: list of chat messages received. Each message is a dict with the keys ['channel', 'username', 'message']
entailment
def reset(self): """ Reset the videostream by restarting ffmpeg """ if self.ffmpeg_process is not None: # Close the previous stream try: self.ffmpeg_process.send_signal(signal.SIGINT) except OSError: pass comma...
Reset the videostream by restarting ffmpeg
entailment
def send_video_frame(self, frame): """Send frame of shape (height, width, 3) with values between 0 and 1. Raises an OSError when the stream is closed. :param frame: array containing the frame. :type frame: numpy array with shape (height, width, 3) containing values b...
Send frame of shape (height, width, 3) with values between 0 and 1. Raises an OSError when the stream is closed. :param frame: array containing the frame. :type frame: numpy array with shape (height, width, 3) containing values between 0.0 and 1.0
entailment
def send_audio(self, left_channel, right_channel): """Add the audio samples to the stream. The left and the right channel should have the same shape. Raises an OSError when the stream is closed. :param left_channel: array containing the audio signal. :type left_channel: numpy ar...
Add the audio samples to the stream. The left and the right channel should have the same shape. Raises an OSError when the stream is closed. :param left_channel: array containing the audio signal. :type left_channel: numpy array with shape (k, ) containing values between -1....
entailment
def send_audio(self, left_channel, right_channel): """Add the audio samples to the stream. The left and the right channel should have the same shape. :param left_channel: array containing the audio signal. :type left_channel: numpy array with shape (k, ) containing values be...
Add the audio samples to the stream. The left and the right channel should have the same shape. :param left_channel: array containing the audio signal. :type left_channel: numpy array with shape (k, ) containing values between -1.0 and 1.0. k can be any integer :param right_...
entailment
def send_video_frame(self, frame, frame_counter=None): """send frame of shape (height, width, 3) with values between 0 and 1 :param frame: array containing the frame. :type frame: numpy array with shape (height, width, 3) containing values between 0.0 and 1.0 :param ...
send frame of shape (height, width, 3) with values between 0 and 1 :param frame: array containing the frame. :type frame: numpy array with shape (height, width, 3) containing values between 0.0 and 1.0 :param frame_counter: frame position number within stream. Pr...
entailment
def send_audio(self, left_channel, right_channel, frame_counter=None): """Add the audio samples to the stream. The left and the right channel should have the same shape. :param left_channel: array containing the audio signal. :typ...
Add the audio samples to the stream. The left and the right channel should have the same shape. :param left_channel: array containing the audio signal. :type left_channel: numpy array with shape (k, ) containing values between -1.0 and 1.0. l can be any integer :param right_...
entailment
def import_attribute(self, path): """ Import an attribute from a module. """ module = '.'.join(path.split('.')[:-1]) function = path.split('.')[-1] module = importlib.import_module(module) return getattr(module, function)
Import an attribute from a module.
entailment
def get_next(self, request): """ Returns a url to redirect to after the login / signup. """ if 'next' in request.session: next = request.session['next'] del request.session['next'] elif 'next' in request.GET: next = request.GET.get('next') ...
Returns a url to redirect to after the login / signup.
entailment
def inactive_response(self, request): """ Return an inactive message. """ inactive_url = getattr(settings, 'LOGIN_INACTIVE_REDIRECT_URL', '') if inactive_url: return HttpResponseRedirect(inactive_url) else: return self.error_to_response(request, {'...
Return an inactive message.
entailment
def create_profile(self, user, save=False, **kwargs): """ Create a profile model. :param user: A user object :param save: If this is set, the profile will be saved to DB straight away :type save: bool """ profile = self.get_model()(user=user, **kwargs...
Create a profile model. :param user: A user object :param save: If this is set, the profile will be saved to DB straight away :type save: bool
entailment
def get_or_create_profile(self, user, save=False, **kwargs): """ Return a profile from DB or if there is none, create a new one. :param user: A user object :param save: If set, a new profile will be saved. :type save: bool """ try: profile = self.get_...
Return a profile from DB or if there is none, create a new one. :param user: A user object :param save: If set, a new profile will be saved. :type save: bool
entailment
def get_session_data(self, request): """ Return a tuple ``(user, profile, client)`` from the session. """ user = request.session['%suser' % SESSION_KEY] profile = request.session['%sprofile' % SESSION_KEY] client = request.session['%sclient' % SESSION_KEY] return ...
Return a tuple ``(user, profile, client)`` from the session.
entailment
def send_login_signal(self, request, user, profile, client): """ Send a signal that a user logged in. This signal should be sent only if the user was *not* logged into Django. """ signals.login.send(sender=profile.__class__, user=user, profile=profile, client=client, ...
Send a signal that a user logged in. This signal should be sent only if the user was *not* logged into Django.
entailment
def send_connect_signal(self, request, user, profile, client): """ Send a signal that a user connected a social profile to his Django account. This signal should be sent *only* when the a new social connection was created. """ signals.connect.send(sender=profile.__class__...
Send a signal that a user connected a social profile to his Django account. This signal should be sent *only* when the a new social connection was created.
entailment
def request_access_token(self, params): """ Foursquare does not accept POST requests to retrieve an access token, so we'll be doing a GET request instead. """ return self.request(self.access_token_url, method="GET", params=params)
Foursquare does not accept POST requests to retrieve an access token, so we'll be doing a GET request instead.
entailment
def openid_form(parser, token): """ Render OpenID form. Allows to pre set the provider:: {% openid_form "https://www.google.com/accounts/o8/id" %} Also creates custom button URLs by concatenating all arguments after the provider's URL {% openid_form "https://www.google.com/accounts/o8/id" S...
Render OpenID form. Allows to pre set the provider:: {% openid_form "https://www.google.com/accounts/o8/id" %} Also creates custom button URLs by concatenating all arguments after the provider's URL {% openid_form "https://www.google.com/accounts/o8/id" STATIC_URL "image/for/google.jpg" %}
entailment
def get_initial_data(self, request, user, profile, client): """ Return initial data for the setup form. The function can be controlled with ``SOCIALREGISTRATION_INITIAL_DATA_FUNCTION``. :param request: The current request object :param user: The unsaved user object :para...
Return initial data for the setup form. The function can be controlled with ``SOCIALREGISTRATION_INITIAL_DATA_FUNCTION``. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API client
entailment
def get_context(self, request, user, profile, client): """ Return additional context for the setup view. The function can be controlled with ``SOCIALREGISTRATION_SETUP_CONTEXT_FUNCTION``. :param request: The current request object :param user: The unsaved user object :pa...
Return additional context for the setup view. The function can be controlled with ``SOCIALREGISTRATION_SETUP_CONTEXT_FUNCTION``. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :param client: The API clie...
entailment
def generate_username_and_redirect(self, request, user, profile, client): """ Generate a username and then redirect the user to the correct place. This method is called when ``SOCIALREGISTRATION_GENERATE_USERNAME`` is set. :param request: The current request object :pa...
Generate a username and then redirect the user to the correct place. This method is called when ``SOCIALREGISTRATION_GENERATE_USERNAME`` is set. :param request: The current request object :param user: The unsaved user object :param profile: The unsaved profile object :...
entailment
def get(self, request): """ When signing a new user up - either display a setup form, or generate the username automatically. """ if request.user.is_authenticated(): return HttpResponseRedirect(self.get_next(request)) try: user, profile, client =...
When signing a new user up - either display a setup form, or generate the username automatically.
entailment
def post(self, request): """ Save the user and profile, login and send the right signals. """ if request.user.is_authenticated(): return self.error_to_response(request, dict( error=_("You are already logged in."))) try: user, profile, cli...
Save the user and profile, login and send the right signals.
entailment
def post(self, request): """ Create a client, store it in the user's session and redirect the user to the API provider to authorize our app and permissions. """ request.session['next'] = self.get_next(request) client = self.get_client()() request.session[self.get_...
Create a client, store it in the user's session and redirect the user to the API provider to authorize our app and permissions.
entailment
def get(self, request): """ Called after the user is redirected back to our application. Tries to: - Complete the OAuth / OAuth2 flow - Redirect the user to another view that deals with login, connecting or user creation. """ try: client ...
Called after the user is redirected back to our application. Tries to: - Complete the OAuth / OAuth2 flow - Redirect the user to another view that deals with login, connecting or user creation.
entailment
def get(self, request): """ Called after authorization was granted and the OAuth flow successfully completed. Tries to: - Connect the remote account if the user is logged in already - Log the user in if a local profile of the remote account exists a...
Called after authorization was granted and the OAuth flow successfully completed. Tries to: - Connect the remote account if the user is logged in already - Log the user in if a local profile of the remote account exists already - Create a user and profile o...
entailment
def client(self, verifier=None): """ Return the correct client depending on which stage of the OAuth process we're in. """ # We're just starting out and don't have neither request nor access # token. Return the standard client if not self._request_token and not se...
Return the correct client depending on which stage of the OAuth process we're in.
entailment
def _get_request_token(self): """ Fetch a request token from `self.request_token_url`. """ params = { 'oauth_callback': self.get_callback_url() } response, content = self.client().request(self.request_token_url, "POST", b...
Fetch a request token from `self.request_token_url`.
entailment
def _get_access_token(self, verifier=None): """ Fetch an access token from `self.access_token_url`. """ response, content = self.client(verifier).request( self.access_token_url, "POST") content = smart_unicode(content) if not response['statu...
Fetch an access token from `self.access_token_url`.
entailment
def get_request_token(self): """ Return the request token for this API. If we've not fetched it yet, go out, request and memoize it. """ if self._request_token is None: self._request_token = self._get_request_token() return self._request_token
Return the request token for this API. If we've not fetched it yet, go out, request and memoize it.
entailment
def get_access_token(self, verifier=None): """ Return the access token for this API. If we've not fetched it yet, go out, request and memoize it. """ if self._access_token is None: self._access_token, self._access_token_dict = self._get_access_token(verifier)...
Return the access token for this API. If we've not fetched it yet, go out, request and memoize it.
entailment
def get_redirect_url(self, **kwargs): """ Return the authorization/authentication URL signed with the request token. """ params = { 'oauth_token': self.get_request_token().key, } return '%s?%s' % (self.auth_url, urllib.urlencode(params))
Return the authorization/authentication URL signed with the request token.
entailment
def complete(self, GET): """ When redirect back to our application, try to complete the flow by requesting an access token. If the access token request fails, it'll throw an `OAuthError`. Tries to complete the flow by validating against the `GET` paramters recei...
When redirect back to our application, try to complete the flow by requesting an access token. If the access token request fails, it'll throw an `OAuthError`. Tries to complete the flow by validating against the `GET` paramters received.
entailment
def request(self, url, method="GET", params=None, headers=None): """ Make signed requests against `url`. """ params = params or {} headers = headers or {} logger.debug("URL: %s", url) logger.debug("Method: %s", method) logger.debug("Headers: %s", headers)...
Make signed requests against `url`.
entailment
def get_redirect_url(self, state='', **kwargs): """ Assemble the URL to where we'll be redirecting the user to to request permissions. """ params = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': self.get_callback_url(**...
Assemble the URL to where we'll be redirecting the user to to request permissions.
entailment
def request_access_token(self, params): """ Request the access token from `self.access_token_url`. The default behaviour is to use a `POST` request, but some services use `GET` requests. Individual clients can override this method to use the correct HTTP method. """ ...
Request the access token from `self.access_token_url`. The default behaviour is to use a `POST` request, but some services use `GET` requests. Individual clients can override this method to use the correct HTTP method.
entailment
def _get_access_token(self, code, **params): """ Fetch an access token with the provided `code`. """ params.update({ 'code': code, 'client_id': self.client_id, 'client_secret': self.secret, 'redirect_uri': self.get_callback_url(), }...
Fetch an access token with the provided `code`.
entailment
def get_access_token(self, code=None, **params): """ Return the memoized access token or go out and fetch one. """ if self._access_token is None: if code is None: raise ValueError(_('Invalid code.')) self.access_token_dict = self._get_...
Return the memoized access token or go out and fetch one.
entailment
def complete(self, GET): """ Complete the OAuth2 flow by fetching an access token with the provided code in the GET parameters. """ if 'error' in GET: raise OAuthError( _("Received error while obtaining access token from %s: %s") % ( ...
Complete the OAuth2 flow by fetching an access token with the provided code in the GET parameters.
entailment
def request(self, url, method="GET", params=None, headers=None, is_signed=True): """ Make a request against ``url``. By default, the request is signed with an access token, but can be turned off by passing ``is_signed=False``. """ params = params or {} headers = headers o...
Make a request against ``url``. By default, the request is signed with an access token, but can be turned off by passing ``is_signed=False``.
entailment
def request_access_token(self, params): """ Google requires correct content-type for POST requests """ return self.client().request(self.access_token_url, method="POST", body=urllib.urlencode(params), headers={'Content-Type':'application/x-www-form-urlencoded'})
Google requires correct content-type for POST requests
entailment
def readInternalC(self): """Return internal temperature value in degrees celsius.""" v = self._read32() # Ignore bottom 4 bits of thermocouple data. v >>= 4 # Grab bottom 11 bits as internal temperature data. internal = v & 0x7FF if v & 0x800: # Negati...
Return internal temperature value in degrees celsius.
entailment
def readTempC(self): """Return the thermocouple temperature value in degrees celsius.""" v = self._read32() # Check for error reading value. if v & 0x7: return float('NaN') # Check if signed bit is set. if v & 0x80000000: # Negative value, take 2's...
Return the thermocouple temperature value in degrees celsius.
entailment
def readLinearizedTempC(self): """Return the NIST-linearized thermocouple temperature value in degrees celsius. See https://learn.adafruit.com/calibrating-sensors/maxim-31855-linearization for more info. """ # MAX31855 thermocouple voltage reading in mV thermocoupleVoltage = (sel...
Return the NIST-linearized thermocouple temperature value in degrees celsius. See https://learn.adafruit.com/calibrating-sensors/maxim-31855-linearization for more info.
entailment
def escape_quotes(self, val): """ Escape any quotes in a value """ if self.is_string(val) and self._in_quotes(val, self.quote): # make sure any previously escaped quotes are not re-escaped middle = self.remove_quotes(val).replace("\\" + self.quote, self.quote) ...
Escape any quotes in a value
entailment
def standardise_quotes(self, val): """ Change the quotes used to wrap a value to the pprint default E.g. "val" to 'val' or 'val' to "val" """ if self._in_quotes(val, self.altquote): middle = self.remove_quotes(val) val = self.add_quotes(middle) re...
Change the quotes used to wrap a value to the pprint default E.g. "val" to 'val' or 'val' to "val"
entailment
def process_key_dict(self, key, d, level): """ Process key value dicts e.g. METADATA "key" "value" """ # add any composite level comments comments = d.get("__comments__", {}) lines = [] self._add_type_comment(level, comments, lines) lines += [self.add_st...
Process key value dicts e.g. METADATA "key" "value"
entailment
def process_dict(self, d, level, comments): """ Process keys and values within a block """ lines = [] for k, v in d.items(): if not self.__is_metadata(k): qk = self.quoter.add_quotes(k) qv = self.quoter.add_quotes(v) li...
Process keys and values within a block
entailment
def process_config_dict(self, key, d, level): """ Process the CONFIG block """ lines = [] for k, v in d.items(): k = "CONFIG {}".format(self.quoter.add_quotes(k.upper())) v = self.quoter.add_quotes(v) lines.append(self.__format_line(self.whites...
Process the CONFIG block
entailment
def process_repeated_list(self, key, lst, level): """ Process blocks of repeated keys e.g. FORMATOPTION """ lines = [] for v in lst: k = key.upper() v = self.quoter.add_quotes(v) lines.append(self.__format_line(self.whitespace(level, 1), k, v)...
Process blocks of repeated keys e.g. FORMATOPTION
entailment
def format_pair_list(self, key, pair_list, level): """ Process lists of pairs (e.g. PATTERN block) """ lines = [self.add_start_line(key, level)] list_spacer = self.spacer * (level + 2) pairs = ["{}{} {}".format(list_spacer, p[0], p[1]) for p in pair_list] lines ...
Process lists of pairs (e.g. PATTERN block)
entailment
def format_repeated_pair_list(self, key, root_list, level): """ Process (possibly) repeated lists of pairs e.g. POINTs blocks """ lines = [] def depth(L): return isinstance(L, (tuple, list)) and max(map(depth, L)) + 1 if depth(root_list) == 2: #...
Process (possibly) repeated lists of pairs e.g. POINTs blocks
entailment
def is_hidden_container(self, key, val): """ The key is not one of the Mapfile keywords, and its values are a list """ if key in ("layers", "classes", "styles", "symbols", "labels", "outputformats", "features", "scaletokens", "composites") a...
The key is not one of the Mapfile keywords, and its values are a list
entailment
def pprint(self, composites): """ Print out a nicely indented Mapfile """ # if only a single composite is used then cast to list # and allow for multiple root composites if composites and not isinstance(composites, list): composites = [composites] l...
Print out a nicely indented Mapfile
entailment
def format_value(self, attr, attr_props, value): """ TODO - refactor and add more specific tests (particularly for expressions) """ if isinstance(value, bool): return str(value).upper() if any(i in ["enum"] for i in attr_props): if not isinstance(value, n...
TODO - refactor and add more specific tests (particularly for expressions)
entailment
def process_attribute(self, type_, attr, value, level): """ Process one of the main composite types (see the type_ value) """ attr_props = self.get_attribute_properties(type_, attr) value = self.format_value(attr, attr_props, value) line = self.__format_line(self.whitesp...
Process one of the main composite types (see the type_ value)
entailment
def process_composite_comment(self, level, comments, key): """ Process comments for composites such as MAP, LAYER etc. """ if key not in comments: comment = "" else: value = comments[key] spacer = self.whitespace(level, 0) if isins...
Process comments for composites such as MAP, LAYER etc.
entailment
def create_animation(img_files): """ See http://pillow.readthedocs.io/en/4.2.x/handbook/image-file-formats.html?highlight=append_images#saving """ open_images = [] for fn in img_files: print(fn) im = Image.open(fn) open_images.append(im) im = open_images[0] im.save...
See http://pillow.readthedocs.io/en/4.2.x/handbook/image-file-formats.html?highlight=append_images#saving
entailment
def start(self, children): """ Parses a MapServer Mapfile Parsing of partial Mapfiles or lists of composites is also possible """ composites = [] for composite_dict in children: if False and self.include_position: key_token = composite_dict[1...
Parses a MapServer Mapfile Parsing of partial Mapfiles or lists of composites is also possible
entailment
def composite(self, t): """ Handle the composite types e.g. CLASS..END t is a list in the form [[Token(__LAYER36, 'LAYER')], [OrderedDict([...])]] """ if len(t) == 1: return t[0] # metadata and values - already processed key_token = t[0][0] attribut...
Handle the composite types e.g. CLASS..END t is a list in the form [[Token(__LAYER36, 'LAYER')], [OrderedDict([...])]]
entailment
def check_composite_tokens(self, name, tokens): """ Return the key and contents of a KEY..END block for PATTERN, POINTS, and PROJECTION """ assert len(tokens) >= 2 key = tokens[0] assert key.value.lower() == name assert tokens[-1].value.lower() == "end" ...
Return the key and contents of a KEY..END block for PATTERN, POINTS, and PROJECTION
entailment
def process_value_pairs(self, tokens, type_): """ Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed """ key, body = self.check_composite_tokens(type_, tokens) key_name = self.key_name(key) ...
Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed
entailment
def func_call(self, t): """ For function calls e.g. TEXT (tostring([area],"%.2f")) """ func, params = t func_name = func.value func.value = "({}({}))".format(func_name, params) return func
For function calls e.g. TEXT (tostring([area],"%.2f"))
entailment
def add_metadata_comments(self, d, metadata): """ Any duplicate keys will be replaced with the last duplicate along with comments """ if len(metadata) > 2: string_pairs = metadata[1:-1] # get all metadata pairs for sp in string_pairs: # get the r...
Any duplicate keys will be replaced with the last duplicate along with comments
entailment
def assign_comments(self, tree, comments): """ Capture any comments in the tree header_comments stores comments preceding a node """ comments = list(comments) comments.sort(key=lambda c: c.line) idx_by_line = {0: 0} # {line_no: comment_idx} for i, c i...
Capture any comments in the tree header_comments stores comments preceding a node
entailment
def parse(self, text, fn=None): """ Parse the Mapfile """ if PY2 and not isinstance(text, unicode): # specify Unicode for Python 2.7 text = unicode(text, 'utf-8') if self.expand_includes: text = self.load_includes(text, fn=fn) try: ...
Parse the Mapfile
entailment
def add_child(graph, child_id, child_label, parent_id, colour): """ http://www.graphviz.org/doc/info/shapes.html#polygon """ node = pydot.Node(child_id, style="filled", fillcolor=colour, label=child_label, shape="polygon", fontname=FONT) graph.add_node(node) graph.add_edge(pydot.Edge(parent_id, ...
http://www.graphviz.org/doc/info/shapes.html#polygon
entailment
def get_schema_path(self, schemas_folder): """ Return a file protocol URI e.g. file:///D:/mappyfile/mappyfile/schemas/ on Windows and file:////home/user/mappyfile/mappyfile/schemas/ on Linux """ # replace any Windows path back slashes with forward slashes schemas_folder ...
Return a file protocol URI e.g. file:///D:/mappyfile/mappyfile/schemas/ on Windows and file:////home/user/mappyfile/mappyfile/schemas/ on Linux
entailment
def get_schema_validator(self, schema_name): """ Had to remove the id property from map.json or it uses URLs for validation See various issues at https://github.com/Julian/jsonschema/pull/306 """ if schema_name not in self.schemas: schema_file = self.get_schema_file(...
Had to remove the id property from map.json or it uses URLs for validation See various issues at https://github.com/Julian/jsonschema/pull/306
entailment
def create_message(self, rootdict, path, error, add_comments): """ Add a validation comment to the dictionary path is the path to the error object, it can be empty if the error is in the root object http://python-jsonschema.readthedocs.io/en/latest/errors/#jsonschema.exceptions.Validatio...
Add a validation comment to the dictionary path is the path to the error object, it can be empty if the error is in the root object http://python-jsonschema.readthedocs.io/en/latest/errors/#jsonschema.exceptions.ValidationError.absolute_path It can also reference an object in a list e.g. [u'laye...
entailment
def validate(self, value, add_comments=False, schema_name="map"): """ verbose - also return the jsonschema error details """ validator = self.get_schema_validator(schema_name) error_messages = [] if isinstance(value, list): for d in value: er...
verbose - also return the jsonschema error details
entailment