repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
jdillard/sphinx-sitemap
sphinx_sitemap/__init__.py
setup
def setup(app): """Setup connects events to the sitemap builder""" app.add_config_value( 'site_url', default=None, rebuild=False ) try: app.add_config_value( 'html_baseurl', default=None, rebuild=False ) except: pass...
python
def setup(app): """Setup connects events to the sitemap builder""" app.add_config_value( 'site_url', default=None, rebuild=False ) try: app.add_config_value( 'html_baseurl', default=None, rebuild=False ) except: pass...
Setup connects events to the sitemap builder
https://github.com/jdillard/sphinx-sitemap/blob/2d8bf7ec6e14f5edd3be4d6b6e979aa8cf63e663/sphinx_sitemap/__init__.py#L19-L38
jdillard/sphinx-sitemap
sphinx_sitemap/__init__.py
add_html_link
def add_html_link(app, pagename, templatename, context, doctree): """As each page is built, collect page names for the sitemap""" app.sitemap_links.append(pagename + ".html")
python
def add_html_link(app, pagename, templatename, context, doctree): """As each page is built, collect page names for the sitemap""" app.sitemap_links.append(pagename + ".html")
As each page is built, collect page names for the sitemap
https://github.com/jdillard/sphinx-sitemap/blob/2d8bf7ec6e14f5edd3be4d6b6e979aa8cf63e663/sphinx_sitemap/__init__.py#L50-L52
jdillard/sphinx-sitemap
sphinx_sitemap/__init__.py
create_sitemap
def create_sitemap(app, exception): """Generates the sitemap.xml from the collected HTML page links""" site_url = app.builder.config.site_url or app.builder.config.html_baseurl if not site_url: print("sphinx-sitemap error: neither html_baseurl nor site_url " "are set in conf.py. Sitema...
python
def create_sitemap(app, exception): """Generates the sitemap.xml from the collected HTML page links""" site_url = app.builder.config.site_url or app.builder.config.html_baseurl if not site_url: print("sphinx-sitemap error: neither html_baseurl nor site_url " "are set in conf.py. Sitema...
Generates the sitemap.xml from the collected HTML page links
https://github.com/jdillard/sphinx-sitemap/blob/2d8bf7ec6e14f5edd3be4d6b6e979aa8cf63e663/sphinx_sitemap/__init__.py#L55-L102
industrial-optimization-group/DESDEO
desdeo/problem/RangeEstimators.py
estimate_payoff_table
def estimate_payoff_table( opt_meth_cls: Type[OptimizationMethod], mo_prob: MOProblem ) -> Tuple[List[float], List[float]]: """ Estimates the ideal and nadir by using a payoff table. This should give a good estimate for the ideal, but can be very inaccurate for the nadir. For an explanation of why, see ...
python
def estimate_payoff_table( opt_meth_cls: Type[OptimizationMethod], mo_prob: MOProblem ) -> Tuple[List[float], List[float]]: """ Estimates the ideal and nadir by using a payoff table. This should give a good estimate for the ideal, but can be very inaccurate for the nadir. For an explanation of why, see ...
Estimates the ideal and nadir by using a payoff table. This should give a good estimate for the ideal, but can be very inaccurate for the nadir. For an explanation of why, see [DEB2010]_. References ---------- .. [DEB2010] Deb, K., Miettinen, K., & Chaudhuri, S. (2010). Toward an estimation of...
https://github.com/industrial-optimization-group/DESDEO/blob/c7aebe8adb20942d200b9a411d4cdec21f5f4bff/desdeo/problem/RangeEstimators.py#L16-L40
industrial-optimization-group/DESDEO
desdeo/problem/RangeEstimators.py
pad
def pad(idnad: Tuple[List[float], List[float]], pad_nadir=0.05, pad_ideal=0.0): """ Pad an ideal/nadir estimate. This is mainly useful for padding the nadir estimated by a payoff table for safety purposes. """ ideal, nadir = idnad ideal_arr = np.array(ideal) nadir_arr = np.array(nadir) i...
python
def pad(idnad: Tuple[List[float], List[float]], pad_nadir=0.05, pad_ideal=0.0): """ Pad an ideal/nadir estimate. This is mainly useful for padding the nadir estimated by a payoff table for safety purposes. """ ideal, nadir = idnad ideal_arr = np.array(ideal) nadir_arr = np.array(nadir) i...
Pad an ideal/nadir estimate. This is mainly useful for padding the nadir estimated by a payoff table for safety purposes.
https://github.com/industrial-optimization-group/DESDEO/blob/c7aebe8adb20942d200b9a411d4cdec21f5f4bff/desdeo/problem/RangeEstimators.py#L43-L54
industrial-optimization-group/DESDEO
desdeo/problem/RangeEstimators.py
round_off
def round_off(idnad: Tuple[List[float], List[float]], dp: int = 2): """ Round off an ideal/nadir estimate e.g. so that it's looks nicer when plotted. This function is careful to round so only ever move the values away from the contained range. """ ideal, nadir = idnad mult = np.power(10, dp)...
python
def round_off(idnad: Tuple[List[float], List[float]], dp: int = 2): """ Round off an ideal/nadir estimate e.g. so that it's looks nicer when plotted. This function is careful to round so only ever move the values away from the contained range. """ ideal, nadir = idnad mult = np.power(10, dp)...
Round off an ideal/nadir estimate e.g. so that it's looks nicer when plotted. This function is careful to round so only ever move the values away from the contained range.
https://github.com/industrial-optimization-group/DESDEO/blob/c7aebe8adb20942d200b9a411d4cdec21f5f4bff/desdeo/problem/RangeEstimators.py#L57-L67
industrial-optimization-group/DESDEO
desdeo/problem/RangeEstimators.py
default_estimate
def default_estimate( opt_meth: Type[OptimizationMethod], mo_prob: MOProblem, dp: int = 2 ) -> Tuple[List[float], List[float]]: """ The recommended nadir/ideal estimator - use a payoff table and then round off the result. """ return round_off(estimate_payoff_table(opt_meth, mo_prob), dp)
python
def default_estimate( opt_meth: Type[OptimizationMethod], mo_prob: MOProblem, dp: int = 2 ) -> Tuple[List[float], List[float]]: """ The recommended nadir/ideal estimator - use a payoff table and then round off the result. """ return round_off(estimate_payoff_table(opt_meth, mo_prob), dp)
The recommended nadir/ideal estimator - use a payoff table and then round off the result.
https://github.com/industrial-optimization-group/DESDEO/blob/c7aebe8adb20942d200b9a411d4cdec21f5f4bff/desdeo/problem/RangeEstimators.py#L70-L77
industrial-optimization-group/DESDEO
desdeo/optimization/OptimizationMethod.py
OptimizationMethod.search
def search(self, max=False, **params) -> Tuple[np.ndarray, List[float]]: """ Search for the optimal solution This sets up the search for the optimization and calls the _search method Parameters ---------- max : bool (default False) If true find mximum of the...
python
def search(self, max=False, **params) -> Tuple[np.ndarray, List[float]]: """ Search for the optimal solution This sets up the search for the optimization and calls the _search method Parameters ---------- max : bool (default False) If true find mximum of the...
Search for the optimal solution This sets up the search for the optimization and calls the _search method Parameters ---------- max : bool (default False) If true find mximum of the objective function instead of minimum **params : dict [optional] Parame...
https://github.com/industrial-optimization-group/DESDEO/blob/c7aebe8adb20942d200b9a411d4cdec21f5f4bff/desdeo/optimization/OptimizationMethod.py#L32-L53
industrial-optimization-group/DESDEO
desdeo/method/NAUTILUS.py
NAUTILUSv1.next_iteration
def next_iteration(self, preference=None): """ Return next iteration bounds """ if preference: self.preference = preference print(("Given preference: %s" % self.preference.pref_input)) self._update_fh() # tmpzh = list(self.zh) self._update...
python
def next_iteration(self, preference=None): """ Return next iteration bounds """ if preference: self.preference = preference print(("Given preference: %s" % self.preference.pref_input)) self._update_fh() # tmpzh = list(self.zh) self._update...
Return next iteration bounds
https://github.com/industrial-optimization-group/DESDEO/blob/c7aebe8adb20942d200b9a411d4cdec21f5f4bff/desdeo/method/NAUTILUS.py#L255-L273
industrial-optimization-group/DESDEO
desdeo/method/NAUTILUS.py
NNAUTILUS.next_iteration
def next_iteration(self, ref_point, bounds=None): """ Calculate the next iteration point to be shown to the DM Parameters ---------- ref_point : list of float Reference point given by the DM """ if bounds: self.problem.points = reachable_point...
python
def next_iteration(self, ref_point, bounds=None): """ Calculate the next iteration point to be shown to the DM Parameters ---------- ref_point : list of float Reference point given by the DM """ if bounds: self.problem.points = reachable_point...
Calculate the next iteration point to be shown to the DM Parameters ---------- ref_point : list of float Reference point given by the DM
https://github.com/industrial-optimization-group/DESDEO/blob/c7aebe8adb20942d200b9a411d4cdec21f5f4bff/desdeo/method/NAUTILUS.py#L325-L364
miso-belica/jusText
justext/__main__.py
output_default
def output_default(paragraphs, fp=sys.stdout, no_boilerplate=True): """ Outputs the paragraphs as: <tag> text of the first paragraph <tag> text of the second paragraph ... where <tag> is <p>, <h> or <b> which indicates standard paragraph, heading or boilerplate respecitvely. """ for ...
python
def output_default(paragraphs, fp=sys.stdout, no_boilerplate=True): """ Outputs the paragraphs as: <tag> text of the first paragraph <tag> text of the second paragraph ... where <tag> is <p>, <h> or <b> which indicates standard paragraph, heading or boilerplate respecitvely. """ for ...
Outputs the paragraphs as: <tag> text of the first paragraph <tag> text of the second paragraph ... where <tag> is <p>, <h> or <b> which indicates standard paragraph, heading or boilerplate respecitvely.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/__main__.py#L74-L94
miso-belica/jusText
justext/__main__.py
output_detailed
def output_detailed(paragraphs, fp=sys.stdout): """ Same as output_default, but only <p> tags are used and the following attributes are added: class, cfclass and heading. """ for paragraph in paragraphs: output = '<p class="%s" cfclass="%s" heading="%i" xpath="%s"> %s' % ( paragr...
python
def output_detailed(paragraphs, fp=sys.stdout): """ Same as output_default, but only <p> tags are used and the following attributes are added: class, cfclass and heading. """ for paragraph in paragraphs: output = '<p class="%s" cfclass="%s" heading="%i" xpath="%s"> %s' % ( paragr...
Same as output_default, but only <p> tags are used and the following attributes are added: class, cfclass and heading.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/__main__.py#L97-L110
miso-belica/jusText
justext/__main__.py
output_krdwrd
def output_krdwrd(paragraphs, fp=sys.stdout): """ Outputs the paragraphs in a KrdWrd compatible format: class<TAB>first text node class<TAB>second text node ... where class is 1, 2 or 3 which means boilerplate, undecided or good respectively. Headings are output as undecided. """ ...
python
def output_krdwrd(paragraphs, fp=sys.stdout): """ Outputs the paragraphs in a KrdWrd compatible format: class<TAB>first text node class<TAB>second text node ... where class is 1, 2 or 3 which means boilerplate, undecided or good respectively. Headings are output as undecided. """ ...
Outputs the paragraphs in a KrdWrd compatible format: class<TAB>first text node class<TAB>second text node ... where class is 1, 2 or 3 which means boilerplate, undecided or good respectively. Headings are output as undecided.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/__main__.py#L113-L133
miso-belica/jusText
justext/core.py
html_to_dom
def html_to_dom(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS): """Converts HTML to DOM.""" if isinstance(html, unicode): decoded_html = html # encode HTML for case it's XML with encoding declaration forced_encoding = encoding if encoding else default_...
python
def html_to_dom(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS): """Converts HTML to DOM.""" if isinstance(html, unicode): decoded_html = html # encode HTML for case it's XML with encoding declaration forced_encoding = encoding if encoding else default_...
Converts HTML to DOM.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L51-L68
miso-belica/jusText
justext/core.py
decode_html
def decode_html(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS): """ Converts a `html` containing an HTML page into Unicode. Tries to guess character encoding from meta tag. """ if isinstance(html, unicode): return html if encoding: return html...
python
def decode_html(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS): """ Converts a `html` containing an HTML page into Unicode. Tries to guess character encoding from meta tag. """ if isinstance(html, unicode): return html if encoding: return html...
Converts a `html` containing an HTML page into Unicode. Tries to guess character encoding from meta tag.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L71-L98
miso-belica/jusText
justext/core.py
preprocessor
def preprocessor(dom): "Removes unwanted parts of DOM." options = { "processing_instructions": False, "remove_unknown_tags": False, "safe_attrs_only": False, "page_structure": False, "annoying_tags": False, "frames": False, "meta": False, "links": ...
python
def preprocessor(dom): "Removes unwanted parts of DOM." options = { "processing_instructions": False, "remove_unknown_tags": False, "safe_attrs_only": False, "page_structure": False, "annoying_tags": False, "frames": False, "meta": False, "links": ...
Removes unwanted parts of DOM.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L101-L122
miso-belica/jusText
justext/core.py
classify_paragraphs
def classify_paragraphs(paragraphs, stoplist, length_low=LENGTH_LOW_DEFAULT, length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT, stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT, no_headings=NO_HEADINGS_DEFAULT): "Context-free paragraph class...
python
def classify_paragraphs(paragraphs, stoplist, length_low=LENGTH_LOW_DEFAULT, length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT, stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT, no_headings=NO_HEADINGS_DEFAULT): "Context-free paragraph class...
Context-free paragraph classification.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L226-L258
miso-belica/jusText
justext/core.py
get_next_neighbour
def get_next_neighbour(i, paragraphs, ignore_neargood): """ Return the class of the paragraph at the bottom end of the short/neargood paragraphs block. If ignore_neargood is True, than only 'bad' or 'good' can be returned, otherwise 'neargood' can be returned, too. """ return _get_neighbour(i, p...
python
def get_next_neighbour(i, paragraphs, ignore_neargood): """ Return the class of the paragraph at the bottom end of the short/neargood paragraphs block. If ignore_neargood is True, than only 'bad' or 'good' can be returned, otherwise 'neargood' can be returned, too. """ return _get_neighbour(i, p...
Return the class of the paragraph at the bottom end of the short/neargood paragraphs block. If ignore_neargood is True, than only 'bad' or 'good' can be returned, otherwise 'neargood' can be returned, too.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L281-L287
miso-belica/jusText
justext/core.py
revise_paragraph_classification
def revise_paragraph_classification(paragraphs, max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT): """ Context-sensitive paragraph classification. Assumes that classify_pragraphs has already been called. """ # copy classes for paragraph in paragraphs: paragraph.class_type = paragraph.cf...
python
def revise_paragraph_classification(paragraphs, max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT): """ Context-sensitive paragraph classification. Assumes that classify_pragraphs has already been called. """ # copy classes for paragraph in paragraphs: paragraph.class_type = paragraph.cf...
Context-sensitive paragraph classification. Assumes that classify_pragraphs has already been called.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L290-L356
miso-belica/jusText
justext/core.py
justext
def justext(html_text, stoplist, length_low=LENGTH_LOW_DEFAULT, length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT, stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT, max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT, no_headings=NO_HEADINGS_DEFAU...
python
def justext(html_text, stoplist, length_low=LENGTH_LOW_DEFAULT, length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT, stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT, max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT, no_headings=NO_HEADINGS_DEFAU...
Converts an HTML page into a list of classified paragraphs. Each paragraph is represented as instance of class ˙˙justext.paragraph.Paragraph˙˙.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L359-L378
miso-belica/jusText
justext/core.py
ParagraphMaker.make_paragraphs
def make_paragraphs(cls, root): """Converts DOM into paragraphs.""" handler = cls() lxml.sax.saxify(root, handler) return handler.paragraphs
python
def make_paragraphs(cls, root): """Converts DOM into paragraphs.""" handler = cls() lxml.sax.saxify(root, handler) return handler.paragraphs
Converts DOM into paragraphs.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L132-L136
miso-belica/jusText
justext/utils.py
get_stoplists
def get_stoplists(): """Returns a collection of built-in stop-lists.""" path_to_stoplists = os.path.dirname(sys.modules["justext"].__file__) path_to_stoplists = os.path.join(path_to_stoplists, "stoplists") stoplist_names = [] for filename in os.listdir(path_to_stoplists): name, extension = ...
python
def get_stoplists(): """Returns a collection of built-in stop-lists.""" path_to_stoplists = os.path.dirname(sys.modules["justext"].__file__) path_to_stoplists = os.path.join(path_to_stoplists, "stoplists") stoplist_names = [] for filename in os.listdir(path_to_stoplists): name, extension = ...
Returns a collection of built-in stop-lists.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/utils.py#L40-L51
miso-belica/jusText
justext/utils.py
get_stoplist
def get_stoplist(language): """Returns an built-in stop-list for the language as a set of words.""" file_path = os.path.join("stoplists", "%s.txt" % language) try: stopwords = pkgutil.get_data("justext", file_path) except IOError: raise ValueError( "Stoplist for language '%s'...
python
def get_stoplist(language): """Returns an built-in stop-list for the language as a set of words.""" file_path = os.path.join("stoplists", "%s.txt" % language) try: stopwords = pkgutil.get_data("justext", file_path) except IOError: raise ValueError( "Stoplist for language '%s'...
Returns an built-in stop-list for the language as a set of words.
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/utils.py#L54-L66
lyft/python-kmsauth
kmsauth/services.py
get_boto_client
def get_boto_client( client, region=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None ): """Get a boto3 client connection.""" cache_key = '{0}:{1}:{2}:{3}'.format( client, region, aw...
python
def get_boto_client( client, region=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None ): """Get a boto3 client connection.""" cache_key = '{0}:{1}:{2}:{3}'.format( client, region, aw...
Get a boto3 client connection.
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/services.py#L10-L42
lyft/python-kmsauth
kmsauth/services.py
get_boto_resource
def get_boto_resource( resource, region=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None ): """Get a boto resource connection.""" cache_key = '{0}:{1}:{2}:{3}'.format( resource, region, ...
python
def get_boto_resource( resource, region=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None ): """Get a boto resource connection.""" cache_key = '{0}:{1}:{2}:{3}'.format( resource, region, ...
Get a boto resource connection.
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/services.py#L45-L77
lyft/python-kmsauth
kmsauth/services.py
get_boto_session
def get_boto_session( region, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None ): """Get a boto3 session.""" return boto3.session.Session( region_name=region, aws_secret_access_key=aws_secret_access_key, aws_access_key_id=...
python
def get_boto_session( region, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None ): """Get a boto3 session.""" return boto3.session.Session( region_name=region, aws_secret_access_key=aws_secret_access_key, aws_access_key_id=...
Get a boto3 session.
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/services.py#L80-L92
lyft/python-kmsauth
kmsauth/__init__.py
ensure_text
def ensure_text(str_or_bytes, encoding='utf-8'): """Ensures an input is a string, decoding if it is bytes. """ if not isinstance(str_or_bytes, six.text_type): return str_or_bytes.decode(encoding) return str_or_bytes
python
def ensure_text(str_or_bytes, encoding='utf-8'): """Ensures an input is a string, decoding if it is bytes. """ if not isinstance(str_or_bytes, six.text_type): return str_or_bytes.decode(encoding) return str_or_bytes
Ensures an input is a string, decoding if it is bytes.
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/__init__.py#L20-L25
lyft/python-kmsauth
kmsauth/__init__.py
ensure_bytes
def ensure_bytes(str_or_bytes, encoding='utf-8', errors='strict'): """Ensures an input is bytes, encoding if it is a string. """ if isinstance(str_or_bytes, six.text_type): return str_or_bytes.encode(encoding, errors) return str_or_bytes
python
def ensure_bytes(str_or_bytes, encoding='utf-8', errors='strict'): """Ensures an input is bytes, encoding if it is a string. """ if isinstance(str_or_bytes, six.text_type): return str_or_bytes.encode(encoding, errors) return str_or_bytes
Ensures an input is bytes, encoding if it is a string.
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/__init__.py#L28-L33
lyft/python-kmsauth
kmsauth/__init__.py
KMSTokenValidator._get_key_alias_from_cache
def _get_key_alias_from_cache(self, key_arn): ''' Find a key's alias by looking up its key_arn in the KEY_METADATA cache. This function will only work after a key has been lookedup by its alias and is meant as a convenience function for turning an ARN that's already been looked u...
python
def _get_key_alias_from_cache(self, key_arn): ''' Find a key's alias by looking up its key_arn in the KEY_METADATA cache. This function will only work after a key has been lookedup by its alias and is meant as a convenience function for turning an ARN that's already been looked u...
Find a key's alias by looking up its key_arn in the KEY_METADATA cache. This function will only work after a key has been lookedup by its alias and is meant as a convenience function for turning an ARN that's already been looked up back into its alias.
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/__init__.py#L156-L166
lyft/python-kmsauth
kmsauth/__init__.py
KMSTokenValidator.decrypt_token
def decrypt_token(self, username, token): ''' Decrypt a token. ''' version, user_type, _from = self._parse_username(username) if (version > self.maximum_token_version or version < self.minimum_token_version): raise TokenValidationError('Unacceptable to...
python
def decrypt_token(self, username, token): ''' Decrypt a token. ''' version, user_type, _from = self._parse_username(username) if (version > self.maximum_token_version or version < self.minimum_token_version): raise TokenValidationError('Unacceptable to...
Decrypt a token.
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/__init__.py#L213-L311
lyft/python-kmsauth
kmsauth/__init__.py
KMSTokenGenerator.get_username
def get_username(self): """Get a username formatted for a specific token version.""" _from = self.auth_context['from'] if self.token_version == 1: return '{0}'.format(_from) elif self.token_version == 2: _user_type = self.auth_context['user_type'] retu...
python
def get_username(self): """Get a username formatted for a specific token version.""" _from = self.auth_context['from'] if self.token_version == 1: return '{0}'.format(_from) elif self.token_version == 2: _user_type = self.auth_context['user_type'] retu...
Get a username formatted for a specific token version.
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/__init__.py#L438-L449
lyft/python-kmsauth
kmsauth/__init__.py
KMSTokenGenerator.get_token
def get_token(self): """Get an authentication token.""" # Generate string formatted timestamps for not_before and not_after, # for the lifetime specified in minutes. now = datetime.datetime.utcnow() # Start the not_before time x minutes in the past, to avoid clock skew # ...
python
def get_token(self): """Get an authentication token.""" # Generate string formatted timestamps for not_before and not_after, # for the lifetime specified in minutes. now = datetime.datetime.utcnow() # Start the not_before time x minutes in the past, to avoid clock skew # ...
Get an authentication token.
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/__init__.py#L451-L491
stanfordnlp/python-stanford-corenlp
corenlp/main.py
dictstr
def dictstr(arg): """ Parse a key=value string as a tuple (key, value) that can be provided as an argument to dict() """ key, value = arg.split("=") if value.lower() == "true" or value.lower() == "false": value = bool(value) elif INT_RE.match(value): value = int(value) elif ...
python
def dictstr(arg): """ Parse a key=value string as a tuple (key, value) that can be provided as an argument to dict() """ key, value = arg.split("=") if value.lower() == "true" or value.lower() == "false": value = bool(value) elif INT_RE.match(value): value = int(value) elif ...
Parse a key=value string as a tuple (key, value) that can be provided as an argument to dict()
https://github.com/stanfordnlp/python-stanford-corenlp/blob/4d0aa08521e13e2a1c707f5a7ddcdaa3ec530d86/corenlp/main.py#L18-L30
stanfordnlp/python-stanford-corenlp
corenlp/client.py
regex_matches_to_indexed_words
def regex_matches_to_indexed_words(matches): """Transforms tokensregex and semgrex matches to indexed words. :param matches: unprocessed regex matches :return: flat array of indexed words """ words = [dict(v, **dict([('sentence', i)])) for i, s in enumerate(matches['sentences']) ...
python
def regex_matches_to_indexed_words(matches): """Transforms tokensregex and semgrex matches to indexed words. :param matches: unprocessed regex matches :return: flat array of indexed words """ words = [dict(v, **dict([('sentence', i)])) for i, s in enumerate(matches['sentences']) ...
Transforms tokensregex and semgrex matches to indexed words. :param matches: unprocessed regex matches :return: flat array of indexed words
https://github.com/stanfordnlp/python-stanford-corenlp/blob/4d0aa08521e13e2a1c707f5a7ddcdaa3ec530d86/corenlp/client.py#L334-L342
stanfordnlp/python-stanford-corenlp
corenlp/client.py
CoreNLPClient._request
def _request(self, buf, properties, date=None): """Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (dict) properties: properties that the server expects :param (str) date: reference date of document, used by server to set...
python
def _request(self, buf, properties, date=None): """Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (dict) properties: properties that the server expects :param (str) date: reference date of document, used by server to set...
Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (dict) properties: properties that the server expects :param (str) date: reference date of document, used by server to set docDate - expects YYYY-MM-DD :return: request resu...
https://github.com/stanfordnlp/python-stanford-corenlp/blob/4d0aa08521e13e2a1c707f5a7ddcdaa3ec530d86/corenlp/client.py#L172-L206
stanfordnlp/python-stanford-corenlp
corenlp/client.py
CoreNLPClient.annotate
def annotate(self, text, annotators=None, output_format=None, properties=None, date=None): """Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (list | string) annotators: list of annotators to use :param (str) output_forma...
python
def annotate(self, text, annotators=None, output_format=None, properties=None, date=None): """Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (list | string) annotators: list of annotators to use :param (str) output_forma...
Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (list | string) annotators: list of annotators to use :param (str) output_format: output type from server: serialized, json, text, conll, conllu, or xml :param (dict) proper...
https://github.com/stanfordnlp/python-stanford-corenlp/blob/4d0aa08521e13e2a1c707f5a7ddcdaa3ec530d86/corenlp/client.py#L208-L243
stanfordnlp/python-stanford-corenlp
corenlp/client.py
CoreNLPClient.__regex
def __regex(self, path, text, pattern, filter, annotators=None, properties=None): """Send a regex-related request to the CoreNLP server. :param (str | unicode) path: the path for the regex endpoint :param text: raw text for the CoreNLPServer to apply the regex :param (str | unicode) patt...
python
def __regex(self, path, text, pattern, filter, annotators=None, properties=None): """Send a regex-related request to the CoreNLP server. :param (str | unicode) path: the path for the regex endpoint :param text: raw text for the CoreNLPServer to apply the regex :param (str | unicode) patt...
Send a regex-related request to the CoreNLP server. :param (str | unicode) path: the path for the regex endpoint :param text: raw text for the CoreNLPServer to apply the regex :param (str | unicode) pattern: regex pattern :param (bool) filter: option to filter sentences that contain matc...
https://github.com/stanfordnlp/python-stanford-corenlp/blob/4d0aa08521e13e2a1c707f5a7ddcdaa3ec530d86/corenlp/client.py#L279-L332
stanfordnlp/python-stanford-corenlp
corenlp/annotator.py
Annotator.properties
def properties(self): """ Defines a Java property to define this anntoator to CoreNLP. """ return { "customAnnotatorClass.{}".format(self.name): "edu.stanford.nlp.pipeline.GenericWebServiceAnnotator", "generic.endpoint": "http://{}:{}".format(self.host, self.port)...
python
def properties(self): """ Defines a Java property to define this anntoator to CoreNLP. """ return { "customAnnotatorClass.{}".format(self.name): "edu.stanford.nlp.pipeline.GenericWebServiceAnnotator", "generic.endpoint": "http://{}:{}".format(self.host, self.port)...
Defines a Java property to define this anntoator to CoreNLP.
https://github.com/stanfordnlp/python-stanford-corenlp/blob/4d0aa08521e13e2a1c707f5a7ddcdaa3ec530d86/corenlp/annotator.py#L53-L62
stanfordnlp/python-stanford-corenlp
corenlp/annotator.py
Annotator.run
def run(self): """ Runs the server using Python's simple HTTPServer. TODO: make this multithreaded. """ httpd = HTTPServer((self.host, self.port), self._Handler) sa = httpd.socket.getsockname() serve_message = "Serving HTTP on {host} port {port} (http://{host}:{po...
python
def run(self): """ Runs the server using Python's simple HTTPServer. TODO: make this multithreaded. """ httpd = HTTPServer((self.host, self.port), self._Handler) sa = httpd.socket.getsockname() serve_message = "Serving HTTP on {host} port {port} (http://{host}:{po...
Runs the server using Python's simple HTTPServer. TODO: make this multithreaded.
https://github.com/stanfordnlp/python-stanford-corenlp/blob/4d0aa08521e13e2a1c707f5a7ddcdaa3ec530d86/corenlp/annotator.py#L125-L138
facelessuser/wcmatch
wcmatch/fnmatch.py
translate
def translate(patterns, *, flags=0): """Translate `fnmatch` pattern.""" flags = _flag_transform(flags) return _wcparse.translate(_wcparse.split(patterns, flags), flags)
python
def translate(patterns, *, flags=0): """Translate `fnmatch` pattern.""" flags = _flag_transform(flags) return _wcparse.translate(_wcparse.split(patterns, flags), flags)
Translate `fnmatch` pattern.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/fnmatch.py#L69-L73
facelessuser/wcmatch
wcmatch/wcmatch.py
WcMatch._compile_wildcard
def _compile_wildcard(self, pattern, pathname=False): """Compile or format the wildcard inclusion/exclusion pattern.""" patterns = None flags = self.flags if pathname: flags |= _wcparse.PATHNAME if pattern: patterns = _wcparse.WcSplit(pattern, flags=flags...
python
def _compile_wildcard(self, pattern, pathname=False): """Compile or format the wildcard inclusion/exclusion pattern.""" patterns = None flags = self.flags if pathname: flags |= _wcparse.PATHNAME if pattern: patterns = _wcparse.WcSplit(pattern, flags=flags...
Compile or format the wildcard inclusion/exclusion pattern.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/wcmatch.py#L109-L119
facelessuser/wcmatch
wcmatch/wcmatch.py
WcMatch._compile
def _compile(self, file_pattern, folder_exclude_pattern): """Compile patterns.""" if not isinstance(file_pattern, _wcparse.WcRegexp): file_pattern = self._compile_wildcard(file_pattern, self.file_pathname) if not isinstance(folder_exclude_pattern, _wcparse.WcRegexp): f...
python
def _compile(self, file_pattern, folder_exclude_pattern): """Compile patterns.""" if not isinstance(file_pattern, _wcparse.WcRegexp): file_pattern = self._compile_wildcard(file_pattern, self.file_pathname) if not isinstance(folder_exclude_pattern, _wcparse.WcRegexp): f...
Compile patterns.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/wcmatch.py#L121-L131
facelessuser/wcmatch
wcmatch/wcmatch.py
WcMatch._valid_file
def _valid_file(self, base, name): """Return whether a file can be searched.""" valid = False fullpath = os.path.join(base, name) if self.file_check is not None and self.compare_file(fullpath[self._base_len:] if self.file_pathname else name): valid = True if valid an...
python
def _valid_file(self, base, name): """Return whether a file can be searched.""" valid = False fullpath = os.path.join(base, name) if self.file_check is not None and self.compare_file(fullpath[self._base_len:] if self.file_pathname else name): valid = True if valid an...
Return whether a file can be searched.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/wcmatch.py#L133-L142
facelessuser/wcmatch
wcmatch/wcmatch.py
WcMatch._valid_folder
def _valid_folder(self, base, name): """Return whether a folder can be searched.""" valid = True fullpath = os.path.join(base, name) if ( not self.recursive or ( self.folder_exclude_check is not None and not self.compare_directory(...
python
def _valid_folder(self, base, name): """Return whether a folder can be searched.""" valid = True fullpath = os.path.join(base, name) if ( not self.recursive or ( self.folder_exclude_check is not None and not self.compare_directory(...
Return whether a folder can be searched.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/wcmatch.py#L154-L169
facelessuser/wcmatch
wcmatch/wcmatch.py
WcMatch.compare_directory
def compare_directory(self, directory): """Compare folder.""" return not self.folder_exclude_check.match(directory + self.sep if self.dir_pathname else directory)
python
def compare_directory(self, directory): """Compare folder.""" return not self.folder_exclude_check.match(directory + self.sep if self.dir_pathname else directory)
Compare folder.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/wcmatch.py#L171-L174
facelessuser/wcmatch
wcmatch/wcmatch.py
WcMatch._walk
def _walk(self): """Start search for valid files.""" self._base_len = len(self.base) for base, dirs, files in os.walk(self.base, followlinks=self.follow_links): # Remove child folders based on exclude rules for name in dirs[:]: try: i...
python
def _walk(self): """Start search for valid files.""" self._base_len = len(self.base) for base, dirs, files in os.walk(self.base, followlinks=self.follow_links): # Remove child folders based on exclude rules for name in dirs[:]: try: i...
Start search for valid files.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/wcmatch.py#L214-L258
facelessuser/wcmatch
wcmatch/_wcparse.py
is_negative
def is_negative(pattern, flags): """Check if negative pattern.""" if flags & MINUSNEGATE: return flags & NEGATE and pattern[0:1] in MINUS_NEGATIVE_SYM else: return flags & NEGATE and pattern[0:1] in NEGATIVE_SYM
python
def is_negative(pattern, flags): """Check if negative pattern.""" if flags & MINUSNEGATE: return flags & NEGATE and pattern[0:1] in MINUS_NEGATIVE_SYM else: return flags & NEGATE and pattern[0:1] in NEGATIVE_SYM
Check if negative pattern.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L159-L165
facelessuser/wcmatch
wcmatch/_wcparse.py
expand_braces
def expand_braces(patterns, flags): """Expand braces.""" if flags & BRACE: for p in ([patterns] if isinstance(patterns, (str, bytes)) else patterns): try: yield from bracex.iexpand(p, keep_escapes=True) except Exception: # pragma: no cover # We w...
python
def expand_braces(patterns, flags): """Expand braces.""" if flags & BRACE: for p in ([patterns] if isinstance(patterns, (str, bytes)) else patterns): try: yield from bracex.iexpand(p, keep_escapes=True) except Exception: # pragma: no cover # We w...
Expand braces.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L168-L182
facelessuser/wcmatch
wcmatch/_wcparse.py
get_case
def get_case(flags): """Parse flags for case sensitivity settings.""" if not bool(flags & CASE_FLAGS): case_sensitive = util.is_case_sensitive() elif flags & FORCECASE: case_sensitive = True else: case_sensitive = False return case_sensitive
python
def get_case(flags): """Parse flags for case sensitivity settings.""" if not bool(flags & CASE_FLAGS): case_sensitive = util.is_case_sensitive() elif flags & FORCECASE: case_sensitive = True else: case_sensitive = False return case_sensitive
Parse flags for case sensitivity settings.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L185-L194
facelessuser/wcmatch
wcmatch/_wcparse.py
is_unix_style
def is_unix_style(flags): """Check if we should use Unix style.""" return (util.platform() != "windows" or (not bool(flags & REALPATH) and get_case(flags))) and not flags & _FORCEWIN
python
def is_unix_style(flags): """Check if we should use Unix style.""" return (util.platform() != "windows" or (not bool(flags & REALPATH) and get_case(flags))) and not flags & _FORCEWIN
Check if we should use Unix style.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L197-L200
facelessuser/wcmatch
wcmatch/_wcparse.py
translate
def translate(patterns, flags): """Translate patterns.""" positive = [] negative = [] if isinstance(patterns, (str, bytes)): patterns = [patterns] flags |= _TRANSLATE for pattern in patterns: for expanded in expand_braces(pattern, flags): (negative if is_negative(e...
python
def translate(patterns, flags): """Translate patterns.""" positive = [] negative = [] if isinstance(patterns, (str, bytes)): patterns = [patterns] flags |= _TRANSLATE for pattern in patterns: for expanded in expand_braces(pattern, flags): (negative if is_negative(e...
Translate patterns.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L203-L222
facelessuser/wcmatch
wcmatch/_wcparse.py
split
def split(patterns, flags): """Split patterns.""" if flags & SPLIT: splitted = [] for pattern in ([patterns] if isinstance(patterns, (str, bytes)) else patterns): splitted.extend(WcSplit(pattern, flags).split()) return splitted else: return patterns
python
def split(patterns, flags): """Split patterns.""" if flags & SPLIT: splitted = [] for pattern in ([patterns] if isinstance(patterns, (str, bytes)) else patterns): splitted.extend(WcSplit(pattern, flags).split()) return splitted else: return patterns
Split patterns.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L225-L234
facelessuser/wcmatch
wcmatch/_wcparse.py
compile
def compile(patterns, flags): # noqa A001 """Compile patterns.""" positive = [] negative = [] if isinstance(patterns, (str, bytes)): patterns = [patterns] for pattern in patterns: for expanded in expand_braces(pattern, flags): (negative if is_negative(expanded, flags) ...
python
def compile(patterns, flags): # noqa A001 """Compile patterns.""" positive = [] negative = [] if isinstance(patterns, (str, bytes)): patterns = [patterns] for pattern in patterns: for expanded in expand_braces(pattern, flags): (negative if is_negative(expanded, flags) ...
Compile patterns.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L237-L252
facelessuser/wcmatch
wcmatch/_wcparse.py
_compile
def _compile(pattern, flags): """Compile the pattern to regex.""" return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())
python
def _compile(pattern, flags): """Compile the pattern to regex.""" return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())
Compile the pattern to regex.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L256-L259
facelessuser/wcmatch
wcmatch/_wcparse.py
_fs_match
def _fs_match(pattern, filename, sep, follow, symlinks): """ Match path against the pattern. Since `globstar` doesn't match symlinks (unless `FOLLOW` is enabled), we must look for symlinks. If we identify a symlink in a `globstar` match, we know this result should not actually match. """ match...
python
def _fs_match(pattern, filename, sep, follow, symlinks): """ Match path against the pattern. Since `globstar` doesn't match symlinks (unless `FOLLOW` is enabled), we must look for symlinks. If we identify a symlink in a `globstar` match, we know this result should not actually match. """ match...
Match path against the pattern. Since `globstar` doesn't match symlinks (unless `FOLLOW` is enabled), we must look for symlinks. If we identify a symlink in a `globstar` match, we know this result should not actually match.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L1258-L1295
facelessuser/wcmatch
wcmatch/_wcparse.py
_match_real
def _match_real(filename, include, exclude, follow, symlinks): """Match real filename includes and excludes.""" sep = '\\' if util.platform() == "windows" else '/' if isinstance(filename, bytes): sep = os.fsencode(sep) if not filename.endswith(sep) and os.path.isdir(filename): filename ...
python
def _match_real(filename, include, exclude, follow, symlinks): """Match real filename includes and excludes.""" sep = '\\' if util.platform() == "windows" else '/' if isinstance(filename, bytes): sep = os.fsencode(sep) if not filename.endswith(sep) and os.path.isdir(filename): filename ...
Match real filename includes and excludes.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L1298-L1320
facelessuser/wcmatch
wcmatch/_wcparse.py
_match_pattern
def _match_pattern(filename, include, exclude, real, path, follow): """Match includes and excludes.""" if real: symlinks = {} if isinstance(filename, bytes): curdir = os.fsencode(os.curdir) mount = RE_BWIN_MOUNT if util.platform() == "windows" else RE_BMOUNT else...
python
def _match_pattern(filename, include, exclude, real, path, follow): """Match includes and excludes.""" if real: symlinks = {} if isinstance(filename, bytes): curdir = os.fsencode(os.curdir) mount = RE_BWIN_MOUNT if util.platform() == "windows" else RE_BMOUNT else...
Match includes and excludes.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L1323-L1361
facelessuser/wcmatch
wcmatch/_wcparse.py
WcPathSplit._sequence
def _sequence(self, i): """Handle character group.""" c = next(i) if c == '!': c = next(i) if c in ('^', '-', '['): c = next(i) while c != ']': if c == '\\': # Handle escapes subindex = i.index ...
python
def _sequence(self, i): """Handle character group.""" c = next(i) if c == '!': c = next(i) if c in ('^', '-', '['): c = next(i) while c != ']': if c == '\\': # Handle escapes subindex = i.index ...
Handle character group.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L322-L343
facelessuser/wcmatch
wcmatch/_wcparse.py
WcPathSplit._references
def _references(self, i, sequence=False): """Handle references.""" value = '' c = next(i) if c == '\\': # \\ if sequence and self.bslash_abort: raise PathNameException value = c elif c == '/': # \/ if s...
python
def _references(self, i, sequence=False): """Handle references.""" value = '' c = next(i) if c == '\\': # \\ if sequence and self.bslash_abort: raise PathNameException value = c elif c == '/': # \/ if s...
Handle references.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L345-L364
facelessuser/wcmatch
wcmatch/_wcparse.py
WcPathSplit.parse_extend
def parse_extend(self, c, i): """Parse extended pattern lists.""" # Start list parsing success = True index = i.index list_type = c try: c = next(i) if c != '(': raise StopIteration while c != ')': c = n...
python
def parse_extend(self, c, i): """Parse extended pattern lists.""" # Start list parsing success = True index = i.index list_type = c try: c = next(i) if c != '(': raise StopIteration while c != ')': c = n...
Parse extended pattern lists.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L366-L400
facelessuser/wcmatch
wcmatch/_wcparse.py
WcPathSplit.store
def store(self, value, l, dir_only): """Group patterns by literals and potential magic patterns.""" if l and value in (b'', ''): return globstar = value in (b'**', '**') and self.globstar magic = self.is_magic(value) if magic: value = compile(value, self...
python
def store(self, value, l, dir_only): """Group patterns by literals and potential magic patterns.""" if l and value in (b'', ''): return globstar = value in (b'**', '**') and self.globstar magic = self.is_magic(value) if magic: value = compile(value, self...
Group patterns by literals and potential magic patterns.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L402-L412
facelessuser/wcmatch
wcmatch/_wcparse.py
WcPathSplit.split
def split(self): """Start parsing the pattern.""" split_index = [] parts = [] start = -1 pattern = self.pattern.decode('latin-1') if self.is_bytes else self.pattern i = util.StringIter(pattern) iter(i) # Detect and store away windows drive as a literal...
python
def split(self): """Start parsing the pattern.""" split_index = [] parts = [] start = -1 pattern = self.pattern.decode('latin-1') if self.is_bytes else self.pattern i = util.StringIter(pattern) iter(i) # Detect and store away windows drive as a literal...
Start parsing the pattern.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L414-L487
facelessuser/wcmatch
wcmatch/_wcparse.py
WcSplit._references
def _references(self, i, sequence=False): """Handle references.""" c = next(i) if c == '\\': # \\ if sequence and self.bslash_abort: raise PathNameException elif c == '/': # \/ if sequence and self.pathname: ...
python
def _references(self, i, sequence=False): """Handle references.""" c = next(i) if c == '\\': # \\ if sequence and self.bslash_abort: raise PathNameException elif c == '/': # \/ if sequence and self.pathname: ...
Handle references.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L527-L543
facelessuser/wcmatch
wcmatch/_wcparse.py
WcSplit.split
def split(self): """Start parsing the pattern.""" split_index = [] parts = [] pattern = self.pattern.decode('latin-1') if self.is_bytes else self.pattern i = util.StringIter(pattern) iter(i) for c in i: if self.extend and c in EXT_TYPES and self.par...
python
def split(self): """Start parsing the pattern.""" split_index = [] parts = [] pattern = self.pattern.decode('latin-1') if self.is_bytes else self.pattern i = util.StringIter(pattern) iter(i) for c in i: if self.extend and c in EXT_TYPES and self.par...
Start parsing the pattern.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L581-L620
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse.update_dir_state
def update_dir_state(self): """ Update the directory state. If we are at the directory start, update to after start state (the character right after). If at after start, reset state. """ if self.dir_start and not self.after_start: self.set_after_star...
python
def update_dir_state(self): """ Update the directory state. If we are at the directory start, update to after start state (the character right after). If at after start, reset state. """ if self.dir_start and not self.after_start: self.set_after_star...
Update the directory state. If we are at the directory start, update to after start state (the character right after). If at after start, reset state.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L683-L695
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse._restrict_sequence
def _restrict_sequence(self): """Restrict sequence.""" if self.pathname: value = self.seq_path_dot if self.after_start and not self.dot else self.seq_path if self.after_start: value = self.no_dir + value else: value = _NO_DOT if self.after_sta...
python
def _restrict_sequence(self): """Restrict sequence.""" if self.pathname: value = self.seq_path_dot if self.after_start and not self.dot else self.seq_path if self.after_start: value = self.no_dir + value else: value = _NO_DOT if self.after_sta...
Restrict sequence.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L702-L713
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse._sequence_range_check
def _sequence_range_check(self, result, last): """ If range backwards, remove it. A bad range will cause the regular expression to fail, so we need to remove it, but return that we removed it so the caller can know the sequence wasn't empty. Caller will have to craft a s...
python
def _sequence_range_check(self, result, last): """ If range backwards, remove it. A bad range will cause the regular expression to fail, so we need to remove it, but return that we removed it so the caller can know the sequence wasn't empty. Caller will have to craft a s...
If range backwards, remove it. A bad range will cause the regular expression to fail, so we need to remove it, but return that we removed it so the caller can know the sequence wasn't empty. Caller will have to craft a sequence that makes sense if empty at the end with either an...
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L715-L738
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse._handle_posix
def _handle_posix(self, i, result, end_range): """Handle posix classes.""" last_posix = False m = i.match(RE_POSIX) if m: last_posix = True # Cannot do range with posix class # so escape last `-` if we think this # is the end of a range. ...
python
def _handle_posix(self, i, result, end_range): """Handle posix classes.""" last_posix = False m = i.match(RE_POSIX) if m: last_posix = True # Cannot do range with posix class # so escape last `-` if we think this # is the end of a range. ...
Handle posix classes.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L740-L754
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse._sequence
def _sequence(self, i): """Handle character group.""" result = ['['] end_range = 0 escape_hyphen = -1 removed = False last_posix = False c = next(i) if c in ('!', '^'): # Handle negate char result.append('^') c = next(...
python
def _sequence(self, i): """Handle character group.""" result = ['['] end_range = 0 escape_hyphen = -1 removed = False last_posix = False c = next(i) if c in ('!', '^'): # Handle negate char result.append('^') c = next(...
Handle character group.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L756-L858
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse._references
def _references(self, i, sequence=False): """Handle references.""" value = '' c = next(i) if c == '\\': # \\ if sequence and self.bslash_abort: raise PathNameException value = r'\\' if self.bslash_abort: if ...
python
def _references(self, i, sequence=False): """Handle references.""" value = '' c = next(i) if c == '\\': # \\ if sequence and self.bslash_abort: raise PathNameException value = r'\\' if self.bslash_abort: if ...
Handle references.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L860-L894
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse._handle_star
def _handle_star(self, i, current): """Handle star.""" if self.pathname: if self.after_start and not self.dot: star = self.path_star_dot2 globstar = self.path_gstar_dot2 elif self.after_start: star = self.path_star_dot1 ...
python
def _handle_star(self, i, current): """Handle star.""" if self.pathname: if self.after_start and not self.dot: star = self.path_star_dot2 globstar = self.path_gstar_dot2 elif self.after_start: star = self.path_star_dot1 ...
Handle star.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L896-L986
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse.clean_up_inverse
def clean_up_inverse(self, current): """ Clean up current. Python doesn't have variable lookbehinds, so we have to do negative lookaheads. !(...) when converted to regular expression is atomic, so once it matches, that's it. So we use the pattern `(?:(?!(?:stuff|to|exclude)<x>))...
python
def clean_up_inverse(self, current): """ Clean up current. Python doesn't have variable lookbehinds, so we have to do negative lookaheads. !(...) when converted to regular expression is atomic, so once it matches, that's it. So we use the pattern `(?:(?!(?:stuff|to|exclude)<x>))...
Clean up current. Python doesn't have variable lookbehinds, so we have to do negative lookaheads. !(...) when converted to regular expression is atomic, so once it matches, that's it. So we use the pattern `(?:(?!(?:stuff|to|exclude)<x>))[^/]*?)` where <x> is everything that comes after...
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L988-L1013
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse.parse_extend
def parse_extend(self, c, i, current, reset_dot=False): """Parse extended pattern lists.""" # Save state temp_dir_start = self.dir_start temp_after_start = self.after_start temp_in_list = self.in_list temp_inv_ext = self.inv_ext self.in_list = True if res...
python
def parse_extend(self, c, i, current, reset_dot=False): """Parse extended pattern lists.""" # Save state temp_dir_start = self.dir_start temp_after_start = self.after_start temp_in_list = self.in_list temp_inv_ext = self.inv_ext self.in_list = True if res...
Parse extended pattern lists.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L1015-L1124
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse.consume_path_sep
def consume_path_sep(self, i): """Consume any consecutive path separators are they count as one.""" try: if self.bslash_abort: count = -1 c = '\\' while c == '\\': count += 1 c = next(i) ...
python
def consume_path_sep(self, i): """Consume any consecutive path separators are they count as one.""" try: if self.bslash_abort: count = -1 c = '\\' while c == '\\': count += 1 c = next(i) ...
Consume any consecutive path separators are they count as one.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L1131-L1151
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse.root
def root(self, pattern, current): """Start parsing the pattern.""" self.set_after_start() i = util.StringIter(pattern) iter(i) root_specified = False if self.win_drive_detect: m = RE_WIN_PATH.match(pattern) if m: drive = m.group(0)...
python
def root(self, pattern, current): """Start parsing the pattern.""" self.set_after_start() i = util.StringIter(pattern) iter(i) root_specified = False if self.win_drive_detect: m = RE_WIN_PATH.match(pattern) if m: drive = m.group(0)...
Start parsing the pattern.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L1153-L1225
facelessuser/wcmatch
wcmatch/_wcparse.py
WcParse.parse
def parse(self): """Parse pattern list.""" result = [''] negative = False p = util.norm_pattern(self.pattern, not self.unix, self.raw_chars) p = p.decode('latin-1') if self.is_bytes else p if is_negative(p, self.flags): negative = True p = p[1:]...
python
def parse(self): """Parse pattern list.""" result = [''] negative = False p = util.norm_pattern(self.pattern, not self.unix, self.raw_chars) p = p.decode('latin-1') if self.is_bytes else p if is_negative(p, self.flags): negative = True p = p[1:]...
Parse pattern list.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L1227-L1255
facelessuser/wcmatch
wcmatch/_wcparse.py
WcRegexp.match
def match(self, filename): """Match filename.""" return _match_pattern(filename, self._include, self._exclude, self._real, self._path, self._follow)
python
def match(self, filename): """Match filename.""" return _match_pattern(filename, self._include, self._exclude, self._real, self._path, self._follow)
Match filename.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L1419-L1422
facelessuser/wcmatch
wcmatch/glob.py
_flag_transform
def _flag_transform(flags): """Transform flags to glob defaults.""" # Here we force `PATHNAME`. flags = (flags & FLAG_MASK) | _wcparse.PATHNAME if flags & _wcparse.REALPATH and util.platform() == "windows": flags |= _wcparse._FORCEWIN if flags & _wcparse.FORCECASE: flags ^= ...
python
def _flag_transform(flags): """Transform flags to glob defaults.""" # Here we force `PATHNAME`. flags = (flags & FLAG_MASK) | _wcparse.PATHNAME if flags & _wcparse.REALPATH and util.platform() == "windows": flags |= _wcparse._FORCEWIN if flags & _wcparse.FORCECASE: flags ^= ...
Transform flags to glob defaults.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L71-L80
facelessuser/wcmatch
wcmatch/glob.py
glob
def glob(patterns, *, flags=0): """Glob.""" return list(iglob(util.to_tuple(patterns), flags=flags))
python
def glob(patterns, *, flags=0): """Glob.""" return list(iglob(util.to_tuple(patterns), flags=flags))
Glob.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L408-L411
facelessuser/wcmatch
wcmatch/glob.py
globmatch
def globmatch(filename, patterns, *, flags=0): """ Check if filename matches pattern. By default case sensitivity is determined by the file system, but if `case_sensitive` is set, respect that instead. """ flags = _flag_transform(flags) if not _wcparse.is_unix_style(flags): filenam...
python
def globmatch(filename, patterns, *, flags=0): """ Check if filename matches pattern. By default case sensitivity is determined by the file system, but if `case_sensitive` is set, respect that instead. """ flags = _flag_transform(flags) if not _wcparse.is_unix_style(flags): filenam...
Check if filename matches pattern. By default case sensitivity is determined by the file system, but if `case_sensitive` is set, respect that instead.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L428-L439
facelessuser/wcmatch
wcmatch/glob.py
globfilter
def globfilter(filenames, patterns, *, flags=0): """Filter names using pattern.""" matches = [] flags = _flag_transform(flags) unix = _wcparse.is_unix_style(flags) obj = _wcparse.compile(_wcparse.split(patterns, flags), flags) for filename in filenames: if not unix: filena...
python
def globfilter(filenames, patterns, *, flags=0): """Filter names using pattern.""" matches = [] flags = _flag_transform(flags) unix = _wcparse.is_unix_style(flags) obj = _wcparse.compile(_wcparse.split(patterns, flags), flags) for filename in filenames: if not unix: filena...
Filter names using pattern.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L442-L456
facelessuser/wcmatch
wcmatch/glob.py
raw_escape
def raw_escape(pattern, unix=False): """Apply raw character transform before applying escape.""" pattern = util.norm_pattern(pattern, False, True) return escape(pattern, unix)
python
def raw_escape(pattern, unix=False): """Apply raw character transform before applying escape.""" pattern = util.norm_pattern(pattern, False, True) return escape(pattern, unix)
Apply raw character transform before applying escape.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L459-L463
facelessuser/wcmatch
wcmatch/glob.py
escape
def escape(pattern, unix=False): """Escape.""" is_bytes = isinstance(pattern, bytes) replace = br'\\\1' if is_bytes else r'\\\1' win = util.platform() == "windows" if win and not unix: magic = _wcparse.RE_BWIN_MAGIC if is_bytes else _wcparse.RE_WIN_MAGIC else: magic = _wcparse.R...
python
def escape(pattern, unix=False): """Escape.""" is_bytes = isinstance(pattern, bytes) replace = br'\\\1' if is_bytes else r'\\\1' win = util.platform() == "windows" if win and not unix: magic = _wcparse.RE_BWIN_MAGIC if is_bytes else _wcparse.RE_WIN_MAGIC else: magic = _wcparse.R...
Escape.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L466-L488
facelessuser/wcmatch
wcmatch/glob.py
Glob._parse_patterns
def _parse_patterns(self, pattern): """Parse patterns.""" self.pattern = [] self.npatterns = None npattern = [] for p in pattern: if _wcparse.is_negative(p, self.flags): # Treat the inverse pattern as a normal pattern if it matches, we will exclude. ...
python
def _parse_patterns(self, pattern): """Parse patterns.""" self.pattern = [] self.npatterns = None npattern = [] for p in pattern: if _wcparse.is_negative(p, self.flags): # Treat the inverse pattern as a normal pattern if it matches, we will exclude. ...
Parse patterns.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L106-L125
facelessuser/wcmatch
wcmatch/glob.py
Glob._match_excluded
def _match_excluded(self, filename, patterns): """Call match real directly to skip unnecessary `exists` check.""" return _wcparse._match_real( filename, patterns._include, patterns._exclude, patterns._follow, self.symlinks )
python
def _match_excluded(self, filename, patterns): """Call match real directly to skip unnecessary `exists` check.""" return _wcparse._match_real( filename, patterns._include, patterns._exclude, patterns._follow, self.symlinks )
Call match real directly to skip unnecessary `exists` check.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L142-L147
facelessuser/wcmatch
wcmatch/glob.py
Glob._is_excluded
def _is_excluded(self, path, dir_only): """Check if file is excluded.""" return self.npatterns and self._match_excluded(path, self.npatterns)
python
def _is_excluded(self, path, dir_only): """Check if file is excluded.""" return self.npatterns and self._match_excluded(path, self.npatterns)
Check if file is excluded.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L149-L152
facelessuser/wcmatch
wcmatch/glob.py
Glob._match_literal
def _match_literal(self, a, b=None): """Match two names.""" return a.lower() == b if not self.case_sensitive else a == b
python
def _match_literal(self, a, b=None): """Match two names.""" return a.lower() == b if not self.case_sensitive else a == b
Match two names.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L154-L157
facelessuser/wcmatch
wcmatch/glob.py
Glob._get_matcher
def _get_matcher(self, target): """Get deep match.""" if target is None: matcher = None elif isinstance(target, (str, bytes)): # Plain text match if not self.case_sensitive: match = target.lower() else: match = targ...
python
def _get_matcher(self, target): """Get deep match.""" if target is None: matcher = None elif isinstance(target, (str, bytes)): # Plain text match if not self.case_sensitive: match = target.lower() else: match = targ...
Get deep match.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L159-L174
facelessuser/wcmatch
wcmatch/glob.py
Glob._glob_dir
def _glob_dir(self, curdir, matcher, dir_only=False, deep=False): """Non recursive directory glob.""" scandir = self.current if not curdir else curdir # Python will never return . or .., so fake it. if os.path.isdir(scandir) and matcher is not None: for special in self.spec...
python
def _glob_dir(self, curdir, matcher, dir_only=False, deep=False): """Non recursive directory glob.""" scandir = self.current if not curdir else curdir # Python will never return . or .., so fake it. if os.path.isdir(scandir) and matcher is not None: for special in self.spec...
Non recursive directory glob.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L176-L233
facelessuser/wcmatch
wcmatch/glob.py
Glob._glob
def _glob(self, curdir, this, rest): """ Handle glob flow. There are really only a couple of cases: - File name. - File name pattern (magic). - Directory. - Directory name pattern (magic). - Extra slashes `////`. - `globstar` `**`. """ ...
python
def _glob(self, curdir, this, rest): """ Handle glob flow. There are really only a couple of cases: - File name. - File name pattern (magic). - Directory. - Directory name pattern (magic). - Extra slashes `////`. - `globstar` `**`. """ ...
Handle glob flow. There are really only a couple of cases: - File name. - File name pattern (magic). - Directory. - Directory name pattern (magic). - Extra slashes `////`. - `globstar` `**`.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L235-L315
facelessuser/wcmatch
wcmatch/glob.py
Glob._get_starting_paths
def _get_starting_paths(self, curdir): """ Get the starting location. For case sensitive paths, we have to "glob" for it first as Python doesn't like for its users to think about case. By scanning for it, we can get the actual casing and then compare. """ ...
python
def _get_starting_paths(self, curdir): """ Get the starting location. For case sensitive paths, we have to "glob" for it first as Python doesn't like for its users to think about case. By scanning for it, we can get the actual casing and then compare. """ ...
Get the starting location. For case sensitive paths, we have to "glob" for it first as Python doesn't like for its users to think about case. By scanning for it, we can get the actual casing and then compare.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L317-L337
facelessuser/wcmatch
wcmatch/glob.py
Glob.glob
def glob(self): """Starts off the glob iterator.""" # Cached symlinks self.symlinks = {} if self.is_bytes: curdir = os.fsencode(os.curdir) else: curdir = os.curdir for pattern in self.pattern: # If the pattern ends with `/` we return...
python
def glob(self): """Starts off the glob iterator.""" # Cached symlinks self.symlinks = {} if self.is_bytes: curdir = os.fsencode(os.curdir) else: curdir = os.curdir for pattern in self.pattern: # If the pattern ends with `/` we return...
Starts off the glob iterator.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L339-L399
facelessuser/wcmatch
wcmatch/util.py
norm_slash
def norm_slash(name): """Normalize path slashes.""" if isinstance(name, str): return name.replace('/', "\\") if not is_case_sensitive() else name else: return name.replace(b'/', b"\\") if not is_case_sensitive() else name
python
def norm_slash(name): """Normalize path slashes.""" if isinstance(name, str): return name.replace('/', "\\") if not is_case_sensitive() else name else: return name.replace(b'/', b"\\") if not is_case_sensitive() else name
Normalize path slashes.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/util.py#L82-L88
facelessuser/wcmatch
wcmatch/util.py
norm_pattern
def norm_pattern(pattern, normalize, is_raw_chars): r""" Normalize pattern. - For windows systems we want to normalize slashes to \. - If raw string chars is enabled, we want to also convert encoded string chars to literal characters. - If `normalize` is enabled, take care to convert \/ to \\...
python
def norm_pattern(pattern, normalize, is_raw_chars): r""" Normalize pattern. - For windows systems we want to normalize slashes to \. - If raw string chars is enabled, we want to also convert encoded string chars to literal characters. - If `normalize` is enabled, take care to convert \/ to \\...
r""" Normalize pattern. - For windows systems we want to normalize slashes to \. - If raw string chars is enabled, we want to also convert encoded string chars to literal characters. - If `normalize` is enabled, take care to convert \/ to \\\\.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/util.py#L91-L136
facelessuser/wcmatch
wcmatch/util.py
is_hidden
def is_hidden(path): """Check if file is hidden.""" hidden = False f = os.path.basename(path) if f[:1] in ('.', b'.'): # Count dot file as hidden on all systems hidden = True elif _PLATFORM == 'windows': # On Windows, look for `FILE_ATTRIBUTE_HIDDEN` FILE_ATTRIBUTE_H...
python
def is_hidden(path): """Check if file is hidden.""" hidden = False f = os.path.basename(path) if f[:1] in ('.', b'.'): # Count dot file as hidden on all systems hidden = True elif _PLATFORM == 'windows': # On Windows, look for `FILE_ATTRIBUTE_HIDDEN` FILE_ATTRIBUTE_H...
Check if file is hidden.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/util.py#L219-L243
facelessuser/wcmatch
wcmatch/util.py
StringIter.match
def match(self, pattern): """Perform regex match at index.""" m = pattern.match(self._string, self._index) if m: self._index = m.end() return m
python
def match(self, pattern): """Perform regex match at index.""" m = pattern.match(self._string, self._index) if m: self._index = m.end() return m
Perform regex match at index.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/util.py#L158-L164
facelessuser/wcmatch
wcmatch/util.py
StringIter.iternext
def iternext(self): """Iterate through characters of the string.""" try: char = self._string[self._index] self._index += 1 except IndexError: # pragma: no cover raise StopIteration return char
python
def iternext(self): """Iterate through characters of the string.""" try: char = self._string[self._index] self._index += 1 except IndexError: # pragma: no cover raise StopIteration return char
Iterate through characters of the string.
https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/util.py#L190-L199
praekeltfoundation/molo
molo/core/utils.py
generate_slug
def generate_slug(text, tail_number=0): from wagtail.core.models import Page """ Returns a new unique slug. Object must provide a SlugField called slug. URL friendly slugs are generated using django.template.defaultfilters' slugify. Numbers are added to the end of slugs for uniqueness. based on...
python
def generate_slug(text, tail_number=0): from wagtail.core.models import Page """ Returns a new unique slug. Object must provide a SlugField called slug. URL friendly slugs are generated using django.template.defaultfilters' slugify. Numbers are added to the end of slugs for uniqueness. based on...
Returns a new unique slug. Object must provide a SlugField called slug. URL friendly slugs are generated using django.template.defaultfilters' slugify. Numbers are added to the end of slugs for uniqueness. based on implementation in jmbo.utils https://github.com/praekelt/jmbo/blob/develop/jmbo/utils/__...
https://github.com/praekeltfoundation/molo/blob/57702fda4fab261d67591415f7d46bc98fa38525/molo/core/utils.py#L132-L174
praekeltfoundation/molo
molo/core/utils.py
update_media_file
def update_media_file(upload_file): ''' Update the Current Media Folder. Returns list of files copied across or raises an exception. ''' temp_directory = tempfile.mkdtemp() temp_file = tempfile.TemporaryFile() # assumes the zip file contains a directory called media temp_media_file ...
python
def update_media_file(upload_file): ''' Update the Current Media Folder. Returns list of files copied across or raises an exception. ''' temp_directory = tempfile.mkdtemp() temp_file = tempfile.TemporaryFile() # assumes the zip file contains a directory called media temp_media_file ...
Update the Current Media Folder. Returns list of files copied across or raises an exception.
https://github.com/praekeltfoundation/molo/blob/57702fda4fab261d67591415f7d46bc98fa38525/molo/core/utils.py#L177-L207
praekeltfoundation/molo
molo/core/utils.py
get_image_hash
def get_image_hash(image): ''' Returns an MD5 hash of the image file Handles images stored locally and on AWS I know this code is ugly. Please don't ask. The rabbit hole is deep. ''' md5 = hashlib.md5() try: for chunk in image.file.chunks(): md5.update(chunk) ...
python
def get_image_hash(image): ''' Returns an MD5 hash of the image file Handles images stored locally and on AWS I know this code is ugly. Please don't ask. The rabbit hole is deep. ''' md5 = hashlib.md5() try: for chunk in image.file.chunks(): md5.update(chunk) ...
Returns an MD5 hash of the image file Handles images stored locally and on AWS I know this code is ugly. Please don't ask. The rabbit hole is deep.
https://github.com/praekeltfoundation/molo/blob/57702fda4fab261d67591415f7d46bc98fa38525/molo/core/utils.py#L210-L235