INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
The 'count' relationship is used for listing endpoints where a specific attribute might hold the value to the number of instances of another attribute.
def count(self, source, target): """ The 'count' relationship is used for listing endpoints where a specific attribute might hold the value to the number of instances of another attribute. """ try: source_value = self._response_holder[source] except KeyError: ...
Return the SSH protocol specific command to connect.
def get_command(self, version=2): """Return the SSH protocol specific command to connect.""" try: options = _C['options'] options_str = " -o ".join(options) if options_str: options_str = "-o " + options_str + " " except KeyError: op...
Connect using the SSH protocol specific FSM.
def connect(self, driver): """Connect using the SSH protocol specific FSM.""" # 0 1 2 events = [driver.password_re, self.device.prompt_re, driver.unable_to_connect_re, # 3 4 5 6 ...
Authenticate using the SSH protocol specific FSM.
def authenticate(self, driver): """Authenticate using the SSH protocol specific FSM.""" # 0 1 2 3 events = [driver.press_return_re, driver.password_re, self.device.prompt_re, pexpect.TIMEOUT] transitions = [ ...
Disconnect using the protocol specific method.
def disconnect(self, driver): """Disconnect using the protocol specific method.""" self.log("SSH disconnect") try: self.device.ctrl.sendline('\x03') self.device.ctrl.sendline('\x04') except OSError: self.log("Protocol already disconnected")
Fallback to SSHv1.
def fallback_to_sshv1(self, ctx): """Fallback to SSHv1.""" command = self.get_command(version=1) ctx.spawn_session(command) return True
Reload the device. CSM_DUT#reload System configuration has been modified. Save? [yes/no]: yes Building configuration... [OK] Proceed with reload? [confirm]
def reload(self, reload_timeout=300, save_config=True): """Reload the device. CSM_DUT#reload System configuration has been modified. Save? [yes/no]: yes Building configuration... [OK] Proceed with reload? [confirm] """ SAVE_CONFIG = re.compile(re.escape(...
Validates a domain by checking that {prefix}={code} is present in the TXT DNS record of the domain to check. Returns true if verification suceeded.
def check_dns_txt(domain, prefix, code): """ Validates a domain by checking that {prefix}={code} is present in the TXT DNS record of the domain to check. Returns true if verification suceeded. """ token = '{}={}'.format(prefix, code) try: for rr in dns.resolver.query(domain, 'TXT'):...
Validates a domain by checking the existance of the CNAME record on the domain as: {prefix}-{code}.{domain} pointing to a domain (usually yours) which the host is {prefix} (i.e.: {prefix}.yourdomain.com). Returns true if verification suceeded.
def check_dns_cname(domain, prefix, code): """ Validates a domain by checking the existance of the CNAME record on the domain as: {prefix}-{code}.{domain} pointing to a domain (usually yours) which the host is {prefix} (i.e.: {prefix}.yourdomain.com). Returns true if verification suceeded. """ ...
Checks whether the html_doc contains a meta matching the prefix & code
def search_meta_tag(html_doc, prefix, code): """ Checks whether the html_doc contains a meta matching the prefix & code """ regex = '<meta\s+(?:name=([\'\"]){0}\\1\s+content=([\'\"]){1}\\2|content=([\'\"]){1}\\3\s+name=([\'\"]){0}\\4)\s*/?>'.format(prefix, code) meta = re.compile(regex, flags=re.MUL...
Validates a domain by checking the existance of a <meta name="{prefix}" content="{code}"> tag in the <head> of the home page of the domain using either HTTP or HTTPs protocols. Returns true if verification suceeded.
def check_meta_tag(domain, prefix, code): """ Validates a domain by checking the existance of a <meta name="{prefix}" content="{code}"> tag in the <head> of the home page of the domain using either HTTP or HTTPs protocols. Returns true if verification suceeded. """ url = '://{}'.format(domain) ...
See: https://core.telegram.org/bots/api#senddocument :param document: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
def sendDocument(self, chat_id, document, thumb=None, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://cor...
See: https://core.telegram.org/bots/api#sendvideo :param video: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
def sendVideo(self, chat_id, video, duration=None, width=None, height=None, thumb=None, caption=None, parse_mode=None, supports_streaming=None, disable_notification=None, ...
See: https://core.telegram.org/bots/api#stoppoll :param msg_identifier: a 2-tuple (``chat_id``, ``message_id``), a 1-tuple (``inline_message_id``), or simply ``inline_message_id``. You may extract this value easily with :meth:`amanobot.message_identifier`
def stopPoll(self, msg_identifier, reply_markup=None): """ See: https://core.telegram.org/bots/api#stoppoll :param msg_identifier: a 2-tuple (``chat_id``, ``message_id``), a 1-tuple (``inline_message_id``), or simply ``inline_message_id``. ...
:deprecated: will be removed in future. Use :class:`.MessageLoop` instead. Spawn a thread to constantly ``getUpdates`` or pull updates from a queue. Apply ``callback`` to every message received. Also starts the scheduler thread for internal events. :param callback: a functi...
def message_loop(self, callback=None, relax=0.1, timeout=20, allowed_updates=None, source=None, ordered=True, maxhold=3, run_forever=False): """ :deprecated: will be removed in future. Use :class:`.MessageLoop` instead. Spawn a thre...
Find postgame struct. We can find postgame location by scanning the last few thousand bytes of the rec and looking for a pattern as follows: [action op] [action length] [action type] 01 00 00 00 30 08 00 00 ff The last occurance of this pattern signals the start of the pos...
def find_postgame(data, size): """Find postgame struct. We can find postgame location by scanning the last few thousand bytes of the rec and looking for a pattern as follows: [action op] [action length] [action type] 01 00 00 00 30 08 00 00 ff The last occurance of this pa...
Parse postgame structure.
def parse_postgame(handle, size): """Parse postgame structure.""" data = handle.read() postgame = find_postgame(data, size) if postgame: pos, length = postgame try: return mgz.body.actions.postgame.parse(data[pos:pos + length]) except construct.core.ConstructError: ...
Get field from achievements structure.
def ach(structure, fields): """Get field from achievements structure.""" field = fields.pop(0) if structure: if hasattr(structure, field): structure = getattr(structure, field) if not fields: return structure return ach(structure, fields) retur...
Get postgame structure.
def get_postgame(self): """Get postgame structure.""" if self._cache['postgame'] is not None: return self._cache['postgame'] self._handle.seek(0) try: self._cache['postgame'] = parse_postgame(self._handle, self.size) return self._cache['postgame'] ...
Get game duration.
def get_duration(self): """Get game duration.""" postgame = self.get_postgame() if postgame: return postgame.duration_int * 1000 duration = self._header.initial.restore_time try: while self._handle.tell() < self.size: operation = mgz.body.o...
Check for restored game.
def get_restored(self): """Check for restored game.""" return self._header.initial.restore_time > 0, self._header.initial.restore_time
Get game version.
def get_version(self): """Get game version.""" return mgz.const.VERSIONS[self._header.version], str(self._header.sub_version)[:5]
Get dataset.
def get_dataset(self): """Get dataset.""" sample = self._header.initial.players[0].attributes.player_stats if 'mod' in sample and sample.mod['id'] > 0: return sample.mod elif 'trickle_food' in sample and sample.trickle_food: return { 'id': 1, ...
Get teams.
def get_teams(self): """Get teams.""" if self._cache['teams']: return self._cache['teams'] teams = [] for j, player in enumerate(self._header.initial.players): added = False for i in range(0, len(self._header.initial.players)): if playe...
Get achievements for a player. Must match on name, not index, since order is not always the same.
def get_achievements(self, name): """Get achievements for a player. Must match on name, not index, since order is not always the same. """ postgame = self.get_postgame() if not postgame: return None for achievements in postgame.achievements: # ach...
Get basic player info.
def get_players(self): """Get basic player info.""" ratings = self.get_ratings() for i, player in enumerate(self._header.initial.players[1:]): achievements = self.get_achievements(player.attributes.player_name) if achievements: winner = achievements.victor...
Get Voobly ladder. This is expensive if the rec is not from Voobly, since it will search the whole file. Returns tuple, (from_voobly, ladder_name, rated, ratings).
def _process_body(self): """Get Voobly ladder. This is expensive if the rec is not from Voobly, since it will search the whole file. Returns tuple, (from_voobly, ladder_name, rated, ratings). """ start_time = time.time() ratings = {} encoding = self.get_e...
Get settings.
def get_settings(self): """Get settings.""" postgame = self.get_postgame() return { 'type': ( self._header.lobby.game_type_id, self._header.lobby.game_type ), 'difficulty': ( self._header.scenario.game_settings.d...
Get the map metadata.
def get_map(self): """Get the map metadata.""" if self._cache['map']: return self._cache['map'] map_id = self._header.scenario.game_settings.map_id instructions = self._header.scenario.messages.instructions size = mgz.const.MAP_SIZES.get(self._header.map_info.size_x) ...
Determine if the game was completed. If there's a postgame, it will indicate completion. If there is no postgame, guess based on resignation.
def get_completed(self): """Determine if the game was completed. If there's a postgame, it will indicate completion. If there is no postgame, guess based on resignation. """ postgame = self.get_postgame() if postgame: return postgame.complete else: ...
Determine mirror match.
def get_mirror(self): """Determine mirror match.""" mirror = False if self.get_diplomacy()['1v1']: civs = set() for data in self.get_players(): civs.add(data['civilization']) mirror = (len(civs) == 1) return mirror
Guess if a player won. Find what team the player was on. If anyone on their team resigned, assume the player lost.
def guess_winner(self, i): """Guess if a player won. Find what team the player was on. If anyone on their team resigned, assume the player lost. """ for team in self.get_teams(): if i not in team: continue for p in team: if...
Attach a handler (any Python callable) for the event.
def on(self, handler): """Attach a handler (any Python callable) for the event.""" if not hasattr(handler, '__call__'): raise TypeError('handler is not a callable object.') self.handlers.add(handler)
Execute the handlers with a message, if any.
def trigger(self, *args, **kwargs): """Execute the handlers with a message, if any.""" for h in self.handlers: h(*args, **kwargs)
Create, add or update an event with a handler or more attached.
def on(self, event, handler=None): """Create, add or update an event with a handler or more attached.""" if isinstance(event, str) and ' ' in event: # event is list str-based self.on(event.split(' '), handler) elif isinstance(event, list): # many events contains same handler ...
Remove an event or a handler from it.
def off(self, event, handler=None): """Remove an event or a handler from it.""" if handler: self.events[event].off(handler) else: del self.events[event] delattr(self, event)
Execute all event handlers with optional arguments for the observable.
def trigger(self, *args, **kargs): """ Execute all event handlers with optional arguments for the observable. """ event = args[0] if isinstance(event, str) and ' ' in event: event = event.split(' ') # split event names ... if isinstance(event, list): # eve...
Ignore SIGINT. During typical keyboard interrupts, the parent does the killing.
def _initializer_wrapper(initializer, *args): """ Ignore SIGINT. During typical keyboard interrupts, the parent does the killing. """ signal.signal(signal.SIGINT, signal.SIG_IGN) if initializer is not None: initializer(*args)
Determines the set of types present in a DataFrame column. :param str col: A column name. :param pandas.DataFrame df: The dataset. Usually ``self._data``. :return: A set of Types.
def _col_type_set(self, col, df): """ Determines the set of types present in a DataFrame column. :param str col: A column name. :param pandas.DataFrame df: The dataset. Usually ``self._data``. :return: A set of Types. """ type_set = set() if df[col].dtype...
Drops columns containing collections (i.e. sets, dicts, lists) from a DataFrame. :param pandas.DataFrame df: Usually self._data. :return: pandas.DataFrame
def _drop_collections(self, df): """ Drops columns containing collections (i.e. sets, dicts, lists) from a DataFrame. :param pandas.DataFrame df: Usually self._data. :return: pandas.DataFrame """ all_cols = df.columns keep_cols = [] # Check whether each ...
Produces the extractor object's data as it is stored internally. :param bool drop_collections: Defaults to False. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame
def raw(self, drop_collections = False): """ Produces the extractor object's data as it is stored internally. :param bool drop_collections: Defaults to False. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame """ base_df = self._...
Returns a reshaped version of extractor's data, where unique combinations of values from col1 and col2 are given individual rows. Example function call from ``tidymbox``: .. code-block:: python self.expand_on('From', 'To', ['MessageID', 'Recipient'], rename1='From', rename2='Recip...
def expand_on(self, col1, col2, rename1 = None, rename2 = None, drop = [], drop_collections = False): """ Returns a reshaped version of extractor's data, where unique combinations of values from col1 and col2 are given individual rows. Example function call from ``tidymbox``: ....
A modified os.walk with support for maximum traversal depth.
def _walk(path, follow_links=False, maximum_depth=None): """A modified os.walk with support for maximum traversal depth.""" root_level = path.rstrip(os.path.sep).count(os.path.sep) for root, dirs, files in os.walk(path, followlinks=follow_links): yield root, dirs, files if maximum_depth is N...
Open an IO-like object for `path`. .. note:: Mode *must* be either 'r' or 'w', as the underlying objects do not understand the full range of modes. :param path: The path to open. :param mode: The mode of the file being opened, either 'r' or 'w'.
def open(self, path: str, mode: str='r') -> IO: """Open an IO-like object for `path`. .. note:: Mode *must* be either 'r' or 'w', as the underlying objects do not understand the full range of modes. :param path: The path to open. :param mode: The mode of the fi...
Add one or more ClassFile sources to the class loader. If a given source is a directory path, it is traversed up to the maximum set depth and all files under it are added to the class loader lookup table. If a given source is a .jar or .zip file it will be opened and the file i...
def update(self, *sources, follow_symlinks: bool=False, maximum_depth: int=20): """Add one or more ClassFile sources to the class loader. If a given source is a directory path, it is traversed up to the maximum set depth and all files under it are added to the class loader ...
Load the class at `path` and return it. Load will attempt to load the file at `path` and `path` + .class before failing. :param path: Fully-qualified path to a ClassFile.
def load(self, path: str) -> ClassFile: """Load the class at `path` and return it. Load will attempt to load the file at `path` and `path` + .class before failing. :param path: Fully-qualified path to a ClassFile. """ # Try to refresh the class from the cache, loading i...
Returns a set of all classes referenced by the ClassFile at `path` without reading the entire ClassFile. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. :param path: Fully-qualified path to a ClassFile.
def dependencies(self, path: str) -> Set[str]: """Returns a set of all classes referenced by the ClassFile at `path` without reading the entire ClassFile. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. ...
Partially load the class at `path`, yield all matching constants from the ConstantPool. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. :param path: Fully-qualified path to a ClassFile. :param options...
def search_constant_pool(self, *, path: str, **options): """Partially load the class at `path`, yield all matching constants from the ConstantPool. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. :par...
Yield the name of all classes discovered in the path map.
def classes(self) -> Iterator[str]: """Yield the name of all classes discovered in the path map.""" yield from ( c[:-6] for c in self.path_map.keys() if c.endswith('.class') )
*create the webarchive object* **Key Arguments:** - ``url`` -- the url of the webpage to generate the webarchive for - ``pathToWebarchive`` -- tthe path to output the the webarchive file to **Return:** - ``webarchive`` -- the path to the webarchive (or -1 if the ge...
def create(self, url, pathToWebarchive): """ *create the webarchive object* **Key Arguments:** - ``url`` -- the url of the webpage to generate the webarchive for - ``pathToWebarchive`` -- tthe path to output the the webarchive file to **Return:** - ...
*parse and clean the html document with Mercury Parser* **Return:** - ``filePath`` -- path to the cleaned HTML document **Usage:** See class usage
def clean( self): """*parse and clean the html document with Mercury Parser* **Return:** - ``filePath`` -- path to the cleaned HTML document **Usage:** See class usage """ self.log.debug('starting the ``clean`` method') url = self....
* request parsed article from mercury* **Key Arguments:** - ``url`` -- the URL to the HTML page to parse and clean **Return:** - None **Usage:** .. todo:: - add usage info - create a sublime snippet for usage ...
def _request_parsed_article_from_mercury( self, url): """* request parsed article from mercury* **Key Arguments:** - ``url`` -- the URL to the HTML page to parse and clean **Return:** - None **Usage:** .. todo:: ...
Wrapper to open land surface model netcdf files using :func:`xarray.open_mfdataset`. .. warning:: The time dimension and variable will both be renamed to 'time' to enable slicing. Parameters ---------- path_to_lsm_files: :obj:`str` Path to land surface model files with wildcard. ...
def open_mfdataset(path_to_lsm_files, lat_var, lon_var, time_var, lat_dim, lon_dim, time_dim, lon_to_180=False, coords_projected=False, loader=None, ...
*convert the kindle_notebook object* **Return:** - ``kindle_notebook`` **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - update the package tutorial if needed .. code-block:: python usage code
def convert(self): """ *convert the kindle_notebook object* **Return:** - ``kindle_notebook`` **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - update the package tutorial if needed .. code-blo...
r'[a-zA-Z_][a-zA-Z0-9_]*
def t_IDENTIFIER(self, t): r'[a-zA-Z_][a-zA-Z0-9_]*' t.type = self.reserved_words.get(t.value, 'IDENTIFIER') return t
r'\n+
def t_newline(self, t): r'\n+' t.lexer.lineno += len(t.value) self.latest_newline = t.lexpos
Extracts user data Using the twitter API. Mutates _data. NOTE: TwitterExtractor requires a complete set of Twitter API credentials to initialize: 'access_token', 'access_secret', 'consumer_key', and 'consumer_secret'. :param list source: A list of user screen name strings. :param args: ...
def _extract(self, source, extract_tweets=True, *args, **kwargs): """ Extracts user data Using the twitter API. Mutates _data. NOTE: TwitterExtractor requires a complete set of Twitter API credentials to initialize: 'access_token', 'access_secret', 'consumer_key', and 'consumer_secret'. ...
Returns a table of Twitter user data, with "users" as rows/observations. :param bool drop_collections: Defaults to True. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame
def users(self, drop_collections = True): """ Returns a table of Twitter user data, with "users" 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 ...
Returns a table of Twitter user data, with "tweets" as rows/observations. .. note:: drop_collections is not available for this method, since there are no meaningful collections to keep. :return: pandas.DataFrame
def tweets(self): """ Returns a table of Twitter user data, with "tweets" as rows/observations. .. note:: drop_collections is not available for this method, since there are no meaningful collections to keep. :return: pandas.DataFrame """ # I've hard coded ...
Process an object using twitter_object_handlers_lookup. Doesn't currently do anything (as of 2017-06-16). :param str name: Object name :param obj: An object to be processed :return: A dictionary of attributes
def _handle_object(self, name, obj): """ Process an object using twitter_object_handlers_lookup. Doesn't currently do anything (as of 2017-06-16). :param str name: Object name :param obj: An object to be processed :return: A dictionary of attributes """ i...
Processes an object, exporting its data as a nested dictionary. :param obj: An object :return: A nested dictionary of object data
def _make_object_dict(self, obj): """ Processes an object, exporting its data as a nested dictionary. :param obj: An object :return: A nested dictionary of object data """ data = {} for attr in dir(obj): if attr[0] is not '_' and attr is not 'status':...
Processes a Twitter User object, exporting as a nested dictionary. Complex values (i.e. objects that aren't int, bool, float, str, or a collection of such) are converted to strings (i.e. using __str__ or __repr__). To access user data only, use make_user_dict(username)['_json']. :param ...
def _make_user_dict(self, username): """ Processes a Twitter User object, exporting as a nested dictionary. Complex values (i.e. objects that aren't int, bool, float, str, or a collection of such) are converted to strings (i.e. using __str__ or __repr__). To access user data only...
*get the ebook object* **Return:** - ``ebook`` **Usage:** See class docstring for usage
def get(self): """ *get the ebook object* **Return:** - ``ebook`` **Usage:** See class docstring for usage """ self.log.debug('starting the ``get`` method') if self.format == "epub": if self.urlOrPath[:4] == "http" or self.u...
*generate the epub book from a URL*
def _url_to_epub( self): """*generate the epub book from a URL* """ self.log.debug('starting the ``_url_to_epub`` method') from polyglot import htmlCleaner cleaner = htmlCleaner( log=self.log, settings=self.settings, url=self.urlOr...
*create a tmp html file with some content used for the header or footer of the ebook* **Key Arguments:** - ``content`` -- the content to include in the HTML file.
def _tmp_html_file( self, content): """*create a tmp html file with some content used for the header or footer of the ebook* **Key Arguments:** - ``content`` -- the content to include in the HTML file. """ self.log.debug('starting the ``_tmp_html_file...
*convert the give epub to mobi format using kindlegen* **Key Arguments:** - ``epubPath`` -- path to the epub book - ``deleteEpub`` -- delete the epub when mobi is generated. Default *False* **Return:** - ``mobi`` -- the path to the generated mobi book
def _epub_to_mobi( self, epubPath, deleteEpub=False): """*convert the give epub to mobi format using kindlegen* **Key Arguments:** - ``epubPath`` -- path to the epub book - ``deleteEpub`` -- delete the epub when mobi is generated. Default *Fal...
*convert docx file to epub*
def _docx_to_epub( self): """*convert docx file to epub* """ self.log.debug('starting the ``_docx_to_epub`` method') if self.footer: footer = self._tmp_html_file(self.footer) footer = '"%(footer)s"' % locals() else: footer = "" ...
Read the Field from the file-like object `fio`. .. 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 Field from the file-like object `fio`. .. 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 providi...
Write the Field 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 Field 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(...
Removes any and all fields for which `f(field)` returns `True`.
def find_and_remove(self, f: Callable): """ Removes any and all fields for which `f(field)` returns `True`. """ self._table = [fld for fld in self._table if not f(fld)]
Removes a `Field` from the table by identity.
def remove(self, field: Field): """ Removes a `Field` from the table by identity. """ self._table = [fld for fld in self._table if fld is not field]
Creates a new field from `name` and `descriptor`. For example:: >>> from jawa.cf import ClassFile >>> cf = ClassFile.create('BeerCounter') >>> field = cf.fields.create('BeerCount', 'I') To automatically create a static field, pass a value:: >>> from jawa.cf imp...
def create(self, name: str, descriptor: str, value: Constant=None) -> Field: """ Creates a new field from `name` and `descriptor`. For example:: >>> from jawa.cf import ClassFile >>> cf = ClassFile.create('BeerCounter') >>> field = cf.fields.create('BeerCount', 'I') ...
Read the FieldTable 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 FieldTable 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...
Write the FieldTable 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 FieldTable 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 `w...
Iterates over the fields table, yielding each matching method. Calling without any arguments is equivalent to iterating over the table. :param name: The name of the field(s) to find. :param type_: The field descriptor (Ex: 'I') :param f: Any callable which takes one argument (the field)...
def find(self, *, name: str=None, type_: str=None, f: Callable=None) -> Iterator[Field]: """ Iterates over the fields table, yielding each matching method. Calling without any arguments is equivalent to iterating over the table. :param name: The name of the field(s) to find...
Stats object handler. :param name: Unused String :param obj: GitPython Stats :return: Dictionary of attributes.
def handle_stats(name, obj): """ Stats object handler. :param name: Unused String :param obj: GitPython Stats :return: Dictionary of attributes. """ return {'total_deletions': obj.total['deletions'], 'total_insertions': obj.total['insertions'], 'total_lines': obj.tota...
Help us read the pkginfo without accessing __init__
def read_pkginfo(filename): """ Help us read the pkginfo without accessing __init__ """ COMMENT_CHAR = '#' OPTION_CHAR = '=' options = {} f = open(filename) for line in f: if COMMENT_CHAR in line: line, comment = line.split(COMMENT_CHAR, 1) if OPTION_CHAR in ...
Check if given value is a valid host string. :param value: a value to test :returns: True if the value is valid
def is_valid_host(value): """Check if given value is a valid host string. :param value: a value to test :returns: True if the value is valid """ host_validators = validators.ipv4, validators.ipv6, validators.domain return any(f(value) for f in host_validators)
Check if given value is a valid URL string. :param value: a value to test :returns: True if the value is valid
def is_valid_url(value): """Check if given value is a valid URL string. :param value: a value to test :returns: True if the value is valid """ match = URL_REGEX.match(value) host_str = urlparse(value).hostname return match and is_valid_host(host_str)
Return a wrapper that runs given method only for valid hosts. :param func: a method to be wrapped :returns: a wrapper that adds argument validation
def accepts_valid_host(func): """Return a wrapper that runs given method only for valid hosts. :param func: a method to be wrapped :returns: a wrapper that adds argument validation """ @functools.wraps(func) def wrapper(obj, value, *args, **kwargs): """Run the function and return a valu...
Return a wrapper that runs given method only for valid URLs. :param func: a method to be wrapped :returns: a wrapper that adds argument validation
def accepts_valid_urls(func): """Return a wrapper that runs given method only for valid URLs. :param func: a method to be wrapped :returns: a wrapper that adds argument validation """ @functools.wraps(func) def wrapper(obj, urls, *args, **kwargs): """Run the function and return a value ...
Returns the `Constant` at `index`, raising a KeyError if it does not exist.
def get(self, index): """ Returns the `Constant` at `index`, raising a KeyError if it does not exist. """ constant = self._pool[index] if not isinstance(constant, Constant): constant = _constant_types[constant[0]](self, index, *constant[1:]) self._...
Iterates over the pool, yielding each matching ``Constant``. Calling without any arguments is equivalent to iterating over the pool. :param type_: Any subclass of :class:`Constant` or ``None``. :param f: Any callable which takes one argument (the constant).
def find(self, type_=None, f=None): """ Iterates over the pool, yielding each matching ``Constant``. Calling without any arguments is equivalent to iterating over the pool. :param type_: Any subclass of :class:`Constant` or ``None``. :param f: Any callable which takes one argume...
Same as ``find()`` but returns only the first result, or `None` if nothing was found.
def find_one(self, *args, **kwargs): """ Same as ``find()`` but returns only the first result, or `None` if nothing was found. """ try: return next(self.find(*args, **kwargs)) except StopIteration: return None
Creates a new :class:`ConstantUTF8`, adding it to the pool and returning it. :param value: The value of the new UTF8 string.
def create_utf8(self, value): """ Creates a new :class:`ConstantUTF8`, adding it to the pool and returning it. :param value: The value of the new UTF8 string. """ self.append((1, value)) return self.get(self.raw_count - 1)
Creates a new :class:`ConstantInteger`, adding it to the pool and returning it. :param value: The value of the new integer.
def create_integer(self, value: int) -> Integer: """ Creates a new :class:`ConstantInteger`, adding it to the pool and returning it. :param value: The value of the new integer. """ self.append((3, value)) return self.get(self.raw_count - 1)
Creates a new :class:`ConstantFloat`, adding it to the pool and returning it. :param value: The value of the new float.
def create_float(self, value: float) -> Float: """ Creates a new :class:`ConstantFloat`, adding it to the pool and returning it. :param value: The value of the new float. """ self.append((4, value)) return self.get(self.raw_count - 1)
Creates a new :class:`ConstantLong`, adding it to the pool and returning it. :param value: The value of the new long.
def create_long(self, value: int) -> Long: """ Creates a new :class:`ConstantLong`, adding it to the pool and returning it. :param value: The value of the new long. """ self.append((5, value)) self.append(None) return self.get(self.raw_count - 2)
Creates a new :class:`ConstantDouble`, adding it to the pool and returning it. :param value: The value of the new Double.
def create_double(self, value: float) -> Double: """ Creates a new :class:`ConstantDouble`, adding it to the pool and returning it. :param value: The value of the new Double. """ self.append((6, value)) self.append(None) return self.get(self.raw_count - 2...
Creates a new :class:`ConstantClass`, adding it to the pool and returning it. :param name: The name of the new class.
def create_class(self, name: str) -> ConstantClass: """ Creates a new :class:`ConstantClass`, adding it to the pool and returning it. :param name: The name of the new class. """ self.append(( 7, self.create_utf8(name).index )) retu...
Creates a new :class:`ConstantString`, adding it to the pool and returning it. :param value: The value of the new string as a UTF8 string.
def create_string(self, value: str) -> String: """ Creates a new :class:`ConstantString`, adding it to the pool and returning it. :param value: The value of the new string as a UTF8 string. """ self.append(( 8, self.create_utf8(value).index ...
Creates a new :class:`ConstantNameAndType`, adding it to the pool and returning it. :param name: The name of the class. :param descriptor: The descriptor for `name`.
def create_name_and_type(self, name: str, descriptor: str) -> NameAndType: """ Creates a new :class:`ConstantNameAndType`, adding it to the pool and returning it. :param name: The name of the class. :param descriptor: The descriptor for `name`. """ self.append(( ...
Creates a new :class:`ConstantFieldRef`, adding it to the pool and returning it. :param class_: The name of the class to which `field` belongs. :param field: The name of the field. :param descriptor: The descriptor for `field`.
def create_field_ref(self, class_: str, field: str, descriptor: str) \ -> FieldReference: """ Creates a new :class:`ConstantFieldRef`, adding it to the pool and returning it. :param class_: The name of the class to which `field` belongs. :param field: The name of the...
Creates a new :class:`ConstantMethodRef`, adding it to the pool and returning it. :param class_: The name of the class to which `method` belongs. :param method: The name of the method. :param descriptor: The descriptor for `method`.
def create_method_ref(self, class_: str, method: str, descriptor: str) \ -> MethodReference: """ Creates a new :class:`ConstantMethodRef`, adding it to the pool and returning it. :param class_: The name of the class to which `method` belongs. :param method: The name ...
Creates a new :class:`ConstantInterfaceMethodRef`, adding it to the pool and returning it. :param class_: The name of the class to which `if_method` belongs. :param if_method: The name of the interface method. :param descriptor: The descriptor for `if_method`.
def create_interface_method_ref(self, class_: str, if_method: str, descriptor: str) -> InterfaceMethodRef: """ Creates a new :class:`ConstantInterfaceMethodRef`, adding it to the pool and returning it. :param class_: The name of the class to which `if...
Read the ConstantPool from the file-like object `fio`. .. 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 fio: Any file-like object providing `read()`
def unpack(self, fio): """ Read the ConstantPool from the file-like object `fio`. .. 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 fio: Any file-like object providing ...
Write the ConstantPool to the file-like object `fout`. .. note:: Advanced usage only. You will typically never need to call this method as it will be calle=d for you when saving a ClassFile. :param fout: Any file-like object providing `write()`
def pack(self, fout): """ Write the ConstantPool to the file-like object `fout`. .. note:: Advanced usage only. You will typically never need to call this method as it will be calle=d for you when saving a ClassFile. :param fout: Any file-like object providing ...
Create the project
def create_project(project_name, template="default"): """ Create the project """ project_dir = get_project_dir_path(project_name) run_tpl = pkg_resources.resource_string(__name__, '%s/run.py' % (SKELETON_DIR)) init_py_tpl = pkg_resources.resource_string(__name__, '%s/init.py' % (SKELETON_DIR))...
Checkout branch. Create it if necessary
def checkout_and_create_branch(repo, name): """Checkout branch. Create it if necessary""" local_branch = repo.branches[name] if name in repo.branches else None if not local_branch: if name in repo.remotes.origin.refs: # If origin branch exists but not local, git.checkout is the fatest wa...
Checkout this branch. Create it if necessary, and push it to origin.
def checkout_create_push_branch(repo, name): """Checkout this branch. Create it if necessary, and push it to origin. """ try: repo.git.checkout(name) _LOGGER.info("Checkout %s success", name) except GitCommandError: _LOGGER.info("Checkout %s was impossible (branch does not exist)...