Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def appendArgs(url, args): if hasattr(args, 'items'): args = args.items() args.sort() else: args = list(args) if len(args) == 0: return url if '?' in url: sep = '&' else: sep = '?' # Map unicode ...
[ "Append query arguments to a HTTP(s) URL. If the URL already has\n query arguemtns, these arguments will be added, and the existing\n arguments will be preserved. Duplicate arguments will not be\n detected or collapsed (both will appear in the output).\n\n @param url: The url to which the arguments will...
Please provide a description of the function:def parseXRDS(text): try: element = ElementTree.XML(text) except XMLError, why: exc = XRDSError('Error parsing document as XML') exc.reason = why raise exc else: tree = ElementTree.ElementTree(element) if not i...
[ "Parse the given text as an XRDS document.\n\n @return: ElementTree containing an XRDS document\n\n @raises XRDSError: When there is a parse error or the document does\n not contain an XRDS.\n " ]
Please provide a description of the function:def getYadisXRD(xrd_tree): xrd = None # for the side-effect of assigning the last one in the list to the # xrd variable for xrd in xrd_tree.findall(xrd_tag): pass # There were no elements found, or else xrd would be set to the # last on...
[ "Return the XRD element that should contain the Yadis services" ]
Please provide a description of the function:def getXRDExpiration(xrd_element, default=None): expires_element = xrd_element.find(expires_tag) if expires_element is None: return default else: expires_string = expires_element.text # Will raise ValueError if the string is not the ...
[ "Return the expiration date of this XRD element, or None if no\n expiration was specified.\n\n @type xrd_element: ElementTree node\n\n @param default: The value to use as the expiration if no\n expiration was specified in the XRD.\n\n @rtype: datetime.datetime\n\n @raises ValueError: If the xr...
Please provide a description of the function:def getCanonicalID(iname, xrd_tree): xrd_list = xrd_tree.findall(xrd_tag) xrd_list.reverse() try: canonicalID = xri.XRI(xrd_list[0].findall(canonicalID_tag)[0].text) except IndexError: return None childID = canonicalID.lower() ...
[ "Return the CanonicalID from this XRDS document.\n\n @param iname: the XRI being resolved.\n @type iname: unicode\n\n @param xrd_tree: The XRDS output from the resolver.\n @type xrd_tree: ElementTree\n\n @returns: The XRI CanonicalID or None.\n @returntype: unicode or None\n " ]
Please provide a description of the function:def getPriorityStrict(element): prio_str = element.get('priority') if prio_str is not None: prio_val = int(prio_str) if prio_val >= 0: return prio_val else: raise ValueError('Priority values must be non-negative in...
[ "Get the priority of this element.\n\n Raises ValueError if the value of the priority is invalid. If no\n priority is specified, it returns a value that compares greater\n than any other value.\n " ]
Please provide a description of the function:def prioSort(elements): # Randomize the services before sorting so that equal priority # elements are load-balanced. random.shuffle(elements) prio_elems = [(getPriority(e), e) for e in elements] prio_elems.sort() sorted_elems = [s for (_, s) in ...
[ "Sort a list of elements that have priority attributes" ]
Please provide a description of the function:def expandService(service_element): uris = sortedURIs(service_element) if not uris: uris = [None] expanded = [] for uri in uris: type_uris = getTypeURIs(service_element) expanded.append((type_uris, uri, service_element)) ret...
[ "Take a service element and expand it into an iterator of:\n ([type_uri], uri, service_element)\n " ]
Please provide a description of the function:def expandServices(service_elements): expanded = [] for service_element in service_elements: expanded.extend(expandService(service_element)) return expanded
[ "Take a sorted iterator of service elements and expand it into a\n sorted iterator of:\n ([type_uri], uri, service_element)\n\n There may be more than one item in the resulting list for each\n service element if there is more than one URI or type for a\n service, but each triple will be unique.\n\n ...
Please provide a description of the function:def makeKVPost(request_message, server_url): # XXX: TESTME resp = fetchers.fetch(server_url, body=request_message.toURLEncoded()) # Process response in separate function that can be shared by async code. return _httpResponseToMessage(resp, server_url)
[ "Make a Direct Request to an OpenID Provider and return the\n result as a Message object.\n\n @raises openid.fetchers.HTTPFetchingError: if an error is\n encountered in making the HTTP post.\n\n @rtype: L{openid.message.Message}\n " ]
Please provide a description of the function:def _httpResponseToMessage(response, server_url): # Should this function be named Message.fromHTTPResponse instead? response_message = Message.fromKVForm(response.body) if response.status == 400: raise ServerError.fromMessage(response_message) e...
[ "Adapt a POST response to a Message.\n\n @type response: L{openid.fetchers.HTTPResponse}\n @param response: Result of a POST to an OpenID endpoint.\n\n @rtype: L{openid.message.Message}\n\n @raises openid.fetchers.HTTPFetchingError: if the server returned a\n status of other than 200 or 400.\n\n ...
Please provide a description of the function:def complete(self, query, current_url): endpoint = self.session.get(self._token_key) message = Message.fromPostArgs(query) response = self.consumer.complete(message, endpoint, current_url) try: del self.session[self._to...
[ "Called to interpret the server's response to an OpenID\n request. It is called in step 4 of the flow described in the\n consumer overview.\n\n @param query: A dictionary of the query parameters for this\n HTTP request.\n\n @param current_url: The URL used to invoke the applic...
Please provide a description of the function:def fromMessage(cls, message): error_text = message.getArg( OPENID_NS, 'error', '<no error message supplied>') error_code = message.getArg(OPENID_NS, 'error_code') return cls(error_text, error_code, message)
[ "Generate a ServerError instance, extracting the error text\n and the error code from the message." ]
Please provide a description of the function:def begin(self, service_endpoint): if self.store is None: assoc = None else: assoc = self._getAssociation(service_endpoint) request = AuthRequest(service_endpoint, assoc) request.return_to_args[self.openid1_no...
[ "Create an AuthRequest object for the specified\n service_endpoint. This method will create an association if\n necessary." ]
Please provide a description of the function:def complete(self, message, endpoint, return_to): mode = message.getArg(OPENID_NS, 'mode', '<No mode set>') modeMethod = getattr(self, '_complete_' + mode, self._completeInvalid) return modeMethod(message, endpo...
[ "Process the OpenID message, using the specified endpoint\n and return_to URL as context. This method will handle any\n OpenID message that is sent to the return_to URL.\n " ]
Please provide a description of the function:def _checkSetupNeeded(self, message): # In OpenID 1, we check to see if this is a cancel from # immediate mode by the presence of the user_setup_url # parameter. if message.isOpenID1(): user_setup_url = message.getArg(OPEN...
[ "Check an id_res message to see if it is a\n checkid_immediate cancel response.\n\n @raises SetupNeededError: if it is a checkid_immediate cancellation\n " ]
Please provide a description of the function:def _doIdRes(self, message, endpoint, return_to): # Checks for presence of appropriate fields (and checks # signed list fields) self._idResCheckForFields(message) if not self._checkReturnTo(message, return_to): raise Prot...
[ "Handle id_res responses that are not cancellations of\n immediate mode requests.\n\n @param message: the response paramaters.\n @param endpoint: the discovered endpoint object. May be None.\n\n @raises ProtocolError: If the message contents are not\n well-formed according to ...
Please provide a description of the function:def _verifyReturnToArgs(query): message = Message.fromPostArgs(query) return_to = message.getArg(OPENID_NS, 'return_to') if return_to is None: raise ProtocolError('Response has no return_to') parsed_url = urlparse(return...
[ "Verify that the arguments in the return_to URL are present in this\n response.\n " ]
Please provide a description of the function:def _verifyDiscoveryResults(self, resp_msg, endpoint=None): if resp_msg.getOpenIDNamespace() == OPENID2_NS: return self._verifyDiscoveryResultsOpenID2(resp_msg, endpoint) else: return self._verifyDiscoveryResultsOpenID1(resp_m...
[ "\n Extract the information from an OpenID assertion message and\n verify it against the original\n\n @param endpoint: The endpoint that resulted from doing discovery\n @param resp_msg: The id_res message object\n\n @returns: the verified endpoint\n " ]
Please provide a description of the function:def _verifyDiscoverySingle(self, endpoint, to_match): # Every type URI that's in the to_match endpoint has to be # present in the discovered endpoint. for type_uri in to_match.type_uris: if not endpoint.usesExtension(type_uri): ...
[ "Verify that the given endpoint matches the information\n extracted from the OpenID assertion, and raise an exception if\n there is a mismatch.\n\n @type endpoint: openid.consumer.discover.OpenIDServiceEndpoint\n @type to_match: openid.consumer.discover.OpenIDServiceEndpoint\n\n @...
Please provide a description of the function:def _discoverAndVerify(self, claimed_id, to_match_endpoints): logging.info('Performing discovery on %s' % (claimed_id,)) _, services = self._discover(claimed_id) if not services: raise DiscoveryFailure('No OpenID information found...
[ "Given an endpoint object created from the information in an\n OpenID response, perform discovery and verify the discovery\n results, returning the matching endpoint that is the result of\n doing that discovery.\n\n @type to_match: openid.consumer.discover.OpenIDServiceEndpoint\n ...
Please provide a description of the function:def _createCheckAuthRequest(self, message): signed = message.getArg(OPENID_NS, 'signed') if signed: for k in signed.split(','): logging.info(k) val = message.getAliasedArg(k) # Signed value...
[ "Generate a check_authentication request message given an\n id_res message.\n " ]
Please provide a description of the function:def _processCheckAuthResponse(self, response, server_url): is_valid = response.getArg(OPENID_NS, 'is_valid', 'false') invalidate_handle = response.getArg(OPENID_NS, 'invalidate_handle') if invalidate_handle is not None: logging.i...
[ "Process the response message from a check_authentication\n request, invalidating associations if requested.\n " ]
Please provide a description of the function:def _getAssociation(self, endpoint): assoc = self.store.getAssociation(endpoint.server_url) if assoc is None or assoc.expiresIn <= 0: assoc = self._negotiateAssociation(endpoint) if assoc is not None: self.sto...
[ "Get an association for the endpoint's server_url.\n\n First try seeing if we have a good association in the\n store. If we do not, then attempt to negotiate an association\n with the server.\n\n If we negotiate a good association, it will get stored.\n\n @returns: A valid associa...
Please provide a description of the function:def _extractSupportedAssociationType(self, server_error, endpoint, assoc_type): # Any error message whose code is not 'unsupported-type' # should be considered a total failure. if server_error.error_co...
[ "Handle ServerErrors resulting from association requests.\n\n @returns: If server replied with an C{unsupported-type} error,\n return a tuple of supported C{association_type}, C{session_type}.\n Otherwise logs the error and returns None.\n @rtype: tuple or None\n " ]
Please provide a description of the function:def _requestAssociation(self, endpoint, assoc_type, session_type): assoc_session, args = self._createAssociateRequest( endpoint, assoc_type, session_type) try: response = self._makeKVPost(args, endpoint.server_url) ex...
[ "Make and process one association request to this endpoint's\n OP endpoint URL.\n\n @returns: An association object or None if the association\n processing failed.\n\n @raises ServerError: when the remote OpenID server returns an error.\n " ]
Please provide a description of the function:def _createAssociateRequest(self, endpoint, assoc_type, session_type): session_type_class = self.session_types[session_type] assoc_session = session_type_class() args = { 'mode': 'associate', 'assoc_type': assoc_type,...
[ "Create an association request for the given assoc_type and\n session_type.\n\n @param endpoint: The endpoint whose server_url will be\n queried. The important bit about the endpoint is whether\n it's in compatiblity mode (OpenID 1.1)\n\n @param assoc_type: The association...
Please provide a description of the function:def _getOpenID1SessionType(self, assoc_response): # If it's an OpenID 1 message, allow session_type to default # to None (which signifies "no-encryption") session_type = assoc_response.getArg(OPENID1_NS, 'session_type') # Handle the ...
[ "Given an association response message, extract the OpenID\n 1.X session type.\n\n This function mostly takes care of the 'no-encryption' default\n behavior in OpenID 1.\n\n If the association type is plain-text, this function will\n return 'no-encryption'\n\n @returns: The...
Please provide a description of the function:def _extractAssociation(self, assoc_response, assoc_session): # Extract the common fields from the response, raising an # exception if they are not found assoc_type = assoc_response.getArg( OPENID_NS, 'assoc_type', no_default) ...
[ "Attempt to extract an association from the response, given\n the association response message and the established\n association session.\n\n @param assoc_response: The association response message from\n the server\n @type assoc_response: openid.message.Message\n\n @pa...
Please provide a description of the function:def setAnonymous(self, is_anonymous): if is_anonymous and self.message.isOpenID1(): raise ValueError('OpenID 1 requests MUST include the ' 'identifier in the request') else: self._anonymous = is_an...
[ "Set whether this request should be made anonymously. If a\n request is anonymous, the identifier will not be sent in the\n request. This is only useful if you are making another kind of\n request with an extension in this request.\n\n Anonymous requests are not allowed when the request ...
Please provide a description of the function:def addExtensionArg(self, namespace, key, value): self.message.setArg(namespace, key, value)
[ "Add an extension argument to this OpenID authentication\n request.\n\n Use caution when adding arguments, because they will be\n URL-escaped and appended to the redirect URL, which can easily\n get quite long.\n\n @param namespace: The namespace for the extension. For\n ...
Please provide a description of the function:def getMessage(self, realm, return_to=None, immediate=False): if return_to: return_to = oidutil.appendArgs(return_to, self.return_to_args) elif immediate: raise ValueError( '"return_to" is mandatory when using ...
[ "Produce a L{openid.message.Message} representing this request.\n\n @param realm: The URL (or URL pattern) that identifies your\n web site to the user when she is authorizing it.\n\n @type realm: str\n\n @param return_to: The URL that the OpenID provider will send the\n us...
Please provide a description of the function:def redirectURL(self, realm, return_to=None, immediate=False): message = self.getMessage(realm, return_to, immediate) return message.toURL(self.endpoint.server_url)
[ "Returns a URL with an encoded OpenID request.\n\n The resulting URL is the OpenID provider's endpoint URL with\n parameters appended as query arguments. You should redirect\n the user agent to this URL.\n\n OpenID 2.0 endpoints also accept POST requests, see\n C{L{shouldSendRedi...
Please provide a description of the function:def formMarkup(self, realm, return_to=None, immediate=False, form_tag_attrs=None): message = self.getMessage(realm, return_to, immediate) return message.toFormMarkup(self.endpoint.server_url, form_tag_attrs)
[ "Get html for a form to submit this request to the IDP.\n\n @param form_tag_attrs: Dictionary of attributes to be added to\n the form tag. 'accept-charset' and 'enctype' have defaults\n that can be overridden. If a value is supplied for\n 'action' or 'method', it will be repl...
Please provide a description of the function:def htmlMarkup(self, realm, return_to=None, immediate=False, form_tag_attrs=None): return oidutil.autoSubmitHTML(self.formMarkup(realm, return_to, ...
[ "Get an autosubmitting HTML page that submits this request to the\n IDP. This is just a wrapper for formMarkup.\n\n @see: formMarkup\n\n @returns: str\n " ]
Please provide a description of the function:def isSigned(self, ns_uri, ns_key): return self.message.getKey(ns_uri, ns_key) in self.signed_fields
[ "Return whether a particular key is signed, regardless of\n its namespace alias\n " ]
Please provide a description of the function:def getSigned(self, ns_uri, ns_key, default=None): if self.isSigned(ns_uri, ns_key): return self.message.getArg(ns_uri, ns_key, default) else: return default
[ "Return the specified signed field if available,\n otherwise return default\n " ]
Please provide a description of the function:def getSignedNS(self, ns_uri): msg_args = self.message.getArgs(ns_uri) for key in msg_args.iterkeys(): if not self.isSigned(ns_uri, key): logging.info("SuccessResponse.getSignedNS: (%s, %s) not signed." ...
[ "Get signed arguments from the response message. Return a\n dict of all arguments in the specified namespace. If any of\n the arguments are not signed, return None.\n " ]
Please provide a description of the function:def extensionResponse(self, namespace_uri, require_signed): if require_signed: return self.getSignedNS(namespace_uri) else: return self.message.getArgs(namespace_uri)
[ "Return response arguments in the specified namespace.\n\n @param namespace_uri: The namespace URI of the arguments to be\n returned.\n\n @param require_signed: True if the arguments should be among\n those signed in the response, False if you don't care.\n\n If require_signed is ...
Please provide a description of the function:def mkFilter(parts): # Convert the parts into a list, and pass to mkCompoundFilter if parts is None: parts = [BasicServiceEndpoint] try: parts = list(parts) except TypeError: return mkCompoundFilter([parts]) else: ret...
[ "Convert a filter-convertable thing into a filter\n\n @param parts: a filter, an endpoint, a callable, or a list of any of these.\n " ]
Please provide a description of the function:def mkCompoundFilter(parts): # Separate into a list of callables and a list of filter objects transformers = [] filters = [] for subfilter in parts: try: subfilter = list(subfilter) except TypeError: # If it's not ...
[ "Create a filter out of a list of filter-like things\n\n Used by mkFilter\n\n @param parts: list of filter, endpoint, callable or list of any of these\n " ]
Please provide a description of the function:def getServiceEndpoints(self, yadis_url, service_element): endpoints = [] # Do an expansion of the service element by xrd:Type and xrd:URI for type_uris, uri, _ in expandService(service_element): # Create a basic endpoint object...
[ "Returns an iterator of endpoint objects produced by the\n filter functions." ]
Please provide a description of the function:def applyFilters(self, endpoint): for filter_function in self.filter_functions: e = filter_function(endpoint) if e is not None: # Once one of the filters has returned an # endpoint, do not apply any mor...
[ "Apply filter functions to an endpoint until one of them\n returns non-None." ]
Please provide a description of the function:def getServiceEndpoints(self, yadis_url, service_element): endpoints = [] for subfilter in self.subfilters: endpoints.extend( subfilter.getServiceEndpoints(yadis_url, service_element)) return endpoints
[ "Generate all endpoint objects for all of the subfilters of\n this filter and return their concatenation." ]
Please provide a description of the function:def randomString(length, chrs=None): if chrs is None: return getBytes(length) else: n = len(chrs) return ''.join([chrs[randrange(n)] for _ in xrange(length)])
[ "Produce a string of length random bytes, chosen from chrs." ]
Please provide a description of the function:def _hasher_first_run(self, preimage): ''' Invoke the backend on-demand, and check an expected hash result, then replace this first run with the new hasher method. This is a bit of a hacky way to minimize overhead on hash calls after this firs...
[]
Please provide a description of the function:def dirname(path: Optional[str]) -> Optional[str]: if path is not None: return os.path.dirname(path)
[ " Returns the directory component of a pathname and None if the argument is None " ]
Please provide a description of the function:def basename(path: Optional[str]) -> Optional[str]: if path is not None: return os.path.basename(path)
[ " Returns the final component of a pathname and None if the argument is None " ]
Please provide a description of the function:def normpath(path: Optional[str]) -> Optional[str]: if path is not None: return os.path.normpath(path)
[ " Normalizes the path, returns None if the argument is None " ]
Please provide a description of the function:def join_paths(path1: Optional[str], path2: Optional[str]) -> Optional[str]: if path1 is not None and path2 is not None: return os.path.join(path1, path2)
[ " Joins two paths if neither of them is None " ]
Please provide a description of the function:def _run(self, name, *args, **kwargs): stdout = six.b('') cmd = getattr(self.git, name) # Ask cmd(...) to return a (status, stdout, stderr) tuple kwargs['with_extended_output'] = True # Execute command t...
[ " Run a git command specified by name and args/kwargs. " ]
Please provide a description of the function:def stasher(self): # nonlocal for python2 stashed = [False] clean = [False] def stash(): if clean[0] or not self.repo.is_dirty(submodules=False): clean[0] = True return ...
[ "\r\n A stashing contextmanager.\r\n " ]
Please provide a description of the function:def checkout(self, branch_name): try: find( self.repo.branches, lambda b: b.name == branch_name ).checkout() except OrigCheckoutError as e: raise CheckoutError(branch_name, details=e)
[ " Checkout a branch by name. " ]
Please provide a description of the function:def rebase(self, target_branch): current_branch = self.repo.active_branch arguments = ( ([self.config('git-up.rebase.arguments')] or []) + [target_branch.name] ) try: self._run('re...
[ " Rebase to target branch. " ]
Please provide a description of the function:def push(self, *args, **kwargs): ''' Push commits to remote ''' stdout = six.b('') # Execute command cmd = self.git.push(as_process=True, *args, **kwargs) # Capture output while True: output = cmd.stdout....
[]
Please provide a description of the function:def change_count(self): status = self.git.status(porcelain=True, untracked_files='no').strip() if not status: return 0 else: return len(status.split('\n'))
[ " The number of changes in the working directory. " ]
Please provide a description of the function:def uniq(seq): seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
[ " Return a copy of seq without duplicates. " ]
Please provide a description of the function:def execute(cmd, cwd=None): try: lines = subprocess \ .check_output(cmd, cwd=cwd, stderr=DEVNULL) \ .splitlines() except subprocess.CalledProcessError: return None else: if lines: return d...
[ " Execute a command and return it's output. " ]
Please provide a description of the function:def decode(s): if isinstance(s, bytes): return s.decode(sys.getdefaultencoding()) else: return s
[ "\r\n Decode a string using the system encoding if needed (ie byte strings)\r\n " ]
Please provide a description of the function:def current_version(): # Monkeypatch setuptools.setup so we get the verison number import setuptools version = [None] def monkey_setup(**settings): version[0] = settings['version'] old_setup = setuptools.setup setuptools.setup = monkey...
[ "\n Get the current version number from setup.py\n " ]
Please provide a description of the function:def run(version, quiet, no_fetch, push, **kwargs): # pragma: no cover if version: if NO_DISTRIBUTE: print(colored('Please install \'git-up\' via pip in order to ' 'get version information.', 'yellow')) els...
[ "\r\n A nicer `git pull`.\r\n " ]
Please provide a description of the function:def run(self): try: if self.should_fetch: self.fetch() self.rebase_all_branches() if self.with_bundler(): self.check_bundler() if self.settings['push.auto']: ...
[ " Run all the git-up stuff. " ]
Please provide a description of the function:def rebase_all_branches(self): col_width = max(len(b.name) for b in self.branches) + 1 if self.repo.head.is_detached: raise GitError("You're not currently on a branch. I'm exiting" " in case you're in the m...
[ " Rebase all branches, if possible. " ]
Please provide a description of the function:def fetch(self): fetch_kwargs = {'multiple': True} fetch_args = [] if self.is_prune(): fetch_kwargs['prune'] = True if self.settings['fetch.all']: fetch_kwargs['all'] = True else: ...
[ "\r\n Fetch the recent refs from the remotes.\r\n\r\n Unless git-up.fetch.all is set to true, all remotes with\r\n locally existent branches will be fetched.\r\n " ]
Please provide a description of the function:def push(self): print('pushing...') push_kwargs = {} push_args = [] if self.settings['push.tags']: push_kwargs['push'] = True if self.settings['push.all']: push_kwargs['all'] = True ...
[ "\r\n Push the changes back to the remote(s) after fetching\r\n " ]
Please provide a description of the function:def log(self, branch, remote): log_hook = self.settings['rebase.log-hook'] if log_hook: if ON_WINDOWS: # pragma: no cover # Running a string in CMD from Python is not that easy on # Windows. Runnin...
[ " Call a log-command, if set by git-up.fetch.all. " ]
Please provide a description of the function:def version_info(self): # Retrive and show local version info package = pkg.get_distribution('git-up') local_version_str = package.version local_version = package.parsed_version print('GitUp version is: ' + colored('...
[ " Tell, what version we're running at and if it's up to date. " ]
Please provide a description of the function:def load_config(self): for key in self.settings: value = self.config(key) # Parse true/false if value == '' or value is None: continue # Not set by user, go on if value.lower() == 'true'...
[ "\r\n Load the configuration from git config.\r\n " ]
Please provide a description of the function:def is_prune(self): required_version = "1.6.6" config_value = self.settings['fetch.prune'] if self.git.is_version_min(required_version): return config_value is not False else: # pragma: no cover if co...
[ "\r\n Return True, if `git fetch --prune` is allowed.\r\n\r\n Because of possible incompatibilities, this requires special\r\n treatment.\r\n " ]
Please provide a description of the function:def with_bundler(self): def gemfile_exists(): return os.path.exists('Gemfile') if 'GIT_UP_BUNDLER_CHECK' in os.environ: print(colored( '''The GIT_UP_BUNDLER_CHECK environment variable is...
[ "\r\n Check, if bundler check is requested.\r\n\r\n Check, if the user wants us to check for new gems and return True in\r\n this case.\r\n :rtype : bool\r\n ", "\r\n Check, if a Gemfile exists in the current repo.\r\n " ]
Please provide a description of the function:def check_bundler(self): def get_config(name): return name if self.config('bundler.' + name) else '' from pkg_resources import Requirement, resource_filename relative_path = os.path.join('PyGitUp', 'check-bundler.rb') ...
[ "\r\n Run the bundler check.\r\n " ]
Please provide a description of the function:def print_error(self, error): print(colored(error.message, 'red'), file=self.stderr) if error.stdout or error.stderr: print(file=self.stderr) print("Here's what git said:", file=self.stderr) print(file=self...
[ "\r\n Print more information about an error.\r\n\r\n :type error: GitError\r\n " ]
Please provide a description of the function:def opendocx(file): '''Open a docx file, return a document XML tree''' mydoc = zipfile.ZipFile(file) xmlcontent = mydoc.read('word/document.xml') document = etree.fromstring(xmlcontent) return document
[]
Please provide a description of the function:def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None, attrnsprefix=None): '''Create an element & return it''' # Deal with list of nsprefix by making namespacemap namespacemap = None if isinstance(nsprefix, list): namesp...
[]
Please provide a description of the function:def pagebreak(type='page', orient='portrait'): '''Insert a break, default 'page'. See http://openxmldeveloper.org/forums/thread/4075.aspx Return our page break element.''' # Need to enumerate different types of page breaks. validtypes = ['page', 'section'...
[]
Please provide a description of the function:def paragraph(paratext, style='BodyText', breakbefore=False, jc='left'): # Make our elements paragraph = makeelement('p') if not isinstance(paratext, list): paratext = [(paratext, '')] text_tuples = [] for pt in paratext: text, char_...
[ "\n Return a new paragraph element containing *paratext*. The paragraph's\n default style is 'Body Text', but a new style may be set using the\n *style* parameter.\n\n @param string jc: Paragraph alignment, possible values:\n left, center, right, both (justified), ...\n ...
Please provide a description of the function:def heading(headingtext, headinglevel, lang='en'): '''Make a new heading, return the heading element''' lmap = {'en': 'Heading', 'it': 'Titolo'} # Make our elements paragraph = makeelement('p') pr = makeelement('pPr') pStyle = makeelement( 'pS...
[]
Please provide a description of the function:def table(contents, heading=True, colw=None, cwunit='dxa', tblw=0, twunit='auto', borders={}, celstyle=None): table = makeelement('tbl') columns = len(contents[0]) # Table properties tableprops = makeelement('tblPr') tablestyle = makeelemen...
[ "\n Return a table element based on specified parameters\n\n @param list contents: A list of lists describing contents. Every item in\n the list can be a string or a valid XML element\n itself. It can also be a list. In that case all the\n ...
Please provide a description of the function:def picture( relationshiplist, picname, picdescription, pixelwidth=None, pixelheight=None, nochangeaspect=True, nochangearrowheads=True, imagefiledict=None): if imagefiledict is None: warn( 'Using picture() without imagefi...
[ "\n Take a relationshiplist, picture file name, and return a paragraph\n containing the image and an updated relationshiplist\n " ]
Please provide a description of the function:def search(document, search): '''Search a document for a regex, return success / fail result''' result = False searchre = re.compile(search) for element in document.iter(): if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements ...
[]
Please provide a description of the function:def replace(document, search, replace): newdocument = document searchre = re.compile(search) for element in newdocument.iter(): if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements if element.text: if searchre...
[ "\n Replace all occurences of string with a different string, return updated\n document\n " ]
Please provide a description of the function:def clean(document): newdocument = document # Clean empty text and r tags for t in ('t', 'r'): rmlist = [] for element in newdocument.iter(): if element.tag == '{%s}%s' % (nsprefixes['w'], t): if not element.text...
[ " Perform misc cleaning operations on documents.\n Returns cleaned document.\n " ]
Please provide a description of the function:def findTypeParent(element, tag): p = element while True: p = p.getparent() if p.tag == tag: return p # Not found return None
[ " Finds fist parent of element of the given type\n\n @param object element: etree element\n @param string the tag parent to search for\n\n @return object element: the found parent or None when not found\n " ]
Please provide a description of the function:def AdvSearch(document, search, bs=3): '''Return set of all regex matches This is an advanced version of python-docx.search() that takes into account blocks of <bs> elements at a time. What it does: It searches the entire document body for text blocks. ...
[]
Please provide a description of the function:def advReplace(document, search, replace, bs=3): # Enables debug output DEBUG = False newdocument = document # Compile the search regexp searchre = re.compile(search) # Will match against searchels. Searchels is a list that contains last #...
[ "\n Replace all occurences of string with a different string, return updated\n document\n\n This is a modified version of python-docx.replace() that takes into\n account blocks of <bs> elements at a time. The replace element can also\n be a string or an xml etree element.\n\n What it does:\n It...
Please provide a description of the function:def getdocumenttext(document): '''Return the raw text of a document, as a list of paragraphs.''' paratextlist = [] # Compile a list of all paragraph (p) elements paralist = [] for element in document.iter(): # Find p (paragraph) elements i...
[]
Please provide a description of the function:def coreproperties(title, subject, creator, keywords, lastmodifiedby=None): coreprops = makeelement('coreProperties', nsprefix='cp') coreprops.append(makeelement('title', tagtext=title, nsprefix='dc')) coreprops.append(makeelement('subject', tagtext=subject,...
[ "\n Create core properties (common document properties referred to in the\n 'Dublin Core' specification). See appproperties() for other stuff.\n " ]
Please provide a description of the function:def appproperties(): appprops = makeelement('Properties', nsprefix='ep') appprops = etree.fromstring( '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Properties x' 'mlns="http://schemas.openxmlformats.org/officeDocument/2006/extended' ...
[ "\n Create app-specific properties. See docproperties() for more common\n document properties.\n\n " ]
Please provide a description of the function:def websettings(): '''Generate websettings''' web = makeelement('webSettings') web.append(makeelement('allowPNG')) web.append(makeelement('doNotSaveAsSingleFile')) return web
[]
Please provide a description of the function:def wordrelationships(relationshiplist): '''Generate a Word relationships file''' # Default list of relationships # FIXME: using string hack instead of making element #relationships = makeelement('Relationships', nsprefix='pr') relationships = etree.froms...
[]
Please provide a description of the function:def savedocx( document, coreprops, appprops, contenttypes, websettings, wordrelationships, output, imagefiledict=None): if imagefiledict is None: warn( 'Using savedocx() without imagefiledict parameter will be deprec' ...
[ "\n Save a modified document\n " ]
Please provide a description of the function:def set_json_converters(encode, decode): ret = _LCB._modify_helpers(json_encode=encode, json_decode=decode) return (ret['json_encode'], ret['json_decode'])
[ "\n Modify the default JSON conversion functions. This affects all\n :class:`~couchbase.bucket.Bucket` instances.\n\n These functions will called instead of the default ones (``json.dumps``\n and ``json.loads``) to encode and decode JSON (when :const:`FMT_JSON` is\n used).\n\n :param callable enco...
Please provide a description of the function:def set_pickle_converters(encode, decode): ret = _LCB._modify_helpers(pickle_encode=encode, pickle_decode=decode) return (ret['pickle_encode'], ret['pickle_decode'])
[ "\n Modify the default Pickle conversion functions. This affects all\n :class:`~couchbase.bucket.Bucket` instances.\n\n These functions will be called instead of the default ones\n (``pickle.dumps`` and ``pickle.loads``) to encode and decode values to and\n from the Pickle format (when :const:`FMT_PI...
Please provide a description of the function:def _depr(fn, usage, stacklevel=3): warn('{0} is deprecated. Use {1} instead'.format(fn, usage), stacklevel=stacklevel, category=DeprecationWarning)
[ "Internal convenience function for deprecation warnings" ]
Please provide a description of the function:def upsert(self, key, value, cas=0, ttl=0, format=None, persist_to=0, replicate_to=0): return _Base.upsert(self, key, value, cas=cas, ttl=ttl, format=format, persist_to=persist_to, replic...
[ "Unconditionally store the object in Couchbase.\n\n :param key:\n The key to set the value with. By default, the key must be\n either a :class:`bytes` or :class:`str` object encodable as\n UTF-8. If a custom `transcoder` class is used (see\n :meth:`~__init__`), the...
Please provide a description of the function:def insert(self, key, value, ttl=0, format=None, persist_to=0, replicate_to=0): return _Base.insert(self, key, value, ttl=ttl, format=format, persist_to=persist_to, replicate_to=replicate_to)
[ "Store an object in Couchbase unless it already exists.\n\n Follows the same conventions as :meth:`upsert` but the value is\n stored only if it does not exist already. Conversely, the value\n is not stored if the key already exists.\n\n Notably missing from this method is the `cas` param...
Please provide a description of the function:def prepend(self, key, value, cas=0, format=None, persist_to=0, replicate_to=0): return _Base.prepend(self, key, value, cas=cas, format=format, persist_to=persist_to, replicate_to=replicate_to)
[ "Prepend a string to an existing value in Couchbase.\n\n .. seealso:: :meth:`append`, :meth:`prepend_multi`\n " ]
Please provide a description of the function:def get(self, key, ttl=0, quiet=None, replica=False, no_format=False): return _Base.get(self, key, ttl=ttl, quiet=quiet, replica=replica, no_format=no_format)
[ "Obtain an object stored in Couchbase by given key.\n\n :param string key: The key to fetch. The type of key is the same\n as mentioned in :meth:`upsert`\n\n :param int ttl: If specified, indicates that the key's expiration\n time should be *modified* when retrieving the value.\n...
Please provide a description of the function:def touch(self, key, ttl=0): return _Base.touch(self, key, ttl=ttl)
[ "Update a key's expiration time\n\n :param string key: The key whose expiration time should be\n modified\n :param int ttl: The new expiration time. If the expiration time\n is `0` then the key never expires (and any existing\n expiration is removed)\n :return: ...
Please provide a description of the function:def lock(self, key, ttl=0): return _Base.lock(self, key, ttl=ttl)
[ "Lock and retrieve a key-value entry in Couchbase.\n\n :param key: A string which is the key to lock.\n\n :param ttl: a TTL for which the lock should be valid.\n While the lock is active, attempts to access the key (via\n other :meth:`lock`, :meth:`upsert` or other mutation calls...