INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Get or create the dashboard comment in this issue.
def get_or_create(cls, issue, header, text=None): """Get or create the dashboard comment in this issue. """ for comment in get_comments(issue): try: if comment.body.splitlines()[0] == header: obj = cls(comment, header) break ...
Register a new hook. Not required (see :py:func:`.connect` method) :param str name: The hook name :return: Django signal :rtype: :py:class:`django.dispatch.Signal`
def register(self, name): """ Register a new hook. Not required (see :py:func:`.connect` method) :param str name: The hook name :return: Django signal :rtype: :py:class:`django.dispatch.Signal` """ signal = Signal(providing_args=['args', 'kwargs']) self._...
Connects a function to a hook.\ Creates the hook (name) if it does not exists :param str name: The hook name :param callable func: A function reference used as a callback :param class sender: Optional sender __class__ to which the\ func should respond. Default will match all ...
def connect(self, name, func, sender=None, dispatch_uid=None): """ Connects a function to a hook.\ Creates the hook (name) if it does not exists :param str name: The hook name :param callable func: A function reference used as a callback :param class sender: Optional sen...
Disconnects a function from a hook :param str name: The hook name :param callable func: A function reference registered previously :param str dispatch_uid: optional unique id,\ see :py:class:`django.dispatch.Signal` for more info.
def disconnect(self, name, func, dispatch_uid=None): """ Disconnects a function from a hook :param str name: The hook name :param callable func: A function reference registered previously :param str dispatch_uid: optional unique id,\ see :py:class:`django.dispatch.Signal...
Sends the signal. Return every function response\ that was hooked to hook-name as a list: [(func, response), ] :param str name: The hook name :param class sender: Optional sender __class__ to which\ registered callback should match (see :py:func:`.connect` method) :return: Signa...
def send(self, name, sender=None, **kwargs): """ Sends the signal. Return every function response\ that was hooked to hook-name as a list: [(func, response), ] :param str name: The hook name :param class sender: Optional sender __class__ to which\ registered callback sho...
Use the factories to create a host object. :param factories: a list of functions that return host objects (Hostname, IPv4Address, IPv6Address) for valid arguments :param value: a value to be passed as argument to factories :returns: an object representing the value, created by one of the factories....
def create_host(factories, value): """Use the factories to create a host object. :param factories: a list of functions that return host objects (Hostname, IPv4Address, IPv6Address) for valid arguments :param value: a value to be passed as argument to factories :returns: an object representing the v...
Test if the object is a subdomain of the other. :param other: the object to which we compare this instance :returns: True if this instance is a subdomain of the other
def is_subdomain(self, other): """Test if the object is a subdomain of the other. :param other: the object to which we compare this instance :returns: True if this instance is a subdomain of the other """ compared = other.value if hasattr(other, 'value') else other try: ...
Assemble the given iterable of mnemonics, operands, and lables. A convienience over constructing individual Instruction and Operand objects, the output of this function can be directly piped to :class:`~jawa.attributes.code.CodeAttribute.assemble()` to produce executable bytecode. As a simple exam...
def assemble(code): """ Assemble the given iterable of mnemonics, operands, and lables. A convienience over constructing individual Instruction and Operand objects, the output of this function can be directly piped to :class:`~jawa.attributes.code.CodeAttribute.assemble()` to produce executable...
Register a hook. @hook: a HookBase subclass reference.
def register(self, hook): """ Register a hook. @hook: a HookBase subclass reference. """ assert callable(hook), \ "Hook must be a callable" assert issubclass(hook, HookBase), \ "The hook does not inherit from HookBase" self._registry.appe...
Save all the forms :param \*args: Positional arguments passed to the forms :param \*\*kwargs: Keyword arguments passed to the forms :return: Sequence of returned values by all the forms as tuples of (instance, result) :rtype: list
def save(self, *args, **kwargs): """ Save all the forms :param \*args: Positional arguments passed to the forms :param \*\*kwargs: Keyword arguments passed to the forms :return: Sequence of returned values by all the forms as tuples of (instance, result) :rtype: list ...
Cleans email address. :param addresses: List of strings (email addresses) :return: List of strings (cleaned email addresses)
def clean_addresses(addresses): """ Cleans email address. :param addresses: List of strings (email addresses) :return: List of strings (cleaned email addresses) """ if addresses is None: return [] addresses = addresses.replace("\'", "") address_list = re.split('[,;]', addresses) ...
Cleans a single email address. :param address: String (email address) :return: String (clean email address)
def clean_address(address): """ Cleans a single email address. :param address: String (email address) :return: String (clean email address) """ if isinstance(address, header.Header): return clean_address(address.encode('ascii')) elif isinstance(address, str): address = addre...
Extracts body text from an mbox message. :param message: Mbox message :return: String
def get_body(message): """ Extracts body text from an mbox message. :param message: Mbox message :return: String """ try: sm = str(message) body_start = sm.find('iamunique', sm.find('iamunique')+1) body_start = sm.find('Content-Transfer-Encoding', body_start+1) bo...
Takes a list and extends it with lists of data, which is extracted from mbox messages. :param mboxfile: Mbox file name/path :param mailTable: A list (of lists) :return: An extended list of lists
def write_table(mboxfile, mailTable): """ Takes a list and extends it with lists of data, which is extracted from mbox messages. :param mboxfile: Mbox file name/path :param mailTable: A list (of lists) :return: An extended list of lists """ mail_box_contents = mailbox.mbox(mboxfile) ...
Extracts all mbox messages from mbox files in mbox_path. :param mbox_path: Path to an mbox file OR a directory containing mbox files. :return: A Pandas DataFrame with messages as rows/observations.
def mbox_to_pandas(mbox_path): """ Extracts all mbox messages from mbox files in mbox_path. :param mbox_path: Path to an mbox file OR a directory containing mbox files. :return: A Pandas DataFrame with messages as rows/observations. """ if os.path.isfile(mbox_path): mbox_files = [mbox_pa...
Lookup all builtin Attribute subclasses, load them, and return a dict
def get_attribute_classes() -> Dict[str, Attribute]: """ Lookup all builtin Attribute subclasses, load them, and return a dict """ attribute_children = pkgutil.iter_modules( importlib.import_module('jawa.attributes').__path__, prefix='jawa.attributes.' ) result = {} for _, n...
Read the ConstantPool from the file-like object `source`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param source: Any file-like object providing `read()`
def unpack(self, source: IO): """ Read the ConstantPool from the file-like object `source`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param source: Any file-like obje...
Write the AttributeTable to the file-like object `out`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when saving a ClassFile. :param out: Any file-like object providing `write()`
def pack(self, out: IO): """ Write the AttributeTable to the file-like object `out`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when saving a ClassFile. :param out: Any file-like object providin...
Creates a new attribute of `type_`, appending it to the attribute table and returning it.
def create(self, type_, *args, **kwargs) -> Any: """ Creates a new attribute of `type_`, appending it to the attribute table and returning it. """ attribute = type_(self, *args, **kwargs) self._table.append(attribute) return attribute
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
def main(arguments=None): """ *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* """ # setup the command-line util settings su = tools( arguments=arguments, docString=__doc__, logLevel="WARNING", opti...
unit : SECOND | MICROSECOND | MINUTE | HOUR | DAY | MONTH | YEAR
def p_unit(self, p): """unit : SECOND | MICROSECOND | MINUTE | HOUR | DAY | MONTH | YEAR """ unit = TimexLexer.reserved_words[p[1]] unit = unit.lower() p[0] = unit
Extracts data from a local git repository. Mutates _data. :param str source: The path to a local git repository. :param args: Arbitrary arguments for extensibility. :param kwargs: Arbitrary keyword arguments for extensibility. :return: None
def _extract(self, source, *args, **kwargs): """ Extracts data from a local git repository. Mutates _data. :param str source: The path to a local git repository. :param args: Arbitrary arguments for extensibility. :param kwargs: Arbitrary keyword arguments for extensibility. ...
Returns a table of git log data, with "commits" as rows/observations. :param bool drop_collections: Defaults to True. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame
def commits(self, drop_collections=True): """ Returns a table of git log data, with "commits" as rows/observations. :param bool drop_collections: Defaults to True. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame """ base_df = s...
Get valid location header values from responses. :param url: a URL address. If a HEAD request sent to it fails because the address has invalid schema, times out or there is a connection error, the generator yields nothing. :returns: valid redirection addresses. If a request for ...
def get_locations(self, url): """Get valid location header values from responses. :param url: a URL address. If a HEAD request sent to it fails because the address has invalid schema, times out or there is a connection error, the generator yields nothing. :returns: valid redirec...
Get valid location header values for all given URLs. The returned values are new, that is: they do not repeat any value contained in the original input. Only unique values are yielded. :param urls: a list of URL addresses :returns: valid location header values from responses ...
def get_new_locations(self, urls): """Get valid location header values for all given URLs. The returned values are new, that is: they do not repeat any value contained in the original input. Only unique values are yielded. :param urls: a list of URL addresses :returns: ...
Get URLs and their redirection addresses. :param urls: a list of URL addresses :returns: an instance of CachedIterable containing given URLs and valid location header values of their responses
def get_urls_and_locations(self, urls): """Get URLs and their redirection addresses. :param urls: a list of URL addresses :returns: an instance of CachedIterable containing given URLs and valid location header values of their responses """ location_generator = self.get_n...
An OCSP GET request contains the DER-in-base64 encoded OCSP request in the HTTP request URL.
def _handle_get(self, request_data): """ An OCSP GET request contains the DER-in-base64 encoded OCSP request in the HTTP request URL. """ der = base64.b64decode(request_data) ocsp_request = self._parse_ocsp_request(der) return self._build_http_response(ocsp_reques...
An OCSP POST request contains the DER encoded OCSP request in the HTTP request body.
def _handle_post(self): """ An OCSP POST request contains the DER encoded OCSP request in the HTTP request body. """ der = request.body.read() ocsp_request = self._parse_ocsp_request(der) return self._build_http_response(ocsp_request)
Create and return an OCSP response from an OCSP request.
def _build_ocsp_response(self, ocsp_request: OCSPRequest) -> OCSPResponse: """ Create and return an OCSP response from an OCSP request. """ # Get the certificate serial tbs_request = ocsp_request['tbs_request'] request_list = tbs_request['request_list'] if len(req...
for show in page['Shows']: if show['VenueId'] == self.getId(): self._make_show(show)
def _buildPark(self): token = self._get_token() ride_page = self._get_request(token, self.getUrl()) show_page = self._get_request(token, SHOW_URL) for ride in ride_page['Results']: if ride['VenueId'] == self.getId(): self._make_attraction(ride) """ ...
Hook tag to call within templates :param dict context: This is automatically passed,\ contains the template state/variables :param str name: The hook which will be dispatched :param \*args: Positional arguments, will be passed to hook callbacks :param \*\*kwargs: Keyword arguments, will be passed t...
def hook_tag(context, name, *args, **kwargs): """ Hook tag to call within templates :param dict context: This is automatically passed,\ contains the template state/variables :param str name: The hook which will be dispatched :param \*args: Positional arguments, will be passed to hook callbacks ...
Helper to include in your own templatetag, for static TemplateHooks Example:: import myhooks from hooks.templatetags import template_hook_collect @register.simple_tag(takes_context=True) def hook(context, name, *args, **kwargs): return template_hook_collect(myhooks, na...
def template_hook_collect(module, hook_name, *args, **kwargs): """ Helper to include in your own templatetag, for static TemplateHooks Example:: import myhooks from hooks.templatetags import template_hook_collect @register.simple_tag(takes_context=True) def hook(context, n...
Extracts data from mbox files. Mutates _data. :param str source: The path to one or more mbox files. :param args: Arbitrary arguments for extensibility. :param kwargs: Arbitrary keyword arguments for extensibility. :return: None
def _extract(self, source, *args, **kwargs): """ Extracts data from mbox files. Mutates _data. :param str source: The path to one or more mbox files. :param args: Arbitrary arguments for extensibility. :param kwargs: Arbitrary keyword arguments for extensibility. :return...
Returns a table of mbox message data, with "messages" as rows/observations. :param bool drop_collections: Defaults to True. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame
def emails(self, drop_collections = True): """ Returns a table of mbox message data, with "messages" as rows/observations. :param bool drop_collections: Defaults to True. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame """ base...
Returns a table of mbox message data, with "sender/recipient" pairs as rows/observations. .. note:: Rows may have a recipient from either "TO" or "CC". SendType column specifies this for each row. .. note:: drop_collections is not available for this method, since there are no...
def sends(self): """ Returns a table of mbox message data, with "sender/recipient" pairs as rows/observations. .. note:: Rows may have a recipient from either "TO" or "CC". SendType column specifies this for each row. .. note:: drop_collections is not availabl...
Create a WebhookMetadata from a comment added to an issue.
def build_from_issue_comment(gh_token, body): """Create a WebhookMetadata from a comment added to an issue. """ if body["action"] in ["created", "edited"]: github_con = Github(gh_token) repo = github_con.get_repo(body['repository']['full_name']) issue = repo.get_issue(body['issue']['...
Create a WebhookMetadata from an opening issue text.
def build_from_issues(gh_token, body): """Create a WebhookMetadata from an opening issue text. """ if body["action"] in ["opened", "edited"]: github_con = Github(gh_token) repo = github_con.get_repo(body['repository']['full_name']) issue = repo.get_issue(body['issue']['number']) ...
Return method tagged "order" in the handler.
def orders(self): """Return method tagged "order" in the handler. """ return [order_cmd for order_cmd in dir(self.handler) if getattr(getattr(self.handler, order_cmd), "bot_order", False)]
Sets the value of the field `name` to `value`, which is `True` or `False`.
def set(self, name, value): """ Sets the value of the field `name` to `value`, which is `True` or `False`. """ flag = self.flags[name] self._value = (self.value | flag) if value else (self.value & ~flag)
Returns this `Flags` object's fields as a dictionary.
def to_dict(self): """ Returns this `Flags` object's fields as a dictionary. """ return dict((k, self.get(k)) for k in self.flags.keys())
Add the given value to the collection. :param host: an ip address or a hostname :raises InvalidHostError: raised when the given value is not a valid ip address nor a hostname
def add(self, host_value): """Add the given value to the collection. :param host: an ip address or a hostname :raises InvalidHostError: raised when the given value is not a valid ip address nor a hostname """ host_obj = self._host_factory(host_value) if self._get...
Get an item matching the given host object. The item may be either a parent domain or identical value. Parent domains and existing identical values always precede insertion point for given value - therefore, we treat an item just before insertion point as potential match. :para...
def _get_match(self, host_object): """Get an item matching the given host object. The item may be either a parent domain or identical value. Parent domains and existing identical values always precede insertion point for given value - therefore, we treat an item just before inse...
Add a new host to the collection. Before a new hostname can be added, all its subdomains already present in the collection must be removed. Since the collection is sorted, we can limit our search for them to a slice of the collection starting from insertion point and ending with ...
def _add_new(self, host_object): """Add a new host to the collection. Before a new hostname can be added, all its subdomains already present in the collection must be removed. Since the collection is sorted, we can limit our search for them to a slice of the collection starting ...
Parses a Method descriptor as described in section 4.3.3 of the JVM specification.
def method_descriptor(descriptor: str) -> MethodDescriptor: """ Parses a Method descriptor as described in section 4.3.3 of the JVM specification. """ end_para = descriptor.find(')') returns = descriptor[end_para + 1:] args = descriptor[1:end_para] return MethodDescriptor( parse...
Uses a tiny state machine to parse JVM descriptors. To get useful wrappers around the results, use :py:func:`jawa.core.descriptor.method_descriptor` or :py:func:`jawa.core.descriptor.field_descriptor`.
def parse_descriptor(descriptor: str) -> list: """ Uses a tiny state machine to parse JVM descriptors. To get useful wrappers around the results, use :py:func:`jawa.core.descriptor.method_descriptor` or :py:func:`jawa.core.descriptor.field_descriptor`. """ # States: # 10 == NORMAL, # ...
create serializer field
def make_field(self, **kwargs): """ create serializer field """ kwargs['required'] = False kwargs['allow_null'] = True return self.field_class(**kwargs)
attach filter to filterset gives a name to use to extract arguments from querydict
def bind(self, name, filterset): """ attach filter to filterset gives a name to use to extract arguments from querydict """ if self.name is not None: name = self.name self.field.bind(name, self)
extract value extarct value from querydict and convert it to native missing and empty values result to None
def parse_value(self, querydict): """ extract value extarct value from querydict and convert it to native missing and empty values result to None """ value = self.field.get_value(querydict) if value in (None, fields.empty, ''): return None return self...
return filtering params
def filter_params(self, value): """ return filtering params """ if value is None: return {} key = self.target if self.lookup_type is not None: key += '__' + self.lookup_type return { key: value }
return filtering params
def filter_params(self, value): """ return filtering params """ if value is None: return {} target = ".".join(self.field.source_attrs) return { '__raw__': { target + ".$id": value } }
return filtering params
def filter_params(self, value): """ return filtering params """ if value is None: return {} val_min = value.get('min', None) val_max = value.get('max', None) params = {} if val_min == val_max: return { self.target: val_min } key = self.t...
*print the original webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF
def _print_original_webpage( self): """*print the original webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF """ self.log.debug('starting the ``_print_original_webpage`` method') if not self.title: r = requests.get(self.url)...
*get the PDF* **Return:** - ``pdfPath`` -- the path to the generated PDF
def get(self): """ *get the PDF* **Return:** - ``pdfPath`` -- the path to the generated PDF """ self.log.debug('starting the ``get`` method') # APPEND TO FILENAME? if not self.append: self.append = "" if not self.readability: ...
*print the parsed/cleaned webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF
def _print_parsed_webpage( self): """*print the parsed/cleaned webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF """ self.log.debug('starting the ``_print_parsed_webpage()`` method') from polyglot import htmlCleaner cleaner = ht...
Return the base directory
def get_base_dir(): """ Return the base directory """ return os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]
Check if a password is valid
def is_valid_password(password): """ Check if a password is valid """ pattern = re.compile(r"^.{4,25}$") return password and pattern.match(password)
Check if url is valid
def is_valid_url(url): """ Check if url is valid """ regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... #r'localhost|' #localhost... r'\d{1,3}\.\d{...
Convert time H:M:S to seconds
def time_to_seconds(t): """ Convert time H:M:S to seconds """ l = list(map(int, t.split(':'))) return sum(n * sec for n, sec in zip(l[::-1], (1, 60, 3600)))
Generate a random string
def generate_random_string(length=8): """ Generate a random string """ char_set = string.ascii_uppercase + string.digits return ''.join(random.sample(char_set * (length - 1), length))
Stop word filter returns list
def filter_stopwords(str): """ Stop word filter returns list """ STOPWORDS = ['a', 'able', 'about', 'across', 'after', 'all', 'almost', 'also', 'am', 'among', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'been', 'but', 'by', 'can', 'cannot', ...
Check if a port is open :param port: :param host: :return bool:
def is_port_open(port, host="127.0.0.1"): """ Check if a port is open :param port: :param host: :return bool: """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((host, int(port))) s.shutdown(2) return True except Exception as e: r...
Convert bytes into human readable
def convert_bytes(bytes): """ Convert bytes into human readable """ bytes = float(bytes) if bytes >= 1099511627776: terabytes = bytes / 1099511627776 size = '%.2fT' % terabytes elif bytes >= 1073741824: gigabytes = bytes / 1073741824 size = '%.2fG' % gigabytes ...
Return a list of chunks :param l: List :param n: int The number of items per chunk :return: List
def list_chunks(l, n): """ Return a list of chunks :param l: List :param n: int The number of items per chunk :return: List """ if n < 1: n = 1 return [l[i:i + n] for i in range(0, len(l), n)]
Check if any items in a list is in a string :params l: dict :params s: string :return bool:
def any_in_string(l, s): """ Check if any items in a list is in a string :params l: dict :params s: string :return bool: """ return any([i in l for i in l if i in s])
To add path to jinja so it can be loaded :param flask_app: :param path: :return:
def add_path_to_jinja(flask_app, path): """ To add path to jinja so it can be loaded :param flask_app: :param path: :return: """ template_dir = path my_loader = jinja2.ChoiceLoader([ flask_app.jinja_loader, jinja2.FileSystemLoader(template_dir) ]) flask_app.jinja_...
A multiprocess decorator :param func: :return:
def bg_process(func): """ A multiprocess decorator :param func: :return: """ @functools.wraps(func) def wrapper(*args, **kwargs): p = multiprocessing.Process(target=func, args=args, kwargs=kwargs) p.start() return wrapper
A threading decorator :param func: :return:
def bg_thread(func): """ A threading decorator :param func: :return: """ @functools.wraps(func) def wrapper(*args, **kwargs): p = threading.Thread(target=func, args=args, kwargs=kwargs) p.start() return wrapper
Wrapper for lxml`s find.
def find(self, node, path): """Wrapper for lxml`s find.""" return node.find(path, namespaces=self.namespaces)
Wrapper for lxml`s xpath.
def xpath(self, node, path): """Wrapper for lxml`s xpath.""" return node.xpath(path, namespaces=self.namespaces)
Return list of files/directories. Each item is a dict. Keys: 'path', 'creationdate', 'displayname', 'length', 'lastmodified', 'isDir'.
def ls(self, path, offset=None, amount=None): """ Return list of files/directories. Each item is a dict. Keys: 'path', 'creationdate', 'displayname', 'length', 'lastmodified', 'isDir'. """ def parseContent(content): result = [] root = ET.fromstri...
Return dict with size of Ya.Disk. Keys: 'available', 'used'.
def df(self): """Return dict with size of Ya.Disk. Keys: 'available', 'used'.""" def parseContent(content): root = ET.fromstring(content) return { 'available': root.find(".//d:quota-available-bytes", namespaces=self.namespaces).text, 'used': root...
Create directory. All part of path must be exists. Raise exception when path already exists.
def mkdir(self, path): """Create directory. All part of path must be exists. Raise exception when path already exists.""" resp = self._sendRequest("MKCOL", path) if resp.status_code != 201: if resp.status_code == 409: raise YaDiskException(409, "Part of path {} does ...
Delete file or directory.
def rm(self, path): """Delete file or directory.""" resp = self._sendRequest("DELETE", path) # By documentation server must return 200 "OK", but I get 204 "No Content". # Anyway file or directory have been removed. if not (resp.status_code in (200, 204)): raise YaDis...
Copy file or directory.
def cp(self, src, dst): """Copy file or directory.""" _check_dst_absolute(dst) resp = self._sendRequest("COPY", src, {'Destination': dst}) if resp.status_code != 201: raise YaDiskException(resp.status_code, resp.content)
Upload file.
def upload(self, file, path): """Upload file.""" with open(file, "rb") as f: resp = self._sendRequest("PUT", path, data=f) if resp.status_code != 201: raise YaDiskException(resp.status_code, resp.content)
Download remote file to disk.
def download(self, path, file): """Download remote file to disk.""" resp = self._sendRequest("GET", path) if resp.status_code == 200: with open(file, "wb") as f: f.write(resp.content) else: raise YaDiskException(resp.status_code, resp.content)
Publish file or folder and return public url
def publish(self, path): """Publish file or folder and return public url""" def parseContent(content): root = ET.fromstring(content) prop = root.find(".//d:prop", namespaces=self.namespaces) return prop.find("{urn:yandex:disk:meta}public_url").text.strip() ...
Make public file or folder private (delete public url)
def unpublish(self, path): """Make public file or folder private (delete public url)""" data = """ <propertyupdate xmlns="DAV:"> <remove> <prop> <public_url xmlns="urn:yandex:disk:meta" /> </prop> </remove> </propertyupdate> """ _check_dst_absolute(pat...
Writes a single instruction of `opcode` with `operands` to `fout`. :param fout: Any file-like object providing ``write()``. :param start_pos: The current position in the stream. :param ins: The `Instruction` to write.
def write_instruction(fout, start_pos, ins): """ Writes a single instruction of `opcode` with `operands` to `fout`. :param fout: Any file-like object providing ``write()``. :param start_pos: The current position in the stream. :param ins: The `Instruction` to write. """ opcode, operands = i...
Reads a single instruction from `fio` and returns it, or ``None`` if the stream is empty. :param fio: Any file-like object providing ``read()``. :param start_pos: The current position in the stream.
def read_instruction(fio, start_pos): """ Reads a single instruction from `fio` and returns it, or ``None`` if the stream is empty. :param fio: Any file-like object providing ``read()``. :param start_pos: The current position in the stream. """ op = fio.read(1) if not op: retur...
Load bytecode definitions from JSON file. If no path is provided the default bytecode.json will be loaded. :param path: Either None or a path to a JSON file to load containing bytecode definitions.
def load_bytecode_definitions(*, path=None) -> dict: """Load bytecode definitions from JSON file. If no path is provided the default bytecode.json will be loaded. :param path: Either None or a path to a JSON file to load containing bytecode definitions. """ if path is not None: ...
Returns the size of this instruction and its operands when packed. `start_pos` is required for the `tableswitch` and `lookupswitch` instruction as the padding depends on alignment.
def size_on_disk(self, start_pos=0): """ Returns the size of this instruction and its operands when packed. `start_pos` is required for the `tableswitch` and `lookupswitch` instruction as the padding depends on alignment. """ # All instructions are at least 1 byte (the op...
``True`` if this instruction needs to be prefixed by the WIDE opcode.
def wide(self): """ ``True`` if this instruction needs to be prefixed by the WIDE opcode. """ if not opcode_table[self.opcode].get('can_be_wide'): return False if self.operands[0].value >= 255: return True if self.opcode == 0x84: ...
*send the mobi book generated to kindle email address(es)* **Return:** - ``success`` -- True or False depending on the success/failure of sending the email to the kindle email address(es).
def send( self): """*send the mobi book generated to kindle email address(es)* **Return:** - ``success`` -- True or False depending on the success/failure of sending the email to the kindle email address(es). """ self.log.debug('starting the ``send`` method') ...
Get file as MIMEBase message
def get_attachment(self, file_path): '''Get file as MIMEBase message''' try: file_ = open(file_path, 'rb') attachment = MIMEBase('application', 'octet-stream') attachment.set_payload(file_.read()) file_.close() encoders.encode_base64(attachmen...
Check if any of the given URLs has a matching host. :param urls: an iterable containing URLs :returns: True if any host has a listed match :raises InvalidURLError: if there are any invalid URLs in the sequence
def any_match(self, urls): """Check if any of the given URLs has a matching host. :param urls: an iterable containing URLs :returns: True if any host has a listed match :raises InvalidURLError: if there are any invalid URLs in the sequence """ return any(urlparse...
Get a host value matching the given value. :param host_value: a value of the host of a type that can be listed by the service :returns: an instance of AddressListItem representing a matched value :raises InvalidHostError: if the argument is not a valid host string
def lookup(self, host_value): """Get a host value matching the given value. :param host_value: a value of the host of a type that can be listed by the service :returns: an instance of AddressListItem representing a matched value :raises InvalidHostError: if the argument ...
Get matching hosts for the given URLs. :param urls: an iterable containing URLs :returns: instances of AddressListItem representing listed hosts matching the ones used by the given URLs :raises InvalidURLError: if there are any invalid URLs in the sequence
def lookup_matching(self, urls): """Get matching hosts for the given URLs. :param urls: an iterable containing URLs :returns: instances of AddressListItem representing listed hosts matching the ones used by the given URLs :raises InvalidURLError: if there are any invalid URLs in...
Get URLs with hosts matching any listed ones. :param urls: an iterable containing URLs to filter :returns: a generator yielding matching URLs :raises InvalidURLError: if there are any invalid URLs in the sequence
def filter_matching(self, urls): """Get URLs with hosts matching any listed ones. :param urls: an iterable containing URLs to filter :returns: a generator yielding matching URLs :raises InvalidURLError: if there are any invalid URLs in the sequence """ for url in...
Decodes a bytestring containing modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param s: bytestring to be converted. :returns: A unicode representation of the original string.
def decode_modified_utf8(s: bytes) -> str: """ Decodes a bytestring containing modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param s: bytestring to be converted. :returns: A unicode representation of the original string. """ s = bytearray(s) buff = [] buffer_...
Encodes a unicode string as modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param u: unicode string to be converted. :returns: A decoded bytearray.
def encode_modified_utf8(u: str) -> bytearray: """ Encodes a unicode string as modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param u: unicode string to be converted. :returns: A decoded bytearray. """ final_string = bytearray() for c in [ord(char) for char in u]...
@Api private Add new :py:class:`TemplateHook` into the registry :param str name: Hook name :return: Instance of :py:class:`TemplateHook` :rtype: :py:class:`TemplateHook`
def _register(self, name): """ @Api private Add new :py:class:`TemplateHook` into the registry :param str name: Hook name :return: Instance of :py:class:`TemplateHook` :rtype: :py:class:`TemplateHook` """ templatehook = TemplateHook() self._regist...
Register a new callback.\ When the name/id is not found\ a new hook is created under its name,\ meaning the hook is usually created by\ the first registered callback :param str name: Hook name :param callable func: A func reference (callback)
def register(self, name, func): """ Register a new callback.\ When the name/id is not found\ a new hook is created under its name,\ meaning the hook is usually created by\ the first registered callback :param str name: Hook name :param callable func: A fu...
Remove a previously registered callback :param str name: Hook name :param callable func: A function reference\ that was registered previously
def unregister(self, name, func): """ Remove a previously registered callback :param str name: Hook name :param callable func: A function reference\ that was registered previously """ try: templatehook = self._registry[name] except KeyError: ...
Remove all callbacks :param str name: Hook name
def unregister_all(self, name): """ Remove all callbacks :param str name: Hook name """ try: templatehook = self._registry[name] except KeyError: return templatehook.unregister_all()
Allow old method names for backwards compatability.
def deprecated_name(name): """Allow old method names for backwards compatability. """ def decorator(func): """Decorator function.""" def func_wrapper(self): """Wrapper for original function.""" if hasattr(self, name): # Return the old property ...
Return an object that corresponds to the given EPSG code. Currently supported object types are: - :class:`GeodeticCRS` - :class:`ProjectedCRS` - :class:`CartesianCS` - :class:`UOM` For example:: >>> print(get(27700)) <ProjectedCRS: 27700, OSGB 1936 / British Na...
def get(code): """ Return an object that corresponds to the given EPSG code. Currently supported object types are: - :class:`GeodeticCRS` - :class:`ProjectedCRS` - :class:`CartesianCS` - :class:`UOM` For example:: >>> print(get(27700)) <ProjectedCRS: 27...
An ordered list of :class:`Axis` objects describing X and Y.
def axes(self): """An ordered list of :class:`Axis` objects describing X and Y.""" axes = self.element.findall(GML_NS + 'axis') return [Axis(axis.find(GML_NS + 'CoordinateSystemAxis')) for axis in axes]
The EPSG code for this CRS.
def id(self): """The EPSG code for this CRS.""" id = self.element.attrib[GML_NS + 'id'] code = id.split('-')[-1] return code
Return the OGC WKT which corresponds to the CRS as HTML. For example:: >>> print(get(27700).as_html()) # doctest: +ELLIPSIS <div class="syntax"><pre><span class="gh">PROJCS</span><span...
def as_html(self): """ Return the OGC WKT which corresponds to the CRS as HTML. For example:: >>> print(get(27700).as_html()) # doctest: +ELLIPSIS <div class="syntax"><pre><span class="gh">PROJCS</span><span... """ url = '{prefix}{code}.html?download'....