INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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. :param str branch_or_commit: If specified, switch to this branch. Branch must exist.
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: ...
Image url of current playing media.
def media_image_url(self): """Image url of current playing media.""" if self.is_nowplaying: base = self.server.construct_url(API_URL) try: image_id = self.session['NowPlayingItem']['ImageTags']['Thumb'] image_type = 'Thumb' except KeyEr...
Return current playstate of the device.
def state(self): """ Return current playstate of the device. """ if self.is_active: if 'NowPlayingItem' in self.session: if self.session['PlayState']['IsPaused']: return STATE_PAUSED else: return STATE_PLAYING ...
Send media commands to server.
async def set_playstate(self, state, pos=0): """ Send media commands to server. """ url = '{}/Sessions/{}/Playing/{}'.format( self.server.construct_url(API_URL), self.session_id, state) params = {'api_key': self.server.api_key} if state == 'seek': params['SeekPos...
*convert plain-text to MMD footnote* **Key Arguments:** - ``text`` -- the text to convert to MMD footnote **Return:** - ``text`` -- the footnote text **Usage:** To convert a text block to footnote text: .. code-block:: python ...
def footnote( self, text): """*convert plain-text to MMD footnote* **Key Arguments:** - ``text`` -- the text to convert to MMD footnote **Return:** - ``text`` -- the footnote text **Usage:** To convert a text block to footno...
*genarate a MMD glossary* **Key Arguments:** - ``term`` -- the term to add as a glossary item - ``definition`` -- the definition of the glossary term **Return:** - ``glossary`` -- the glossary text **Usage:** To genarate a glossary item: ...
def glossary( self, term, definition): """*genarate a MMD glossary* **Key Arguments:** - ``term`` -- the term to add as a glossary item - ``definition`` -- the definition of the glossary term **Return:** - ``glossary`` -- ...
*generate a MMD citation* **Key Arguments:** - ``title`` -- the citation title - ``author`` -- the author. Default *False* - ``year`` -- year published. Default *False* - ``url`` -- url to the media. Default *False* - ``publisher`` -- the publisher of...
def cite( self, title, author=False, year=False, url=False, publisher=False, mediaKind=False, linkedText=False, nocite=False): """*generate a MMD citation* **Key Arguments:** - ``titl...
*convert plain-text to MMD header* **Key Arguments:** - ``text`` -- the text to convert to MMD header - ``level`` -- the header level to convert the text to **Return:** - ``header`` -- the MMD header **Usage:** To convert a text MMD header: ...
def header( self, text, level): """*convert plain-text to MMD header* **Key Arguments:** - ``text`` -- the text to convert to MMD header - ``level`` -- the header level to convert the text to **Return:** - ``header`` -- th...
*genarate a MMD definition* **Key Arguments:** - ``text`` -- the text to define - ``definition`` -- the definition **Return:** - ``definition`` -- the MMD style definition **Usage:** To genarate a MMD definition: .. code-block:: py...
def definition( self, text, definition): """*genarate a MMD definition* **Key Arguments:** - ``text`` -- the text to define - ``definition`` -- the definition **Return:** - ``definition`` -- the MMD style definition ...
*generate a link to a MMD header* **Key Arguments:** - ``headerText`` -- the header text (or anchor tag) - ``text`` -- the doc text to link. Default *False* **Return:** - ``link`` -- the link to the header **Usage:** To generate a MMD header li...
def headerLink( self, headerText, text=False): """*generate a link to a MMD header* **Key Arguments:** - ``headerText`` -- the header text (or anchor tag) - ``text`` -- the doc text to link. Default *False* **Return:** - `...
*create MMD image link* **Key Arguments:** - ``title`` -- the title for the image - ``url`` -- the image URL - ``width`` -- the width in pixels of the image. Default *800* **Return:** - ``imageLink`` -- the MMD image link **Usage:** ...
def image( self, url, title="", width=800): """*create MMD image link* **Key Arguments:** - ``title`` -- the title for the image - ``url`` -- the image URL - ``width`` -- the width in pixels of the image. Default *800* ...
*convert plain-text to MMD blockquote* **Key Arguments:** - ``text`` -- the text to convert to MMD blockquote **Return:** - ``blockquote`` -- the MMD blockquote **Usage:** To convert a text to a MMD blockquote: .. code-block:: python ...
def blockquote( self, text): """*convert plain-text to MMD blockquote* **Key Arguments:** - ``text`` -- the text to convert to MMD blockquote **Return:** - ``blockquote`` -- the MMD blockquote **Usage:** To convert a text to...
*convert plain-text to MMD unordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD unordered list **Return:** - ``ul`` -- the MMD unordered list **Usage:** To convert text to a MMD unordered list: .. code-block:: python ...
def ul( self, text): """*convert plain-text to MMD unordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD unordered list **Return:** - ``ul`` -- the MMD unordered list **Usage:** To convert text to a MMD...
*convert plain-text to MMD ordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD ordered list **Return:** - ``ol`` -- the MMD ordered list **Usage:** To convert text to MMD ordered list: .. code-block:: python ...
def ol( self, text): """*convert plain-text to MMD ordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD ordered list **Return:** - ``ol`` -- the MMD ordered list **Usage:** To convert text to MMD ordered...
*convert plain-text to MMD fenced codeblock* **Key Arguments:** - ``text`` -- the text to convert to MMD fenced codeblock - ``lang`` -- the code language for syntax highlighting. Default *''* **Return:** - ``text`` -- the MMD fenced codeblock **Usage:** ...
def codeblock( self, text, lang=""): """*convert plain-text to MMD fenced codeblock* **Key Arguments:** - ``text`` -- the text to convert to MMD fenced codeblock - ``lang`` -- the code language for syntax highlighting. Default *''* **...
*generate a MMD sytle link* **Key Arguments:** - ``text`` -- the text to link from - ``url`` -- the url to link to **Return:** - ``text`` -- the linked text **Usage:** To convert a text and url to MMD link: .. code-block:: python ...
def inline_link( self, text, url): """*generate a MMD sytle link* **Key Arguments:** - ``text`` -- the text to link from - ``url`` -- the url to link to **Return:** - ``text`` -- the linked text **Usage:** ...
*snip the whitespace at the start and end of the text* **Key Arguments:** - ``text`` -- the text to snip **Return:** - ``prefix``, ``text``, ``suffix`` -- the starting whitespace, text and endding whitespace
def _snip_whitespace( self, text): """*snip the whitespace at the start and end of the text* **Key Arguments:** - ``text`` -- the text to snip **Return:** - ``prefix``, ``text``, ``suffix`` -- the starting whitespace, text and endding whitespace ...
*surround text with given characters* **Key Arguments:** - ``text`` -- the text to surround. - ``left`` -- characters to the left of text - ``right`` -- characters to the right of text **Return:** - ``text`` -- the surronded text
def _surround( self, text, left, right): """*surround text with given characters* **Key Arguments:** - ``text`` -- the text to surround. - ``left`` -- characters to the left of text - ``right`` -- characters to the righ...
Create and immediately drop into a Python shell. If IPython version 5 or greater is available it will be used instead of the built-in python shell. :param local_ns: An optional dict containing the global namespace of the newly created shell. :param banner: An optional banner to ...
def start_shell(local_ns: Dict=None, banner: str=''): """Create and immediately drop into a Python shell. If IPython version 5 or greater is available it will be used instead of the built-in python shell. :param local_ns: An optional dict containing the global namespace of the n...
Replace CONSTANT_INDEX operands with the literal Constant object from the constant pool. :param ins: Instruction to potentially modify. :param cf: The ClassFile instance used to resolve Constants. :return: Potentially modified instruction.
def expand_constants(ins: Instruction, *, cf) -> Instruction: """Replace CONSTANT_INDEX operands with the literal Constant object from the constant pool. :param ins: Instruction to potentially modify. :param cf: The ClassFile instance used to resolve Constants. :return: Potentially modified instruc...
Replaces one instruction with another based on the transform rules in the bytecode definitions. This can help simplify your code as it reduces the overall number of instructions. For example, `aload_0` will become `aload 0`. :param ins: Instruction to potentially modify. :return: Potentially modifi...
def simple_swap(ins: Instruction) -> Instruction: """Replaces one instruction with another based on the transform rules in the bytecode definitions. This can help simplify your code as it reduces the overall number of instructions. For example, `aload_0` will become `aload 0`. :param ins: Instructi...
Inspect running environment for request object. There should be one, but don't rely on it.
def find_request(): ''' Inspect running environment for request object. There should be one, but don't rely on it. ''' frame = inspect.currentframe() request = None f = frame while not request and f: if 'request' in f.f_locals and isinstance(f.f_locals['request'], HttpRequest): request = f.f_locals['reque...
with_user_roles(roles) It allows to check if a user has access to a view by adding the decorator with_user_roles([]) Requires flask-login In your model, you must have a property 'role', which will be invoked to be compared to the roles provided. If current_user doesn't have a role, it will t...
def with_user_roles(roles): """ with_user_roles(roles) It allows to check if a user has access to a view by adding the decorator with_user_roles([]) Requires flask-login In your model, you must have a property 'role', which will be invoked to be compared to the roles provided. If cur...
:param UserStruct: The User model structure containing other classes :param login_view: The login view interface :param template_dir: The directory containing the view pages :return: UserAdmin Doc: User Admin is a view that allows you to admin users. You must create a Pylot view called `UserAdm...
def user_admin_view(model, login_view="Login", template_dir=None): """ :param UserStruct: The User model structure containing other classes :param login_view: The login view interface :param template_dir: The directory containing the view pages :return: UserAdmin Doc: User Admin is a view t...
:param PostStruct:
def post_manager_view(model, view="PostManager", template_dir=None): """ :param PostStruct: """ PostStruct = model.PostStruct Pylot.context_(COMPONENT_POST_MANAGER=True) if not template_dir: template_dir = "Pylot/PostManager" template_page = template_dir + "/%s.html" class Po...
Create the Maintenance view Must be instantiated import maintenance_view MaintenanceView = maintenance_view() :param view_template: The directory containing the view pages :return:
def maintenance_view(template=None): """ Create the Maintenance view Must be instantiated import maintenance_view MaintenanceView = maintenance_view() :param view_template: The directory containing the view pages :return: """ if not template: template = "Pylot/Maintenance/i...
Create the Error view Must be instantiated import error_view ErrorView = error_view() :param template_dir: The directory containing the view pages :return:
def error_view(template_dir=None): """ Create the Error view Must be instantiated import error_view ErrorView = error_view() :param template_dir: The directory containing the view pages :return: """ if not template_dir: template_dir = "Pylot/Error" template_page = "%s/...
{{ s|nl2br }} Convert newlines into <p> and <br />s.
def nl2br(s): """ {{ s|nl2br }} Convert newlines into <p> and <br />s. """ if not isinstance(s, basestring): s = str(s) s = re.sub(r'\r\n|\r|\n', '\n', s) paragraphs = re.split('\n{2,}', s) paragraphs = ['<p>%s</p>' % p.strip().replace('\n', '<br />') for p in paragraphs] re...
Allow to create Signed object to upload to S3 via JS
def sign_s3_upload(self): """ Allow to create Signed object to upload to S3 via JS """ AWS_ACCESS_KEY = self.config_('AWS_ACCESS_KEY_ID') AWS_SECRET_KEY = self.config_('AWS_SECRET_ACCESS_KEY') S3_BUCKET = self.config_('AWS_S3_BUCKET_NAME') object_name = request.a...
Post Model
def post_struct(UserStruct): """ Post Model """ db = UserStruct.User.db class SlugNameMixin(object): name = db.Column(db.String(250)) slug = db.Column(db.String(250), index=True, unique=True) @classmethod def get_by_slug(cls, slug): """ Ret...
Register as callback for when new devices are added.
def add_new_devices_callback(self, callback): """Register as callback for when new devices are added. """ self._new_devices_callbacks.append(callback) _LOGGER.debug('Added new devices callback to %s', callback)
Call registered callback functions.
def _do_new_devices_callback(self, msg): """Call registered callback functions.""" for callback in self._new_devices_callbacks: _LOGGER.debug('Devices callback %s', callback) self._event_loop.call_soon(callback, msg)
Register as callback for when stale devices exist.
def add_stale_devices_callback(self, callback): """Register as callback for when stale devices exist. """ self._stale_devices_callbacks.append(callback) _LOGGER.debug('Added stale devices callback to %s', callback)
Call registered callback functions.
def _do_stale_devices_callback(self, msg): """Call registered callback functions.""" for callback in self._stale_devices_callbacks: _LOGGER.debug('Stale Devices callback %s', callback) self._event_loop.call_soon(callback, msg)
Register as callback for when a matching device changes.
def add_update_callback(self, callback, device): """Register as callback for when a matching device changes.""" self._update_callbacks.append([callback, device]) _LOGGER.debug('Added update callback to %s on %s', callback, device)
Remove a registered update callback.
def remove_update_callback(self, callback, device): """ Remove a registered update callback. """ if [callback, device] in self._update_callbacks: self._update_callbacks.remove([callback, device]) _LOGGER.debug('Removed update callback %s for %s', callbac...
Call registered callback functions.
def _do_update_callback(self, msg): """Call registered callback functions.""" for callback, device in self._update_callbacks: if device == msg: _LOGGER.debug('Update callback %s for device %s by %s', callback, device, msg) self._e...
Public method for initiating connectivity with the emby server.
def start(self): """Public method for initiating connectivity with the emby server.""" asyncio.ensure_future(self.register(), loop=self._event_loop) if self._own_loop: _LOGGER.info("Starting up our own event loop.") self._event_loop.run_forever() self._event_...
Async method for stopping connectivity with the emby server.
async def stop(self): """Async method for stopping connectivity with the emby server.""" self._shutdown = True if self.wsck: _LOGGER.info('Closing Emby server websocket.') await self.wsck.close() self.wsck = None if self._own_loop: _LOGGE...
Return http/https or ws/wss url.
def construct_url(self, style): """ Return http/https or ws/wss url. """ if style is API_URL: if self._ssl: return 'https://{}:{}'.format(self._host, self._port) else: return 'http://{}:{}'.format(self._host, self._port) elif style is SOCKE...
Register library device id and get initial device list.
async def register(self): """Register library device id and get initial device list. """ url = '{}/Sessions'.format(self.construct_url(API_URL)) params = {'api_key': self._api_key} reg = await self.api_request(url, params) if reg is None: self._registered = False ...
Make api post request.
async def api_post(self, url, params): """Make api post request.""" post = None try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): post = await self._api_session.post( url, params=params) if post.status != 204: ...
Make api fetch request.
async def api_request(self, url, params): """Make api fetch request.""" request = None try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): request = await self._api_session.get( url, params=params) if request.status...
Open websocket connection.
async def socket_connection(self): """ Open websocket connection. """ if not self._registered: _LOGGER.error('Client not registered, cannot start socket.') return url = '{}?DeviceID={}&api_key={}'.format( self.construct_url(SOCKET_URL), self._api_id, self._ap...
Process messages from the event stream.
def process_msg(self, msg): """Process messages from the event stream.""" jmsg = json.loads(msg) msgtype = jmsg['MessageType'] msgdata = jmsg['Data'] _LOGGER.debug('New websocket message recieved of type: %s', msgtype) if msgtype == 'Sessions': self._sessions...
Update device list.
def update_device_list(self, sessions): """ Update device list. """ if sessions is None: _LOGGER.error('Error updating Emby devices.') return new_devices = [] active_devices = [] dev_update = False for device in sessions: dev_name = '{...
Check device state to see if we need to fire the callback. True if either state is 'Playing' False if both states are: 'Paused', 'Idle', or 'Off' True on any state transition.
def update_check(self, existing, new): """ Check device state to see if we need to fire the callback. True if either state is 'Playing' False if both states are: 'Paused', 'Idle', or 'Off' True on any state transition. """ old_state = existing.state if 'NowPlayin...
Entry point for f2format.
def main(): """Entry point for f2format.""" parser = get_parser() args = parser.parse_args() # set up variables ARCHIVE = args.archive_path archive = (not args.no_archive) os.environ['F2FORMAT_VERSION'] = args.python os.environ['F2FORMAT_ENCODING'] = args.encoding def find(root): ...
A utility which sets up reasonable defaults for a new public class. :param this: The name of this class. :param super_: The name of this class's superclass.
def create(cls, this: str, super_: str=u'java/lang/Object') -> 'ClassFile': """ A utility which sets up reasonable defaults for a new public class. :param this: The name of this class. :param super_: The name of this class's superclass. """ cf = ClassFile() cf.ac...
Saves the class to the file-like object `source`. :param source: Any file-like object providing write().
def save(self, source: IO): """ Saves the class to the file-like object `source`. :param source: Any file-like object providing write(). """ write = source.write write(pack( '>IHH', ClassFile.MAGIC, self.version.minor, sel...
Loads an existing JVM ClassFile from any file-like object.
def _from_io(self, source: IO): """ Loads an existing JVM ClassFile from any file-like object. """ read = source.read if unpack('>I', source.read(4))[0] != ClassFile.MAGIC: raise ValueError('invalid magic number') # The version is swapped on disk to (minor, ...
A list of direct superinterfaces of this class as indexes into the constant pool, in left-to-right order.
def interfaces(self) -> Iterable[ConstantClass]: """ A list of direct superinterfaces of this class as indexes into the constant pool, in left-to-right order. """ return [self._constants[idx] for idx in self._interfaces]
Returns the bootstrap methods table from the BootstrapMethods attribute, if one exists. If it does not, one will be created. :returns: Table of `BootstrapMethod` objects.
def bootstrap_methods(self) -> BootstrapMethod: """ Returns the bootstrap methods table from the BootstrapMethods attribute, if one exists. If it does not, one will be created. :returns: Table of `BootstrapMethod` objects. """ bootstrap = self.attributes.find_one(name='B...
List enabled Attributes. Prints a list of all enabled ClassFile Attributes.
def attributes(): """List enabled Attributes. Prints a list of all enabled ClassFile Attributes. """ attribute_classes = get_attribute_classes() for name, class_ in attribute_classes.items(): click.echo( u'{name} - Added in: {ai} ({cv})'.format( name=click.style(...
Lookup instruction information. Lookup an instruction by its mnemonic.
def ins(mnemonic): """Lookup instruction information. Lookup an instruction by its mnemonic. """ try: opcode = bytecode.opcode_table[mnemonic] except KeyError: click.secho(u'No definition found.', fg='red') return click.echo(u'{mnemonic} (0x{op})'.format( mnemon...
Drop into a debugging shell.
def shell_command(class_path): """Drop into a debugging shell.""" loader = ClassLoader(*class_path) shell.start_shell(local_ns={ 'ClassFile': ClassFile, 'loader': loader, 'constants': importlib.import_module('jawa.constants'), })
Convert a bytecode.yaml file into a prepared bytecode.json. Jawa internally uses a YAML file to define all bytecode opcodes, operands, runtime exceptions, default transforms, etc... However since JSON is available in the python stdlib and YAML is not, we process this YAML file before distribution to p...
def definition_to_json(source): """Convert a bytecode.yaml file into a prepared bytecode.json. Jawa internally uses a YAML file to define all bytecode opcodes, operands, runtime exceptions, default transforms, etc... However since JSON is available in the python stdlib and YAML is not, we process ...
Output a list of all classes referenced by the given source.
def dependencies(source): """Output a list of all classes referenced by the given source.""" loader = ClassLoader(source, max_cache=-1) all_dependencies = set() for klass in loader.classes: new_dependencies = loader.dependencies(klass) - all_dependencies all_dependencies.update(new_depen...
Grep the constant pool of all classes in source.
def grep(source, regex, stop_on_first=False): """Grep the constant pool of all classes in source.""" loader = ClassLoader(source, max_cache=-1) r = re.compile(regex) def _matches(constant): return r.match(constant.value) for klass in loader.classes: it = loader.search_constant_pool...
fetch an URL. :func:`~urlfetch.fetch` is a wrapper of :func:`~urlfetch.request`. It calls :func:`~urlfetch.get` by default. If one of parameter ``data`` or parameter ``files`` is supplied, :func:`~urlfetch.post` is called.
def fetch(*args, **kwargs): """fetch an URL. :func:`~urlfetch.fetch` is a wrapper of :func:`~urlfetch.request`. It calls :func:`~urlfetch.get` by default. If one of parameter ``data`` or parameter ``files`` is supplied, :func:`~urlfetch.post` is called. """ data = kwargs.get('data', None) f...
request an URL :arg string url: URL to be fetched. :arg string method: (optional) HTTP method, one of ``GET``, ``DELETE``, ``HEAD``, ``OPTIONS``, ``PUT``, ``POST``, ``TRACE``, ``PATCH``. ``GET`` is the default. :arg dict/string params: (optional) Dict or stri...
def request(url, method="GET", params=None, data=None, headers={}, timeout=None, files={}, randua=False, auth=None, length_limit=None, proxies=None, trust_env=True, max_redirects=0, source_address=None, **kwargs): """request an URL :arg string url: URL to be fetched. :ar...
Return a dictionary of parsed url Including scheme, netloc, path, params, query, fragment, uri, username, password, host, port and http_host
def parse_url(url): """Return a dictionary of parsed url Including scheme, netloc, path, params, query, fragment, uri, username, password, host, port and http_host """ try: url = unicode(url) except UnicodeDecodeError: pass if py3k: make_utf8 = lambda x: x else:...
encoding/decoding helper.
def mb_code(s, coding=None, errors='replace'): """encoding/decoding helper.""" if isinstance(s, unicode): return s if coding is None else s.encode(coding, errors=errors) for c in ('utf-8', 'gb2312', 'gbk', 'gb18030', 'big5'): try: s = s.decode(c) return s if coding is...
Get proxies from os.environ.
def get_proxies_from_environ(): """Get proxies from os.environ.""" proxies = {} http_proxy = os.getenv('http_proxy') or os.getenv('HTTP_PROXY') https_proxy = os.getenv('https_proxy') or os.getenv('HTTPS_PROXY') if http_proxy: proxies['http'] = http_proxy if https_proxy: proxies['...
Returns a User-Agent string randomly from file. :arg string filename: (Optional) Path to the file from which a random useragent is generated. By default it's ``True``, a file shipped with this module will be used. :returns: An user-agent string.
def random_useragent(filename=True): """Returns a User-Agent string randomly from file. :arg string filename: (Optional) Path to the file from which a random useragent is generated. By default it's ``True``, a file shipped with this module will be used. :returns: An user-agent string. "...
Concatenate url and argument dictionary >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' :arg string url: URL being concat to. :arg dict args: Args being concat. :arg bool keep_existing: (Optional) Whether to keep the args which are ...
def url_concat(url, args, keep_existing=True): """Concatenate url and argument dictionary >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' :arg string url: URL being concat to. :arg dict args: Args being concat. :arg bool keep_existing: (Optional) Whet...
Generate a multipart boundry. :returns: A boundary string
def choose_boundary(): """Generate a multipart boundry. :returns: A boundary string """ global BOUNDARY_PREFIX if BOUNDARY_PREFIX is None: BOUNDARY_PREFIX = "urlfetch" try: uid = repr(os.getuid()) BOUNDARY_PREFIX += "." + uid except AttributeError: ...
Encode multipart. :arg dict data: Data to be encoded :arg dict files: Files to be encoded :returns: Encoded binary string :raises: :class:`UrlfetchException`
def encode_multipart(data, files): """Encode multipart. :arg dict data: Data to be encoded :arg dict files: Files to be encoded :returns: Encoded binary string :raises: :class:`UrlfetchException` """ body = BytesIO() boundary = choose_boundary() part_boundary = b('--%s\r\n' % bounda...
Response body. :raises: :class:`ContentLimitExceeded`, :class:`ContentDecodingError`
def body(self): """Response body. :raises: :class:`ContentLimitExceeded`, :class:`ContentDecodingError` """ content = [] length = 0 for chunk in self: content.append(chunk) length += len(chunk) if self.length_limit and length > self.le...
Load response body as json. :raises: :class:`ContentDecodingError`
def json(self): """Load response body as json. :raises: :class:`ContentDecodingError` """ try: return json.loads(self.text) except Exception as e: raise ContentDecodingError(e)
Response headers. Response headers is a dict with all keys in lower case. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.headers { 'content-length': '8719', 'x-cache': 'MISS from localhost', 'accept-ra...
def headers(self): """Response headers. Response headers is a dict with all keys in lower case. >>> import urlfetch >>> response = urlfetch.get("http://docs.python.org/") >>> response.headers { 'content-length': '8719', 'x-cache': 'MISS from loca...
Cookies in dict
def cookies(self): """Cookies in dict""" c = Cookie.SimpleCookie(self.getheader('set-cookie')) return dict((i.key, i.value) for i in c.values())
Cookie string
def cookiestring(self): """Cookie string""" return '; '.join('%s=%s' % (k, v) for k, v in self.cookies.items())
Links parsed from HTTP Link header
def links(self): """Links parsed from HTTP Link header""" ret = [] linkheader = self.getheader('link') if not linkheader: return ret for i in linkheader.split(','): try: url, params = i.split(';', 1) except ValueError: ...
Cookie string setter
def cookiestring(self, value): """"Cookie string setter""" c = Cookie.SimpleCookie(value) sc = [(i.key, i.value) for i in c.values()] self.cookies = dict(sc)
Issue a request.
def request(self, *args, **kwargs): """Issue a request.""" headers = self.headers.copy() if self.cookiestring: headers['Cookie'] = self.cookiestring headers.update(kwargs.get('headers', {})) kwargs['headers'] = headers r = request(*args, **kwargs) sel...
This helper function handles incoming test_data for make_object_dict. If thereis a special handler in git_object_handlers_lookup, this is used. Otherwise, the given name:obj pair is returned as-is. :param name: String :param obj: The object to be processed. :return: A dictionary of attributes.
def handle_object(name, obj): """ This helper function handles incoming test_data for make_object_dict. If thereis a special handler in git_object_handlers_lookup, this is used. Otherwise, the given name:obj pair is returned as-is. :param name: String :param obj: The object to be processed. ...
Processes an object, exporting its data as a nested dictionary. Individual objects are handled using handle_object. :param obj: The object to be processed. :param keep: Object attributes to be kept. Defaults to all attributes. :return: A dictionary of attributes.
def make_object_dict(obj, keep=[]): """ Processes an object, exporting its data as a nested dictionary. Individual objects are handled using handle_object. :param obj: The object to be processed. :param keep: Object attributes to be kept. Defaults to all attributes. :return: A dictionary of attr...
Extracts Git commit test_data from a local repository. :param rpath: The path to a local Git repo. :param extract: A list of attribute name strings. :return: A Pandas dataframe containing Git commit test_data.
def extract_log(rpath,extract=simple_attributes): """ Extracts Git commit test_data from a local repository. :param rpath: The path to a local Git repo. :param extract: A list of attribute name strings. :return: A Pandas dataframe containing Git commit test_data. """ # Get repo m_repo = ...
The main conversion process. Args: - string -- str, context to be converted - lineno -- dict<int: int>, line number to actual offset mapping Returns: - str -- converted string
def convert(string, lineno): """The main conversion process. Args: - string -- str, context to be converted - lineno -- dict<int: int>, line number to actual offset mapping Returns: - str -- converted string """ def parse(string): try: return parso.parse(string,...
Wrapper works for conversion. Args: - filename -- str, file to be converted
def f2format(filename): """Wrapper works for conversion. Args: - filename -- str, file to be converted """ print('Now converting %r...' % filename) # fetch encoding encoding = os.getenv('F2FORMAT_ENCODING', LOCALE_ENCODING) lineno = dict() # line number -> file offset conten...
If any exception comes, log them in the given Github obj.
def exception_to_github(github_obj_to_comment, summary=""): """If any exception comes, log them in the given Github obj. """ context = ExceptionContext() try: yield context except Exception: # pylint: disable=broad-except if summary: summary = ": ({})".format(summary) ...
Create a comment, whatever the object is a PR, a commit or an issue.
def create_comment(github_object, body): """Create a comment, whatever the object is a PR, a commit or an issue. """ try: return github_object.create_issue_comment(body) # It's a PR except AttributeError: return github_object.create_comment(body)
git config --global user.email "you@example.com" git config --global user.name "Your Name"
def configure_user(gh_token, repo): """git config --global user.email "you@example.com" git config --global user.name "Your Name" """ user = user_from_token(gh_token) repo.git.config('user.email', user.email or 'aspysdk2@microsoft.com') repo.git.config('user.name', user.name or 'SwaggerToSDK ...
If the SDK git id is incomplete, try to complete it with user login
def get_full_sdk_id(gh_token, sdk_git_id): """If the SDK git id is incomplete, try to complete it with user login""" if not '/' in sdk_git_id: login = user_from_token(gh_token).login return '{}/{}'.format(login, sdk_git_id) return sdk_git_id
Sync the current branch in this fork against the direct parent on Github
def sync_fork(gh_token, github_repo_id, repo, push=True): """Sync the current branch in this fork against the direct parent on Github""" if not gh_token: _LOGGER.warning('Skipping the upstream repo sync, no token') return _LOGGER.info('Check if repo has to be sync with upstream') github_...
Try to create the PR. If the PR exists, try to find it instead. Raises otherwise. You should always use the complete head syntax "org:branch", since the syntax is required in case of listing. if "none_if_no_commit" is set, return None instead of raising exception if the problem is that head and base a...
def get_or_create_pull(github_repo, title, body, head, base, *, none_if_no_commit=False): """Try to create the PR. If the PR exists, try to find it instead. Raises otherwise. You should always use the complete head syntax "org:branch", since the syntax is required in case of listing. if "none_if_no_co...
Clone the given repo_id to the folder. If PR number is specified fetch the magic branches pull/<id>/head or pull/<id>/merge from Github. "merge" is tried first, and fallback to "head". Beware that pr_number implies detached head, and then no push is possible. If branch is specified, checkout this bran...
def clone_to_path(gh_token, folder, sdk_git_id, branch_or_commit=None, *, pr_number=None): """Clone the given repo_id to the folder. If PR number is specified fetch the magic branches pull/<id>/head or pull/<id>/merge from Github. "merge" is tried first, and fallback to "head". Beware that pr_number im...
Do the PR
def do_pr(gh_token, sdk_git_id, sdk_pr_target_repo_id, branch_name, base_branch, pr_body=""): # pylint: disable=too-many-arguments "Do the PR" if not gh_token: _LOGGER.info('Skipping the PR, no token found') return None if not sdk_pr_target_repo_id: _LOGGER.info('Skipping the PR, no...
Clear the readonly bit and reattempt the removal
def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path)
Context manager to avoid readonly problem while cleanup the temp dir. If PR number is given, use magic branches "pull" from Github.
def manage_git_folder(gh_token, temp_dir, git_id, *, pr_number=None): """Context manager to avoid readonly problem while cleanup the temp dir. If PR number is given, use magic branches "pull" from Github. """ _LOGGER.debug("Git ID %s", git_id) if Path(git_id).exists(): yield git_id ...
Returns a GithubLink to a raw content.
def as_raw_link(self): """Returns a GithubLink to a raw content. """ if self.link_type == "raw": return self # Can be discussed if we need an hard copy, or fail if self.link_type != "blob": raise ValueError("Cannot get a download link from a tree link") re...
Mimic issue API, so we can use it everywhere. Return dashboard comment.
def create_comment(self, text): """Mimic issue API, so we can use it everywhere. Return dashboard comment. """ return DashboardComment.get_or_create(self._issue_or_pr, self._header, text)