code
stringlengths
1
18.2k
def __launchThreads(self, numThreads): """Launch some threads and start to process users. :param numThreads: number of thrads to launch. :type numThreads: int. """ i = 0 while i < numThreads: self.__logger.debug("Launching thread number " + str(i)) i += 1 newThr = Thread(target=self.__processUsers) newThr.setDaemon(Tru...
def __readAPI(self, url): """Read a petition to the GitHub API (private). :param url: URL to query. :type url: str. :return: the response of the API -a dictionary with these fields-: * total_count (int): number of total users that match with the search * incomplete_results (bool): https://developer.github.com/v3/search...
if reset < 0: log_message = "Error when reading response. Wait: 30 secs" sleep_duration = 30 else: utcAux = datetime.datetime.utcnow() utcAux = utcAux.utctimetuple() now_sec = timegm(utcAux) sleep_duration = reset - now_sec log_message = "Limit of API. Wait: " log_message += str(sleep_duration) log_message += " secs" s...
def __getURL(self, page=1, start_date=None, final_date=None, order="asc"): """Get the API's URL to query to get data about users. :param page: number of the page. :param start_date: start date of the range to search users (Y-m-d). "param final_date: final date of the range to search users (Y-m-d). :param order: order o...
+ ".." + final_date + \ "&sort=joined&order=" + order + \ "&per_page=100&page=" + str(page) return url
def mentions(self): """ Returns mentions :return: list of mentions :rtype: list """ if self._mentions is None: self._mentions = [] for mention_element in self._element.xpath('mention'): this_mention = Mention(self, mention_element) self._mentions.append(this_mention) if this_mention.representative: self._representative...
def sentence(self): """ The sentence related to this mention :getter: returns the sentence this mention relates to :type: corenlp_xml.document.Sentence """ if self._sentence is None: sentences = self._element.xpath('sentence/text()') if len(sentences) > 0: self._sentence = self._coref.document.get_sentence_by_id(int(se...
def head(self): """ The token serving as the "head" of the mention :getter: the token corresponding to the head :type: corenlp_xml.document.Token """ if self._head is None: self._head = self.sentence.tokens[self._head_id-1] return self._head
def enbase64(byte_str): """ Encode bytes/strings to base64. Args: - ``byte_str``: The string or bytes to base64 encode. Returns: - byte_str encoded as base64. """ # Python 3: base64.b64encode() expects type byte if isinstance(byte_str, str) and not PYTHON2: byte_str = bytes(byte_str, 'utf-8') return base64.b64encode(by...
def debase64(byte_str): """ Decode base64 encoded bytes/strings. Args: - ``byte_str``: The string or bytes to base64 encode. Returns: - decoded string as type str for python2 and type byte for python3. """ # Python 3: base64.b64decode() expects type byte if isinstance(byte_str, str) and not PYTHON2: byte_str = bytes(by...
def generate_password_hash(password, salt, N=1 << 14, r=8, p=1, buflen=64): """ Generate password hash givin the password string and salt. Args: - ``password``: Password string. - ``salt`` : Random base64 encoded string. Optional args: - ``N`` : the CPU cost, must be a power of 2 greater than 1, defaults to 1 << 14. - ...
= scrypt_hash(password, salt, N, r, p, buflen) return enbase64(pw_hash)
def check_password_hash(password, password_hash, salt, N=1 << 14, r=8, p=1, buflen=64): """ Given a password, hash, salt this function verifies the password is equal to hash/salt. Args: - ``password``: The password to perform check on. Returns: - ``bool`` """ candidate_hash = generate_password_hash(password, salt, N, r...
def write_moc_ascii(moc, filename=None, file=None): """Write a MOC to an ASCII file. Either a filename, or an open file object can be specified. """ orders = [] for (order, cells) in moc: ranges = [] rmin = rmax = None for cell in sorted(cells): if rmin is None: rmin = rmax = cell elif rmax == cell - 1: rmax = cell els...
def read_moc_ascii(moc, filename=None, file=None): """Read from an ASCII file into a MOC. Either a filename, or an open file object can be specified. """ if file is not None: orders = _read_ascii(file) else: with open(filename, 'r') as f: orders = _read_ascii(f) for text in orders: if not text: continue cells = [] (ord...
def index(): """ Base testsuite view. """ # setup_env() logs = Table('log', metadata, autoload=True) criticals = logs.select().where(logs.c.log_level == 50).order_by( 'siteconfig', 'date_created') criticals_count = logs.count(logs.c.log_level == 50) errors = logs.select().where(logs.c.log_level == 40).order_by( 'siteco...
def emit(self, record): """ Handle the logging call. """ if bool(self.store_only): do_not_store = True for extra in self.store_only: if bool(getattr(record, extra, None)): do_not_store = False break if do_not_store: return self.db = sqlite3.connect(self.filename) self.db.execute( """ INSERT INTO log( log_level, log_lev...
def timezone(self, value): """Set the timezone.""" self._timezone = (value if isinstance(value, datetime.tzinfo) else tz.gettz(value))
def recursive_iterator(func): """Decorates a function by optimizing it for iterator recursion. Requires function arguments to be pickleable.""" tee_store = {} @_coconut.functools.wraps(func) def recursive_iterator_func(*args, **kwargs): hashable_args_kwargs = _coconut.pickle.dumps((args, kwargs), _coconut.pickle.HIGHES...
def addpattern(base_func): """Decorator to add a new case to a pattern-matching function, where the new case is checked last.""" def pattern_adder(func): @_coconut.functools.wraps(func) @_coconut_tco def add_pattern_func(*args, **kwargs): try: return base_func(*args, **kwargs) except _coconut_MatchError: raise _coconut...
def fmap(func, obj): """Creates a copy of obj with func applied to its contents.""" if _coconut.hasattr(obj, "__fmap__"): return obj.__fmap__(func) args = _coconut_map(func, obj) if _coconut.isinstance(obj, _coconut.dict): args = _coconut_zip(args, obj.values()) if _coconut.isinstance(obj, _coconut.tuple) and _coconut....
def index(self, elem): """Find the index of elem in the reversed iterator.""" return _coconut.len(self._iter) - self._iter.index(elem) - 1
def index(self, elem): """Find the index of elem in the count.""" if elem not in self: raise _coconut.ValueError(_coconut.repr(elem) + " is not in count") return (elem - self._start) // self._step
def normalize_uri_path_component(path_component): """ normalize_uri_path_component(path_component) -> str Normalize the path component according to RFC 3986. This performs the following operations: * Alpha, digit, and the symbols '-', '.', '_', and '~' (unreserved characters) are left alone. * Characters outside this r...
0x25, 37 if i + 2 >= len(path_component): result.write(b"%25") i += 1 continue try: value = int(path_component[i+1:i+3], 16) except ValueError: raise ValueError("Invalid %% encoding at position %d" % i) if value in _rfc3986_unreserved: result.write(int2byte(value)) else: result.write(b"%%%02X" % value) i += 3 elif c ==...
def get_canonical_uri_path(uri_path): """ get_canonical_uri_path(uri_path) -> str Normalizes the specified URI path component, removing redundant slashes and relative path components. A ValueError exception is raised if: * The URI path is not empty and not absolute (does not start with '/'). * A parent relative path el...
while i < len(components): # Fix % encodings. component = normalize_uri_path_component(components[i]) components[i] = component if components[i] == ".": # Relative current directory. Remove this. del components[i] # Don't increment i; with the deletion, we're now pointing to # the next element in the path. elif compone...
def normalize_query_parameters(query_string): """ normalize_query_parameters(query_string) -> dict Converts a query string into a dictionary mapping parameter names to a list of the sorted values. This ensurses that the query string follows % encoding rules according to RFC 3986 and checks for duplicate keys. A ValueEr...
def canonical_uri_path(self): """ The canonicalized URI path from the request. """ result = getattr(self, "_canonical_uri_path", None) if result is None: result = self._canonical_uri_path = get_canonical_uri_path( self.uri_path) return result
def query_parameters(self): """ A key to list of values mapping of the query parameters seen in the request. """ result = getattr(self, "_query_parameters", None) if result is None: result = self._query_parameters = normalize_query_parameters( self.query_string) return result
def canonical_query_string(self): """ The canonical query string from the query parameters. This takes the query string from the request and orders the parameters in """ results = [] for key, values in iteritems(self.query_parameters): # Don't include the signature itself. if key == _x_amz_signature: continue for value...
def authorization_header_parameters(self): """ The parameters from the Authorization header (only). If the Authorization header is not present or is not an AWS SigV4 header, an AttributeError exception is raised. """ result = getattr(self, "_authorization_header_parameters", None) if result is None: auth = self.headers...
def signed_headers(self): """ An ordered dictionary containing the signed header names and values. """ # See if the signed headers are listed in the query string signed_headers = self.query_parameters.get(_x_amz_signedheaders) if signed_headers is not None: signed_headers = url_unquote(signed_headers[0]) else: # Get th...
def request_timestamp(self): """ The timestamp of the request in ISO8601 YYYYMMDD'T'HHMMSS'Z' format. If this is not available in the query parameters or headers, or the value is not a valid format for AWS SigV4, an AttributeError exception is raised. """ amz_date = self.query_parameters.get(_x_amz_date) if amz_date is...
% amz_date) return amz_date
def access_key(self): """ The access key id used to sign the request. If the access key is not in the same credential scope as this request, an AttributeError exception is raised. """ credential = self.query_parameters.get(_x_amz_credential) if credential is not None: credential = url_unquote(credential[0]) else: crede...
def request_signature(self): """ The signature passed in the request. """ signature = self.query_parameters.get(_x_amz_signature) if signature is not None: signature = signature[0] else: signature = self.authorization_header_parameters.get(_signature) if signature is None: raise AttributeError("Signature was not passed...
def canonical_request(self): """ The AWS SigV4 canonical request given parameters from an HTTP request. This process is outlined here: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html The canonical request is: request_method + '\n' + canonical_uri_path + '\n' + canonical_query_string + '...
def string_to_sign(self): """ The AWS SigV4 string being signed. """ return (AWS4_HMAC_SHA256 + "\n" + self.request_timestamp + "\n" + self.credential_scope + "\n" + sha256(self.canonical_request.encode("utf-8")).hexdigest())
def expected_signature(self): """ The AWS SigV4 signature expected from the request. """ k_secret = b"AWS4" + self.key_mapping[self.access_key].encode("utf-8") k_date = hmac.new(k_secret, self.request_date.encode("utf-8"), sha256).digest() k_region = hmac.new(k_date, self.region.encode("utf-8"), sha256).digest() k_serv...
def verify(self): """ Verifies that the request timestamp is not beyond our allowable timestamp mismatch and that the request signature matches our expectations. """ try: if self.timestamp_mismatch is not None: m = _iso8601_timestamp_regex.match(self.request_timestamp) year = int(m.group("year")) month = int(m.group("m...
def getTauLeibniz(n): """Returns a list containing first n digits of Pi """ myTau = tauGenLeibniz() result = [] if n > 0: result += [next(myTau) for i in range(n)] myTau.close() return result
def moothedata(data, key=None): """Return an amusing picture containing an item from a dict. Parameters ---------- data: mapping A mapping, such as a raster dataset's ``meta`` or ``profile`` property. key: A key of the ``data`` mapping. """ if not key: key = choice(list(data.keys())) logger.debug("Using randomly chosen...
def resource_collection_response(cls, offset=0, limit=20): """ This method is deprecated for version 1.1.0. Please use get_collection """ request_args = {'page[offset]': offset, 'page[limit]': limit} return cls.get_collection(request_args)
def get_collection(cls, request_args): r""" Used to fetch a collection of resource object of type 'cls' in response to a GET request\ . get_resource_or_collection should only be invoked on a resource when the client specifies a GET request. :param request_args: The query parameters supplied with the request. currently ...
= "{class_link}?page[offset]={offset}&page[limit]={limit}".format( class_link=cls.get_class_link(), offset=0, limit=limit ) if int(offset) - int(limit) > 0: data['links']['prev'] = "{class_link}?page[offset]={offset}&page[limit]={limit}".format( class_link=cls.get_class_link(), offset=int(offset)-int(limit), limit=limi...
def get_resource(cls, request_args, id): r""" Used to fetch a single resource object with the given id in response to a GET request.\ get_resource should only be invoked on a resource when the client specifies a GET request. :param request_args: :return: The query parameters supplied with the request. currently support...
def get_resource_or_collection(cls, request_args, id=None): r""" Deprecated for version 1.1.0. Please use get_resource or get_collection. This function has multiple behaviors. With id specified: Used to fetch a single resource object with the given id in response to a GET request.\ get_resource_or_collection should onl...
in the database. The id field must be set in the model -- it \ is not the same as the node id. If the id is not supplied the full collection will be returned. :return: An HTTP response object in accordance with the specification at \ http://jsonapi.org/format/#fetching-resources """ if id: try: r = cls.get_resource(req...
def create_resource(cls, request_json): r""" Used to create a node in the database of type 'cls' in response to a POST request. create_resource should only \ be invoked on a resource when the client specifies a POST request. :param request_json: a dictionary formatted according to the specification at \ http://jsonapi....
key, attributes[key]) else: raise EnumeratedTypeError else: setattr(new_resource, key, attributes[key]) new_resource.save() for r in new_resource.hashed: unhashed = getattr(new_resource, r) if unhashed: setattr(new_resource, r, hashlib.sha256(unhashed).hexdigest()) new_resource.save() relationships = data.get('relation...
= status_code except UniqueProperty: r = application_codes.error_response([application_codes.UNIQUE_KEY_VIOLATION]) try: new_resource.delete() except: pass except DoesNotExist: r = application_codes.error_response([application_codes.RESOURCE_NOT_FOUND]) try: new_resource.delete() except: pass except WrongTypeError as e...
def deactivate_resource(cls, id): r""" Used to deactivate a node of type 'cls' in response to a DELETE request. deactivate_resource should only \ be invoked on a resource when the client specifies a DELETE request. :param id: The 'id' field of the node to update in the database. The id field must be set in the model --...
def get_relationship(cls, request_args, id, related_collection_name, related_resource=None): """ Get a relationship :param request_args: :param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \ be set in the model -- it is not the same as the node id :param related...
def create_relationships(cls, id, related_collection_name, request_json): r""" Used to create relationship(s) between the id node and the nodes identified in the included resource \ identifier objects. :param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \ be set...
cls.get_class_from_type(rsrc_identifier['type']).nodes.get(id=rsrc_identifier['id']) rel_attrs = rsrc_identifier.get('meta') if not rel_attrs or isinstance(rel_attrs, dict): related_collection.connect(the_new_node, rel_attrs) else: raise WrongTypeError #r = this_resource.relationship_collection_response(related_collect...
def disconnect_relationship(cls, id, related_collection_name, request_json): """ Disconnect one or more relationship in a collection with cardinality 'Many'. :param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \ be set in the model -- it is not the same as the n...
r = application_codes.error_response([application_codes.BAD_FORMAT_VIOLATION]) return r
def delete_relationship(cls, id, related_collection_name, related_resource=None): """ Deprecated for version 1.1.0. Please use update_relationship """ try: this_resource = cls.nodes.get(id=id, active=True) if not related_resource: r = this_resource.delete_relationship_collection(related_collection_name) else: r = this_...
def update_relationship(cls, id, related_collection_name, request_json): r""" Used to completely replace all the existing relationships with new ones. :param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \ be set in the model -- it is not the same as the node id ...
connected resource else: the_new_node = cls.get_class_from_type(data['type']).nodes.get(id=data['id']) if related_collection.single(): # update the relationship related_collection.reconnect(related_collection.single(), the_new_node) the_rel = eval('related_collection.relationship(the_new_node)'.format( start_node=this_...
def get_stop_words(self, language, fail_safe=False): """ Returns a StopWord object initialized with the stop words collection requested by ``language``. If the requested language is not available a StopWordError is raised. If ``fail_safe`` is set to True, an empty StopWord object is returned. """ try: language = self.l...
def _get_stop_words(self, language): """ Internal method for getting the stop words collections and raising errors. """ if language not in self.available_languages: raise StopWordError( 'Stop words are not available in "%s".\n' 'If possible do a pull request at : ' 'https://github.com/Fantomas42/mots-vides' % language)...
def available_languages(self): """ Returns a list of languages providing collection of stop words. """ available_languages = getattr(self, '_available_languages', None) if available_languages: return available_languages try: languages = os.listdir(self.data_directory) except OSError: raise StopWordError( "'datas' direc...
def get_collection_filename(self, language): """ Returns the filename containing the stop words collection for a specific language. """ filename = os.path.join(self.data_directory, '%s.txt' % language) return filename
def read_collection(self, filename): """ Reads and returns a collection of stop words into a file. """ with open(filename, 'rb') as fd: lines = fd.read().decode('utf-8-sig').splitlines() collection = list(filter(bool, [line.strip() for line in lines])) return collection
def write_collection(self, filename, collection): """ Writes a collection of stop words into a file. """ collection = sorted(list(collection)) with open(filename, 'wb+') as fd: fd.truncate() fd.write('\n'.join(collection).encode('utf-8'))
def startproject_command(context, basedir, sourcedir, targetdir, backend, config): """ Create a new Sass project This will prompt you to define your project configuration in a settings file then create needed directory structure. Arguments 'basedir', 'config', 'sourcedir', 'targetdir' can not be empty. 'backend' argume...
e: logger.critical(six.text_type(e)) raise click.Abort() else: logger.info(u"Project directory structure and configuration file have " "been created.") logger.info(u"Now you should start to create some Sass sources into " "'{}', then compile them " "using:".format(results['sourcedir'])) logger.info(u" boussole compile ...
def list_example(): """ Example list pagination. """ from uuid import uuid4 from redis import StrictRedis from zato.redis_paginator import ListPaginator conn = StrictRedis() key = 'paginator:{}'.format(uuid4().hex) for x in range(1, 18): conn.rpush(key, x) p = ListPaginator(conn, key, 6) print(p.count) # 17 print(p.num...
def zset_example(): """ Example sorted set pagination. """ from uuid import uuid4 from redis import StrictRedis from zato.redis_paginator import ZSetPaginator conn = StrictRedis() key = 'paginator:{}'.format(uuid4().hex) # 97-114 is 'a' to 'r' in ASCII for x in range(1, 18): conn.zadd(key, x, chr(96 + x)) p = ZSetPagin...
def load(cls, graph, element): """ Instantiates the node in the graph if it's not already stored in the graph :param graph: The dependency graph this node is a member of :type graph: corenlp_xml.dependencies.DependencyGraph :param element: The lxml element wrapping the node :type element: lxml.ElementBase """ node = gr...
def governor(self, dep_type, node): """ Registers a node as governing this node :param dep_type: The dependency type :type dep_type: str :param node: :return: self, provides fluent interface :rtype: corenlp_xml.dependencies.DependencyNode """ self._governors[dep_type] = self._governors.get(dep_type, []) + [node] return...
def dependent(self, dep_type, node): """ Registers a node as dependent on this node :param dep_type: The dependency type :type dep_type: str :param node: The node to be registered as a dependent :type node: corenlp_xml.dependencies.DependencyNode :return: self, provides fluent interface :rtype: corenlp_xml.dependencies...
def governor(self): """ Accesses the governor node :getter: Returns the Governor node :type: corenlp_xml.dependencies.DependencyNode """ if self._governor is None: governors = self._element.xpath('governor') if len(governors) > 0: self._governor = DependencyNode.load(self._graph, governors[0]) return self._governor
def dependent(self): """ Accesses the dependent node :getter: returns the Dependent node :type: corenlp_xml.dependencies.DependencyNode """ if self._dependent is None: dependents = self._element.xpath('dependent') if len(dependents) > 0: self._dependent = DependencyNode.load(self._graph, dependents[0]) return self._dep...
def strip_quotes(self, content): """ Unquote given rule. Args: content (str): An import rule. Raises: InvalidImportRule: Raise exception if the rule is badly quoted (not started or not ended quotes). Returns: string: The given rule unquoted. """ error_msg = "Following rule is badly quoted: {}" if (content.startswith('"...
def flatten_rules(self, declarations): """ Flatten returned import rules from regex. Because import rules can contains multiple items in the same rule (called multiline import rule), the regex ``REGEX_IMPORT_RULE`` return a list of unquoted items for each rule. Args: declarations (list): A SCSS source. Returns: list: G...
def parse(self, content): """ Parse a stylesheet document with a regex (``REGEX_IMPORT_RULE``) to extract all import rules and return them. Args: content (str): A SCSS source. Returns: list: Finded paths in import rules. """ # Remove all comments before searching for import rules, to not catch # commented breaked impor...
def naccess_available(): """True if naccess is available on the path.""" available = False try: subprocess.check_output(['naccess'], stderr=subprocess.DEVNULL) except subprocess.CalledProcessError: available = True except FileNotFoundError: print("naccess has not been found on your path. If you have already " "installe...
def run_naccess(pdb, mode, path=True, include_hetatms=False, outfile=None, path_to_ex=None): """Uses naccess to run surface accessibility calculations. Notes ----- Requires the naccess program, with a path to its executable provided in global_settings. For information on the Naccess program, see: http://www.bioinf.manc...
naccess_out : str naccess output file for given mode as a string. """ if mode not in ['asa', 'rsa', 'log']: raise ValueError( "mode {} not valid. Must be \'asa\', \'rsa\' or \'log\'" .format(mode)) if path_to_ex: naccess_exe = path_to_ex else: naccess_exe = 'naccess' if not path: if type(pdb) == str: pdb = pdb.encode()...
inf: inf.write(naccess_out) temp_dir.cleanup() return naccess_out
def extract_residue_accessibility(in_rsa, path=True, get_total=False): """Parses rsa file for solvent accessibility for each residue. Parameters ---------- in_rsa : str Path to naccess rsa file path : bool Indicates if in_rsa is a path or a string get_total : bool Indicates if the total accessibility from the file need...
"HEM"] if get_total: (all_atoms, _, _, _, _) = total_accessibility( rsa, path=False) return rel_solv_acc_all_atoms, all_atoms return rel_solv_acc_all_atoms, None
def selenium(self): """Get the instance of webdriver, it starts the browser if the webdriver is not yet instantied :return: a `selenium instance <http://selenium-python.readthedocs.org/ api.html#module-selenium.webdriver.remote.webdriver>` """ if not self._web_driver: self._web_driver = self._start_driver() return self...
def normalize(self): """ Sum the values in a Counter, then create a new Counter where each new value (while keeping the original key) is equal to the original value divided by sum of all the original values (this is sometimes referred to as the normalization constant). https://en.wikipedia.org/wiki/Normalization_(stati...
def get_weighted_random_value(self): """ This will generate a value by creating a cumulative distribution, and a random number, and selecting the value who's cumulative distribution interval contains the generated random number. For example, if there's 0.7 chance of generating the letter "a" and 0.3 chance of generatin...
def paths_by_depth(paths): """Sort list of paths by number of directories in it .. todo:: check if a final '/' is consistently given or ommitted. :param iterable paths: iterable containing paths (str) :rtype: list """ return sorted( paths, key=lambda path: path.count(os.path.sep), reverse=True )
def get_relative_from_paths(self, filepath, paths): """ Find the relative filepath from the most relevant multiple paths. This is somewhat like a ``os.path.relpath(path[, start])`` but where ``start`` is a list. The most relevant item from ``paths`` will be used to apply the relative transform. Args: filepath (str): Pa...
def is_partial(self, filepath): """ Check if file is a Sass partial source (see `Sass partials Reference`_). Args: filepath (str): A file path. Can be absolute, relative or just a filename. Returns: bool: True if file is a partial source, else False. """ path, filename = os.path.split(filepath) return filename.startswi...
def is_allowed(self, filepath, excludes=[]): """ Check from exclude patterns if a relative filepath is allowed Args: filepath (str): A relative file path. (exclude patterns are allways based from the source directory). Keyword Arguments: excludes (list): A list of excluding (glob) patterns. If filepath matchs one of pa...
def match_conditions(self, filepath, sourcedir=None, nopartial=True, exclude_patterns=[], excluded_libdirs=[]): """ Find if a filepath match all required conditions. Available conditions are (in order): * Is allowed file extension; * Is a partial source; * Is from an excluded directory; * Is matching an exclude pattern...
filepath, if filepath starts with one them, it won't match condtions. Returns: bool: ``True`` if match all conditions, else ``False``. """ # Ensure libdirs ends with / to avoid missmatching with # 'startswith' usage excluded_libdirs = [os.path.join(d, "") for d in excluded_libdirs] # Match an filename extension admitte...
def change_extension(self, filepath, new_extension): """ Change final filename extension. Args: filepath (str): A file path (relative or absolute). new_extension (str): New extension name (without leading dot) to apply. Returns: str: Filepath with new extension. """ filename, ext = os.path.splitext(filepath) return '.'...
def get_destination(self, filepath, targetdir=None): """ Return destination path from given source file path. Destination is allways a file with extension ``.css``. Args: filepath (str): A file path. The path is allways relative to sources directory. If not relative, ``targetdir`` won't be joined. absolute (bool): If g...
def compilable_sources(self, sourcedir, absolute=False, recursive=True, excludes=[]): """ Find all scss sources that should be compiled, aka all sources that are not "partials" Sass sources. Args: sourcedir (str): Directory path to scan. Keyword Arguments: absolute (bool): Returned paths will be absolute using ``source...
relative_dir = '' # Matching all conditions absolute_filepath = os.path.join(root, item) conditions = { 'sourcedir': sourcedir, 'nopartial': True, 'exclude_patterns': excludes, 'excluded_libdirs': [], } if self.match_conditions(absolute_filepath, **conditions): relative_filepath = os.path.join(relative_dir, item) if ab...
def mirror_sources(self, sourcedir, targetdir=None, recursive=True, excludes=[]): """ Mirroring compilable sources filepaths to their targets. Args: sourcedir (str): Directory path to scan. Keyword Arguments: absolute (bool): Returned paths will be absolute using ``sourcedir`` argument (if True), else return relative p...
sources: src = filepath dst = self.get_destination(src, targetdir=targetdir) # In absolute mode if targetdir: src = os.path.join(sourcedir, src) maplist.append((src, dst)) return maplist