INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | 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 | 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 | 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 | 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. | 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. | 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... |
Compute diplomacy. | def get_diplomacy(self):
"""Compute diplomacy."""
if not self._cache['teams']:
self.get_teams()
player_num = 0
computer_num = 0
for player in self._header.scenario.game_settings.player_info:
if player.type == 'human':
player_num += 1
... |
Get achievements for a player. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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... |
Add one or more ClassFile sources to the class loader. | 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
... |
Open an IO - like object for path. | 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... |
Load the class at path and return it. | 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. | 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. | 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 * | 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 * | 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 * | 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. | 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 * | 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. | 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. | 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. | 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 ). | 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. | 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 ]. | 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 * | 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 * | 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 * | 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. | 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. | 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:: | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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)... |
Do a commit if modified/ untracked files | def do_commit(repo, message_template, branch_name, hexsha):
"Do a commit if modified/untracked files"
repo.git.add(repo.working_tree_dir)
if not repo.git.diff(staged=True):
_LOGGER.warning('No modified files in this Autorest run')
return False
checkout_and_create_branch(repo, branch_na... |
Get the SHA1 of the current repo | def get_repo_hexsha(git_folder):
"""Get the SHA1 of the current repo"""
repo = Repo(str(git_folder))
if repo.bare:
not_git_hexsha = "notgitrepo"
_LOGGER.warning("Not a git repo, SHA1 used will be: %s", not_git_hexsha)
return not_git_hexsha
hexsha = repo.head.commit.hexsha
_LO... |
Fetch the refspec and checkout FETCH_HEAD. Beware that you will ne in detached head mode. | def checkout_with_fetch(git_folder, refspec, repository="origin"):
"""Fetch the refspec, and checkout FETCH_HEAD.
Beware that you will ne in detached head mode.
"""
_LOGGER.info("Trying to fetch and checkout %s", refspec)
repo = Repo(str(git_folder))
repo.git.fetch(repository, refspec) # FETCH_... |
Clone the given URL to the folder. | def clone_to_path(https_authenticated_url, folder, branch_or_commit=None):
"""Clone the given URL to the folder.
:param str branch_or_commit: If specified, switch to this branch. Branch must exist.
"""
_LOGGER.info("Cloning repo")
repo = Repo.clone_from(https_authenticated_url, str(folder))
# D... |
List of files in HEAD commit. | def get_files_in_commit(git_folder, commit_id="HEAD"):
"""List of files in HEAD commit.
"""
repo = Repo(str(git_folder))
output = repo.git.diff("--name-only", commit_id+"^", commit_id)
return output.splitlines() |
extract values from query | def parse_values(self, query):
"""
extract values from query
"""
values = {}
for name, filt in self.filters.items():
val = filt.parse_value(query)
if val is None:
continue
values[name] = val
return values |
convert values to filtering params and apply to queryset | def filter_queryset(self, queryset):
"""
convert values to filtering params and apply to queryset
"""
for name, filt in self.filters.items():
val = self.values.get(name, None)
if name is None:
continue
params = filt.filter_params(val)
... |
Artist of current playing media ( Music track only ). | def media_artist(self):
"""Artist of current playing media (Music track only)."""
try:
artists = self.session['NowPlayingItem']['Artists']
if len(artists) > 1:
return artists[0]
else:
return artists
except KeyError:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.