id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
235,800
scikit-tda/kepler-mapper
kmapper/plotlyviz.py
summary_fig
def summary_fig( mapper_summary, width=600, height=500, top=60, left=20, bottom=60, right=20, bgcolor="rgb(240,240,240)", ): """Define a dummy figure that displays info on the algorithms and sklearn class instances or methods used Returns a FigureWidget object representing the figure """ text = _text_mapper_summary(mapper_summary) data = [ dict( type="scatter", x=[0, width], y=[height, 0], mode="text", text=[text, ""], textposition="bottom right", hoverinfo="none", ) ] layout = dict( title="Algorithms and scikit-learn objects/methods", width=width, height=height, font=dict(size=12), xaxis=dict(visible=False), yaxis=dict(visible=False, range=[0, height + 5]), margin=dict(t=top, b=bottom, l=left, r=right), plot_bgcolor=bgcolor, ) return go.FigureWidget(data=data, layout=layout)
python
def summary_fig( mapper_summary, width=600, height=500, top=60, left=20, bottom=60, right=20, bgcolor="rgb(240,240,240)", ): text = _text_mapper_summary(mapper_summary) data = [ dict( type="scatter", x=[0, width], y=[height, 0], mode="text", text=[text, ""], textposition="bottom right", hoverinfo="none", ) ] layout = dict( title="Algorithms and scikit-learn objects/methods", width=width, height=height, font=dict(size=12), xaxis=dict(visible=False), yaxis=dict(visible=False, range=[0, height + 5]), margin=dict(t=top, b=bottom, l=left, r=right), plot_bgcolor=bgcolor, ) return go.FigureWidget(data=data, layout=layout)
[ "def", "summary_fig", "(", "mapper_summary", ",", "width", "=", "600", ",", "height", "=", "500", ",", "top", "=", "60", ",", "left", "=", "20", ",", "bottom", "=", "60", ",", "right", "=", "20", ",", "bgcolor", "=", "\"rgb(240,240,240)\"", ",", ")",...
Define a dummy figure that displays info on the algorithms and sklearn class instances or methods used Returns a FigureWidget object representing the figure
[ "Define", "a", "dummy", "figure", "that", "displays", "info", "on", "the", "algorithms", "and", "sklearn", "class", "instances", "or", "methods", "used", "Returns", "a", "FigureWidget", "object", "representing", "the", "figure" ]
d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d
https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/plotlyviz.py#L543-L583
235,801
scikit-tda/kepler-mapper
kmapper/nerve.py
GraphNerve.compute
def compute(self, nodes): """Helper function to find edges of the overlapping clusters. Parameters ---------- nodes: A dictionary with entires `{node id}:{list of ids in node}` Returns ------- edges: A 1-skeleton of the nerve (intersecting nodes) simplicies: Complete list of simplices """ result = defaultdict(list) # Create links when clusters from different hypercubes have members with the same sample id. candidates = itertools.combinations(nodes.keys(), 2) for candidate in candidates: # if there are non-unique members in the union if ( len(set(nodes[candidate[0]]).intersection(nodes[candidate[1]])) >= self.min_intersection ): result[candidate[0]].append(candidate[1]) edges = [[x, end] for x in result for end in result[x]] simplices = [[n] for n in nodes] + edges return result, simplices
python
def compute(self, nodes): result = defaultdict(list) # Create links when clusters from different hypercubes have members with the same sample id. candidates = itertools.combinations(nodes.keys(), 2) for candidate in candidates: # if there are non-unique members in the union if ( len(set(nodes[candidate[0]]).intersection(nodes[candidate[1]])) >= self.min_intersection ): result[candidate[0]].append(candidate[1]) edges = [[x, end] for x in result for end in result[x]] simplices = [[n] for n in nodes] + edges return result, simplices
[ "def", "compute", "(", "self", ",", "nodes", ")", ":", "result", "=", "defaultdict", "(", "list", ")", "# Create links when clusters from different hypercubes have members with the same sample id.", "candidates", "=", "itertools", ".", "combinations", "(", "nodes", ".", ...
Helper function to find edges of the overlapping clusters. Parameters ---------- nodes: A dictionary with entires `{node id}:{list of ids in node}` Returns ------- edges: A 1-skeleton of the nerve (intersecting nodes) simplicies: Complete list of simplices
[ "Helper", "function", "to", "find", "edges", "of", "the", "overlapping", "clusters", "." ]
d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d
https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/nerve.py#L35-L67
235,802
scikit-tda/kepler-mapper
kmapper/cover.py
Cover.fit
def fit(self, data): """ Fit a cover on the data. This method constructs centers and radii in each dimension given the `perc_overlap` and `n_cube`. Parameters ============ data: array-like Data to apply the cover to. Warning: First column must be an index column. Returns ======== centers: list of arrays A list of centers for each cube """ # TODO: support indexing into any columns di = np.array(range(1, data.shape[1])) indexless_data = data[:, di] n_dims = indexless_data.shape[1] # support different values along each dimension ## -- is a list, needs to be array ## -- is a singleton, needs repeating if isinstance(self.n_cubes, Iterable): n_cubes = np.array(self.n_cubes) assert ( len(n_cubes) == n_dims ), "Custom cubes in each dimension must match number of dimensions" else: n_cubes = np.repeat(self.n_cubes, n_dims) if isinstance(self.perc_overlap, Iterable): perc_overlap = np.array(self.perc_overlap) assert ( len(perc_overlap) == n_dims ), "Custom cubes in each dimension must match number of dimensions" else: perc_overlap = np.repeat(self.perc_overlap, n_dims) assert all(0.0 <= p <= 1.0 for p in perc_overlap), ( "Each overlap percentage must be between 0.0 and 1.0., not %s" % perc_overlap ) bounds = self._compute_bounds(indexless_data) ranges = bounds[1] - bounds[0] # (n-1)/n |range| inner_range = ((n_cubes - 1) / n_cubes) * ranges inset = (ranges - inner_range) / 2 # |range| / (2n ( 1 - p)) radius = ranges / (2 * (n_cubes) * (1 - perc_overlap)) # centers are fixed w.r.t perc_overlap zip_items = list(bounds) # work around 2.7,3.4 weird behavior zip_items.extend([n_cubes, inset]) centers_per_dimension = [ np.linspace(b + r, c - r, num=n) for b, c, n, r in zip(*zip_items) ] centers = [np.array(c) for c in product(*centers_per_dimension)] self.centers_ = centers self.radius_ = radius self.inset_ = inset self.inner_range_ = inner_range self.bounds_ = bounds self.di_ = di if self.verbose > 0: print( " - Cover - centers: %s\ninner_range: %s\nradius: %s" % (self.centers_, self.inner_range_, self.radius_) ) return centers
python
def fit(self, data): # TODO: support indexing into any columns di = np.array(range(1, data.shape[1])) indexless_data = data[:, di] n_dims = indexless_data.shape[1] # support different values along each dimension ## -- is a list, needs to be array ## -- is a singleton, needs repeating if isinstance(self.n_cubes, Iterable): n_cubes = np.array(self.n_cubes) assert ( len(n_cubes) == n_dims ), "Custom cubes in each dimension must match number of dimensions" else: n_cubes = np.repeat(self.n_cubes, n_dims) if isinstance(self.perc_overlap, Iterable): perc_overlap = np.array(self.perc_overlap) assert ( len(perc_overlap) == n_dims ), "Custom cubes in each dimension must match number of dimensions" else: perc_overlap = np.repeat(self.perc_overlap, n_dims) assert all(0.0 <= p <= 1.0 for p in perc_overlap), ( "Each overlap percentage must be between 0.0 and 1.0., not %s" % perc_overlap ) bounds = self._compute_bounds(indexless_data) ranges = bounds[1] - bounds[0] # (n-1)/n |range| inner_range = ((n_cubes - 1) / n_cubes) * ranges inset = (ranges - inner_range) / 2 # |range| / (2n ( 1 - p)) radius = ranges / (2 * (n_cubes) * (1 - perc_overlap)) # centers are fixed w.r.t perc_overlap zip_items = list(bounds) # work around 2.7,3.4 weird behavior zip_items.extend([n_cubes, inset]) centers_per_dimension = [ np.linspace(b + r, c - r, num=n) for b, c, n, r in zip(*zip_items) ] centers = [np.array(c) for c in product(*centers_per_dimension)] self.centers_ = centers self.radius_ = radius self.inset_ = inset self.inner_range_ = inner_range self.bounds_ = bounds self.di_ = di if self.verbose > 0: print( " - Cover - centers: %s\ninner_range: %s\nradius: %s" % (self.centers_, self.inner_range_, self.radius_) ) return centers
[ "def", "fit", "(", "self", ",", "data", ")", ":", "# TODO: support indexing into any columns", "di", "=", "np", ".", "array", "(", "range", "(", "1", ",", "data", ".", "shape", "[", "1", "]", ")", ")", "indexless_data", "=", "data", "[", ":", ",", "d...
Fit a cover on the data. This method constructs centers and radii in each dimension given the `perc_overlap` and `n_cube`. Parameters ============ data: array-like Data to apply the cover to. Warning: First column must be an index column. Returns ======== centers: list of arrays A list of centers for each cube
[ "Fit", "a", "cover", "on", "the", "data", ".", "This", "method", "constructs", "centers", "and", "radii", "in", "each", "dimension", "given", "the", "perc_overlap", "and", "n_cube", "." ]
d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d
https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/cover.py#L135-L214
235,803
scikit-tda/kepler-mapper
kmapper/cover.py
Cover.transform_single
def transform_single(self, data, center, i=0): """ Compute entries of `data` in hypercube centered at `center` Parameters =========== data: array-like Data to find in entries in cube. Warning: first column must be index column. center: array-like Center points for the cube. Cube is found as all data in `[center-self.radius_, center+self.radius_]` i: int, default 0 Optional counter to aid in verbose debugging. """ lowerbounds, upperbounds = center - self.radius_, center + self.radius_ # Slice the hypercube entries = (data[:, self.di_] >= lowerbounds) & ( data[:, self.di_] <= upperbounds ) hypercube = data[np.invert(np.any(entries == False, axis=1))] if self.verbose > 1: print( "There are %s points in cube %s/%s" % (hypercube.shape[0], i + 1, len(self.centers_)) ) return hypercube
python
def transform_single(self, data, center, i=0): lowerbounds, upperbounds = center - self.radius_, center + self.radius_ # Slice the hypercube entries = (data[:, self.di_] >= lowerbounds) & ( data[:, self.di_] <= upperbounds ) hypercube = data[np.invert(np.any(entries == False, axis=1))] if self.verbose > 1: print( "There are %s points in cube %s/%s" % (hypercube.shape[0], i + 1, len(self.centers_)) ) return hypercube
[ "def", "transform_single", "(", "self", ",", "data", ",", "center", ",", "i", "=", "0", ")", ":", "lowerbounds", ",", "upperbounds", "=", "center", "-", "self", ".", "radius_", ",", "center", "+", "self", ".", "radius_", "# Slice the hypercube", "entries",...
Compute entries of `data` in hypercube centered at `center` Parameters =========== data: array-like Data to find in entries in cube. Warning: first column must be index column. center: array-like Center points for the cube. Cube is found as all data in `[center-self.radius_, center+self.radius_]` i: int, default 0 Optional counter to aid in verbose debugging.
[ "Compute", "entries", "of", "data", "in", "hypercube", "centered", "at", "center" ]
d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d
https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/cover.py#L216-L244
235,804
scikit-tda/kepler-mapper
kmapper/cover.py
Cover.transform
def transform(self, data, centers=None): """ Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`. Empty hypercubes are removed from the result Parameters =========== data: array-like Data to find in entries in cube. Warning: first column must be index column. centers: list of array-like Center points for all cubes as returned by `self.fit`. Default is to use `self.centers_`. Returns ========= hypercubes: list of array-like list of entries in each hypercobe in `data`. """ centers = centers or self.centers_ hypercubes = [ self.transform_single(data, cube, i) for i, cube in enumerate(centers) ] # Clean out any empty cubes (common in high dimensions) hypercubes = [cube for cube in hypercubes if len(cube)] return hypercubes
python
def transform(self, data, centers=None): centers = centers or self.centers_ hypercubes = [ self.transform_single(data, cube, i) for i, cube in enumerate(centers) ] # Clean out any empty cubes (common in high dimensions) hypercubes = [cube for cube in hypercubes if len(cube)] return hypercubes
[ "def", "transform", "(", "self", ",", "data", ",", "centers", "=", "None", ")", ":", "centers", "=", "centers", "or", "self", ".", "centers_", "hypercubes", "=", "[", "self", ".", "transform_single", "(", "data", ",", "cube", ",", "i", ")", "for", "i...
Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`. Empty hypercubes are removed from the result Parameters =========== data: array-like Data to find in entries in cube. Warning: first column must be index column. centers: list of array-like Center points for all cubes as returned by `self.fit`. Default is to use `self.centers_`. Returns ========= hypercubes: list of array-like list of entries in each hypercobe in `data`.
[ "Find", "entries", "of", "all", "hypercubes", ".", "If", "centers", "=", "None", "then", "use", "self", ".", "centers_", "as", "computed", "in", "self", ".", "fit", ".", "Empty", "hypercubes", "are", "removed", "from", "the", "result" ]
d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d
https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/cover.py#L246-L273
235,805
scikit-tda/kepler-mapper
kmapper/adapter.py
to_networkx
def to_networkx(graph): """ Convert a Mapper 1-complex to a networkx graph. Parameters ----------- graph: dictionary, graph object returned from `kmapper.map` Returns -------- g: graph as networkx.Graph() object """ # import here so networkx is not always required. import networkx as nx nodes = graph["nodes"].keys() edges = [[start, end] for start, ends in graph["links"].items() for end in ends] g = nx.Graph() g.add_nodes_from(nodes) nx.set_node_attributes(g, dict(graph["nodes"]), "membership") g.add_edges_from(edges) return g
python
def to_networkx(graph): # import here so networkx is not always required. import networkx as nx nodes = graph["nodes"].keys() edges = [[start, end] for start, ends in graph["links"].items() for end in ends] g = nx.Graph() g.add_nodes_from(nodes) nx.set_node_attributes(g, dict(graph["nodes"]), "membership") g.add_edges_from(edges) return g
[ "def", "to_networkx", "(", "graph", ")", ":", "# import here so networkx is not always required.", "import", "networkx", "as", "nx", "nodes", "=", "graph", "[", "\"nodes\"", "]", ".", "keys", "(", ")", "edges", "=", "[", "[", "start", ",", "end", "]", "for",...
Convert a Mapper 1-complex to a networkx graph. Parameters ----------- graph: dictionary, graph object returned from `kmapper.map` Returns -------- g: graph as networkx.Graph() object
[ "Convert", "a", "Mapper", "1", "-", "complex", "to", "a", "networkx", "graph", "." ]
d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d
https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/adapter.py#L8-L35
235,806
PyThaiNLP/pythainlp
pythainlp/corpus/__init__.py
get_corpus
def get_corpus(filename: str) -> frozenset: """ Read corpus from file and return a frozenset :param string filename: file corpus """ lines = [] with open(os.path.join(corpus_path(), filename), "r", encoding="utf-8-sig") as fh: lines = fh.read().splitlines() return frozenset(lines)
python
def get_corpus(filename: str) -> frozenset: lines = [] with open(os.path.join(corpus_path(), filename), "r", encoding="utf-8-sig") as fh: lines = fh.read().splitlines() return frozenset(lines)
[ "def", "get_corpus", "(", "filename", ":", "str", ")", "->", "frozenset", ":", "lines", "=", "[", "]", "with", "open", "(", "os", ".", "path", ".", "join", "(", "corpus_path", "(", ")", ",", "filename", ")", ",", "\"r\"", ",", "encoding", "=", "\"u...
Read corpus from file and return a frozenset :param string filename: file corpus
[ "Read", "corpus", "from", "file", "and", "return", "a", "frozenset" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/corpus/__init__.py#L41-L51
235,807
PyThaiNLP/pythainlp
pythainlp/corpus/__init__.py
get_corpus_path
def get_corpus_path(name: str) -> [str, None]: """ Get corpus path :param string name: corpus name """ db = TinyDB(corpus_db_path()) temp = Query() if len(db.search(temp.name == name)) > 0: path = get_full_data_path(db.search(temp.name == name)[0]["file"]) db.close() if not os.path.exists(path): download(name) return path return None
python
def get_corpus_path(name: str) -> [str, None]: db = TinyDB(corpus_db_path()) temp = Query() if len(db.search(temp.name == name)) > 0: path = get_full_data_path(db.search(temp.name == name)[0]["file"]) db.close() if not os.path.exists(path): download(name) return path return None
[ "def", "get_corpus_path", "(", "name", ":", "str", ")", "->", "[", "str", ",", "None", "]", ":", "db", "=", "TinyDB", "(", "corpus_db_path", "(", ")", ")", "temp", "=", "Query", "(", ")", "if", "len", "(", "db", ".", "search", "(", "temp", ".", ...
Get corpus path :param string name: corpus name
[ "Get", "corpus", "path" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/corpus/__init__.py#L54-L72
235,808
PyThaiNLP/pythainlp
pythainlp/summarize/__init__.py
summarize
def summarize( text: str, n: int, engine: str = "frequency", tokenizer: str = "newmm" ) -> List[str]: """ Thai text summarization :param str text: text to be summarized :param int n: number of sentences to be included in the summary :param str engine: text summarization engine :param str tokenizer: word tokenizer :return List[str] summary: list of selected sentences """ sents = [] if engine == "frequency": sents = FrequencySummarizer().summarize(text, n, tokenizer) else: # if engine not found, return first n sentences sents = sent_tokenize(text)[:n] return sents
python
def summarize( text: str, n: int, engine: str = "frequency", tokenizer: str = "newmm" ) -> List[str]: sents = [] if engine == "frequency": sents = FrequencySummarizer().summarize(text, n, tokenizer) else: # if engine not found, return first n sentences sents = sent_tokenize(text)[:n] return sents
[ "def", "summarize", "(", "text", ":", "str", ",", "n", ":", "int", ",", "engine", ":", "str", "=", "\"frequency\"", ",", "tokenizer", ":", "str", "=", "\"newmm\"", ")", "->", "List", "[", "str", "]", ":", "sents", "=", "[", "]", "if", "engine", "...
Thai text summarization :param str text: text to be summarized :param int n: number of sentences to be included in the summary :param str engine: text summarization engine :param str tokenizer: word tokenizer :return List[str] summary: list of selected sentences
[ "Thai", "text", "summarization" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/summarize/__init__.py#L13-L32
235,809
PyThaiNLP/pythainlp
pythainlp/corpus/conceptnet.py
edges
def edges(word: str, lang: str = "th"): """ Get edges from ConceptNet API :param str word: word :param str lang: language """ obj = requests.get(f"http://api.conceptnet.io/c/{lang}/{word}").json() return obj["edges"]
python
def edges(word: str, lang: str = "th"): obj = requests.get(f"http://api.conceptnet.io/c/{lang}/{word}").json() return obj["edges"]
[ "def", "edges", "(", "word", ":", "str", ",", "lang", ":", "str", "=", "\"th\"", ")", ":", "obj", "=", "requests", ".", "get", "(", "f\"http://api.conceptnet.io/c/{lang}/{word}\"", ")", ".", "json", "(", ")", "return", "obj", "[", "\"edges\"", "]" ]
Get edges from ConceptNet API :param str word: word :param str lang: language
[ "Get", "edges", "from", "ConceptNet", "API" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/corpus/conceptnet.py#L8-L17
235,810
PyThaiNLP/pythainlp
pythainlp/util/wordtonum.py
thaiword_to_num
def thaiword_to_num(word: str) -> int: """ Converts a Thai number spellout word to actual number value :param str word: a Thai number spellout :return: number """ if not word: return None tokens = [] if isinstance(word, str): tokens = _TOKENIZER.word_tokenize(word) elif isinstance(word, Iterable): for w in word: tokens.extend(_TOKENIZER.word_tokenize(w)) res = [] for tok in tokens: if tok in _THAIWORD_NUMS_UNITS: res.append(tok) else: m = _NU_PAT.fullmatch(tok) if m: res.extend([t for t in m.groups() if t]) # ตัด None ทิ้ง else: pass # should not be here return _thaiword_to_num(res)
python
def thaiword_to_num(word: str) -> int: if not word: return None tokens = [] if isinstance(word, str): tokens = _TOKENIZER.word_tokenize(word) elif isinstance(word, Iterable): for w in word: tokens.extend(_TOKENIZER.word_tokenize(w)) res = [] for tok in tokens: if tok in _THAIWORD_NUMS_UNITS: res.append(tok) else: m = _NU_PAT.fullmatch(tok) if m: res.extend([t for t in m.groups() if t]) # ตัด None ทิ้ง else: pass # should not be here return _thaiword_to_num(res)
[ "def", "thaiword_to_num", "(", "word", ":", "str", ")", "->", "int", ":", "if", "not", "word", ":", "return", "None", "tokens", "=", "[", "]", "if", "isinstance", "(", "word", ",", "str", ")", ":", "tokens", "=", "_TOKENIZER", ".", "word_tokenize", "...
Converts a Thai number spellout word to actual number value :param str word: a Thai number spellout :return: number
[ "Converts", "a", "Thai", "number", "spellout", "word", "to", "actual", "number", "value" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/util/wordtonum.py#L69-L97
235,811
PyThaiNLP/pythainlp
pythainlp/tag/__init__.py
pos_tag
def pos_tag( words: List[str], engine: str = "perceptron", corpus: str = "orchid" ) -> List[Tuple[str, str]]: """ Part of Speech tagging function. :param list words: a list of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) * artagger - RDR POS tagger :param str corpus: * orchid - annotated Thai academic articles (default) * orchid_ud - annotated Thai academic articles using Universal Dependencies Tags * pud - Parallel Universal Dependencies (PUD) treebanks :return: returns a list of labels regarding which part of speech it is """ _corpus = corpus _tag = [] if corpus == "orchid_ud": corpus = "orchid" if not words: return [] if engine == "perceptron": from .perceptron import tag as tag_ elif engine == "artagger": tag_ = _artagger_tag else: # default, use "unigram" ("old") engine from .unigram import tag as tag_ _tag = tag_(words, corpus=corpus) if _corpus == "orchid_ud": _tag = _orchid_to_ud(_tag) return _tag
python
def pos_tag( words: List[str], engine: str = "perceptron", corpus: str = "orchid" ) -> List[Tuple[str, str]]: _corpus = corpus _tag = [] if corpus == "orchid_ud": corpus = "orchid" if not words: return [] if engine == "perceptron": from .perceptron import tag as tag_ elif engine == "artagger": tag_ = _artagger_tag else: # default, use "unigram" ("old") engine from .unigram import tag as tag_ _tag = tag_(words, corpus=corpus) if _corpus == "orchid_ud": _tag = _orchid_to_ud(_tag) return _tag
[ "def", "pos_tag", "(", "words", ":", "List", "[", "str", "]", ",", "engine", ":", "str", "=", "\"perceptron\"", ",", "corpus", ":", "str", "=", "\"orchid\"", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "_corpus", "=", ...
Part of Speech tagging function. :param list words: a list of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) * artagger - RDR POS tagger :param str corpus: * orchid - annotated Thai academic articles (default) * orchid_ud - annotated Thai academic articles using Universal Dependencies Tags * pud - Parallel Universal Dependencies (PUD) treebanks :return: returns a list of labels regarding which part of speech it is
[ "Part", "of", "Speech", "tagging", "function", "." ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/__init__.py#L122-L157
235,812
PyThaiNLP/pythainlp
pythainlp/tag/__init__.py
pos_tag_sents
def pos_tag_sents( sentences: List[List[str]], engine: str = "perceptron", corpus: str = "orchid" ) -> List[List[Tuple[str, str]]]: """ Part of Speech tagging Sentence function. :param list sentences: a list of lists of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) * artagger - RDR POS tagger :param str corpus: * orchid - annotated Thai academic articles (default) * orchid_ud - annotated Thai academic articles using Universal Dependencies Tags * pud - Parallel Universal Dependencies (PUD) treebanks :return: returns a list of labels regarding which part of speech it is """ if not sentences: return [] return [pos_tag(sent, engine=engine, corpus=corpus) for sent in sentences]
python
def pos_tag_sents( sentences: List[List[str]], engine: str = "perceptron", corpus: str = "orchid" ) -> List[List[Tuple[str, str]]]: if not sentences: return [] return [pos_tag(sent, engine=engine, corpus=corpus) for sent in sentences]
[ "def", "pos_tag_sents", "(", "sentences", ":", "List", "[", "List", "[", "str", "]", "]", ",", "engine", ":", "str", "=", "\"perceptron\"", ",", "corpus", ":", "str", "=", "\"orchid\"", ")", "->", "List", "[", "List", "[", "Tuple", "[", "str", ",", ...
Part of Speech tagging Sentence function. :param list sentences: a list of lists of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) * artagger - RDR POS tagger :param str corpus: * orchid - annotated Thai academic articles (default) * orchid_ud - annotated Thai academic articles using Universal Dependencies Tags * pud - Parallel Universal Dependencies (PUD) treebanks :return: returns a list of labels regarding which part of speech it is
[ "Part", "of", "Speech", "tagging", "Sentence", "function", "." ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/__init__.py#L160-L180
235,813
PyThaiNLP/pythainlp
pythainlp/spell/pn.py
_keep
def _keep( word_freq: int, min_freq: int, min_len: int, max_len: int, dict_filter: Callable[[str], bool], ): """ Keep only Thai words with at least min_freq frequency and has length between min_len and max_len characters """ if not word_freq or word_freq[1] < min_freq: return False word = word_freq[0] if not word or len(word) < min_len or len(word) > max_len or word[0] == ".": return False return dict_filter(word)
python
def _keep( word_freq: int, min_freq: int, min_len: int, max_len: int, dict_filter: Callable[[str], bool], ): if not word_freq or word_freq[1] < min_freq: return False word = word_freq[0] if not word or len(word) < min_len or len(word) > max_len or word[0] == ".": return False return dict_filter(word)
[ "def", "_keep", "(", "word_freq", ":", "int", ",", "min_freq", ":", "int", ",", "min_len", ":", "int", ",", "max_len", ":", "int", ",", "dict_filter", ":", "Callable", "[", "[", "str", "]", ",", "bool", "]", ",", ")", ":", "if", "not", "word_freq",...
Keep only Thai words with at least min_freq frequency and has length between min_len and max_len characters
[ "Keep", "only", "Thai", "words", "with", "at", "least", "min_freq", "frequency", "and", "has", "length", "between", "min_len", "and", "max_len", "characters" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L31-L49
235,814
PyThaiNLP/pythainlp
pythainlp/spell/pn.py
_edits1
def _edits1(word: str) -> Set[str]: """ Return a set of words with edit distance of 1 from the input word """ splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1] replaces = [L + c + R[1:] for L, R in splits if R for c in thai_letters] inserts = [L + c + R for L, R in splits for c in thai_letters] return set(deletes + transposes + replaces + inserts)
python
def _edits1(word: str) -> Set[str]: splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1] replaces = [L + c + R[1:] for L, R in splits if R for c in thai_letters] inserts = [L + c + R for L, R in splits for c in thai_letters] return set(deletes + transposes + replaces + inserts)
[ "def", "_edits1", "(", "word", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "splits", "=", "[", "(", "word", "[", ":", "i", "]", ",", "word", "[", "i", ":", "]", ")", "for", "i", "in", "range", "(", "len", "(", "word", ")", "+", "1...
Return a set of words with edit distance of 1 from the input word
[ "Return", "a", "set", "of", "words", "with", "edit", "distance", "of", "1", "from", "the", "input", "word" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L52-L62
235,815
PyThaiNLP/pythainlp
pythainlp/spell/pn.py
_edits2
def _edits2(word: str) -> Set[str]: """ Return a set of words with edit distance of 2 from the input word """ return set(e2 for e1 in _edits1(word) for e2 in _edits1(e1))
python
def _edits2(word: str) -> Set[str]: return set(e2 for e1 in _edits1(word) for e2 in _edits1(e1))
[ "def", "_edits2", "(", "word", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "return", "set", "(", "e2", "for", "e1", "in", "_edits1", "(", "word", ")", "for", "e2", "in", "_edits1", "(", "e1", ")", ")" ]
Return a set of words with edit distance of 2 from the input word
[ "Return", "a", "set", "of", "words", "with", "edit", "distance", "of", "2", "from", "the", "input", "word" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L65-L69
235,816
PyThaiNLP/pythainlp
pythainlp/spell/pn.py
NorvigSpellChecker.known
def known(self, words: List[str]) -> List[str]: """ Return a list of given words that found in the spelling dictionary :param str words: A list of words to check if they are in the spelling dictionary """ return list(w for w in words if w in self.__WORDS)
python
def known(self, words: List[str]) -> List[str]: return list(w for w in words if w in self.__WORDS)
[ "def", "known", "(", "self", ",", "words", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "return", "list", "(", "w", "for", "w", "in", "words", "if", "w", "in", "self", ".", "__WORDS", ")" ]
Return a list of given words that found in the spelling dictionary :param str words: A list of words to check if they are in the spelling dictionary
[ "Return", "a", "list", "of", "given", "words", "that", "found", "in", "the", "spelling", "dictionary" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L114-L120
235,817
PyThaiNLP/pythainlp
pythainlp/spell/pn.py
NorvigSpellChecker.prob
def prob(self, word: str) -> float: """ Return probability of an input word, according to the spelling dictionary :param str word: A word to check its probability of occurrence """ return self.__WORDS[word] / self.__WORDS_TOTAL
python
def prob(self, word: str) -> float: return self.__WORDS[word] / self.__WORDS_TOTAL
[ "def", "prob", "(", "self", ",", "word", ":", "str", ")", "->", "float", ":", "return", "self", ".", "__WORDS", "[", "word", "]", "/", "self", ".", "__WORDS_TOTAL" ]
Return probability of an input word, according to the spelling dictionary :param str word: A word to check its probability of occurrence
[ "Return", "probability", "of", "an", "input", "word", "according", "to", "the", "spelling", "dictionary" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L122-L128
235,818
PyThaiNLP/pythainlp
pythainlp/spell/pn.py
NorvigSpellChecker.spell
def spell(self, word: str) -> List[str]: """ Return a list of possible words, according to edit distance of 1 and 2, sorted by frequency of word occurrance in the spelling dictionary :param str word: A word to check its spelling """ if not word: return "" candidates = ( self.known([word]) or self.known(_edits1(word)) or self.known(_edits2(word)) or [word] ) candidates.sort(key=self.freq, reverse=True) return candidates
python
def spell(self, word: str) -> List[str]: if not word: return "" candidates = ( self.known([word]) or self.known(_edits1(word)) or self.known(_edits2(word)) or [word] ) candidates.sort(key=self.freq, reverse=True) return candidates
[ "def", "spell", "(", "self", ",", "word", ":", "str", ")", "->", "List", "[", "str", "]", ":", "if", "not", "word", ":", "return", "\"\"", "candidates", "=", "(", "self", ".", "known", "(", "[", "word", "]", ")", "or", "self", ".", "known", "("...
Return a list of possible words, according to edit distance of 1 and 2, sorted by frequency of word occurrance in the spelling dictionary :param str word: A word to check its spelling
[ "Return", "a", "list", "of", "possible", "words", "according", "to", "edit", "distance", "of", "1", "and", "2", "sorted", "by", "frequency", "of", "word", "occurrance", "in", "the", "spelling", "dictionary" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/spell/pn.py#L138-L156
235,819
PyThaiNLP/pythainlp
pythainlp/tokenize/__init__.py
sent_tokenize
def sent_tokenize(text: str, engine: str = "whitespace+newline") -> List[str]: """ This function does not yet automatically recognize when a sentence actually ends. Rather it helps split text where white space and a new line is found. :param str text: the text to be tokenized :param str engine: choose between 'whitespace' or 'whitespace+newline' :return: list of sentences """ if not text or not isinstance(text, str): return [] sentences = [] if engine == "whitespace": sentences = re.split(r" +", text, re.U) else: # default, use whitespace + newline sentences = text.split() return sentences
python
def sent_tokenize(text: str, engine: str = "whitespace+newline") -> List[str]: if not text or not isinstance(text, str): return [] sentences = [] if engine == "whitespace": sentences = re.split(r" +", text, re.U) else: # default, use whitespace + newline sentences = text.split() return sentences
[ "def", "sent_tokenize", "(", "text", ":", "str", ",", "engine", ":", "str", "=", "\"whitespace+newline\"", ")", "->", "List", "[", "str", "]", ":", "if", "not", "text", "or", "not", "isinstance", "(", "text", ",", "str", ")", ":", "return", "[", "]",...
This function does not yet automatically recognize when a sentence actually ends. Rather it helps split text where white space and a new line is found. :param str text: the text to be tokenized :param str engine: choose between 'whitespace' or 'whitespace+newline' :return: list of sentences
[ "This", "function", "does", "not", "yet", "automatically", "recognize", "when", "a", "sentence", "actually", "ends", ".", "Rather", "it", "helps", "split", "text", "where", "white", "space", "and", "a", "new", "line", "is", "found", "." ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tokenize/__init__.py#L115-L135
235,820
PyThaiNLP/pythainlp
pythainlp/tag/locations.py
tag_provinces
def tag_provinces(tokens: List[str]) -> List[Tuple[str, str]]: """ Recognize Thailand provinces in text Input is a list of words Return a list of tuples Example:: >>> text = ['หนองคาย', 'น่าอยู่'] >>> tag_provinces(text) [('หนองคาย', 'B-LOCATION'), ('น่าอยู่', 'O')] """ province_list = provinces() output = [] for token in tokens: if token in province_list: output.append((token, "B-LOCATION")) else: output.append((token, "O")) return output
python
def tag_provinces(tokens: List[str]) -> List[Tuple[str, str]]: province_list = provinces() output = [] for token in tokens: if token in province_list: output.append((token, "B-LOCATION")) else: output.append((token, "O")) return output
[ "def", "tag_provinces", "(", "tokens", ":", "List", "[", "str", "]", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "province_list", "=", "provinces", "(", ")", "output", "=", "[", "]", "for", "token", "in", "tokens", ":", ...
Recognize Thailand provinces in text Input is a list of words Return a list of tuples Example:: >>> text = ['หนองคาย', 'น่าอยู่'] >>> tag_provinces(text) [('หนองคาย', 'B-LOCATION'), ('น่าอยู่', 'O')]
[ "Recognize", "Thailand", "provinces", "in", "text" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/locations.py#L11-L32
235,821
PyThaiNLP/pythainlp
pythainlp/tag/named_entity.py
ThaiNameTagger.get_ner
def get_ner( self, text: str, pos: bool = True ) -> Union[List[Tuple[str, str]], List[Tuple[str, str, str]]]: """ Get named-entities in text :param string text: Thai text :param boolean pos: get Part-Of-Speech tag (True) or get not (False) :return: list of strings with name labels (and part-of-speech tags) **Example**:: >>> from pythainlp.tag.named_entity import ThaiNameTagger >>> ner = ThaiNameTagger() >>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.") [('วันที่', 'NOUN', 'O'), (' ', 'PUNCT', 'O'), ('15', 'NUM', 'B-DATE'), (' ', 'PUNCT', 'I-DATE'), ('ก.ย.', 'NOUN', 'I-DATE'), (' ', 'PUNCT', 'I-DATE'), ('61', 'NUM', 'I-DATE'), (' ', 'PUNCT', 'O'), ('ทดสอบ', 'VERB', 'O'), ('ระบบ', 'NOUN', 'O'), ('เวลา', 'NOUN', 'O'), (' ', 'PUNCT', 'O'), ('14', 'NOUN', 'B-TIME'), (':', 'PUNCT', 'I-TIME'), ('49', 'NUM', 'I-TIME'), (' ', 'PUNCT', 'I-TIME'), ('น.', 'NOUN', 'I-TIME')] >>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.", pos=False) [('วันที่', 'O'), (' ', 'O'), ('15', 'B-DATE'), (' ', 'I-DATE'), ('ก.ย.', 'I-DATE'), (' ', 'I-DATE'), ('61', 'I-DATE'), (' ', 'O'), ('ทดสอบ', 'O'), ('ระบบ', 'O'), ('เวลา', 'O'), (' ', 'O'), ('14', 'B-TIME'), (':', 'I-TIME'), ('49', 'I-TIME'), (' ', 'I-TIME'), ('น.', 'I-TIME')] """ self.__tokens = word_tokenize(text, engine=_WORD_TOKENIZER) self.__pos_tags = pos_tag( self.__tokens, engine="perceptron", corpus="orchid_ud" ) self.__x_test = self.__extract_features(self.__pos_tags) self.__y = self.crf.predict_single(self.__x_test) if pos: return [ (self.__pos_tags[i][0], self.__pos_tags[i][1], data) for i, data in enumerate(self.__y) ] return [(self.__pos_tags[i][0], data) for i, data in enumerate(self.__y)]
python
def get_ner( self, text: str, pos: bool = True ) -> Union[List[Tuple[str, str]], List[Tuple[str, str, str]]]: self.__tokens = word_tokenize(text, engine=_WORD_TOKENIZER) self.__pos_tags = pos_tag( self.__tokens, engine="perceptron", corpus="orchid_ud" ) self.__x_test = self.__extract_features(self.__pos_tags) self.__y = self.crf.predict_single(self.__x_test) if pos: return [ (self.__pos_tags[i][0], self.__pos_tags[i][1], data) for i, data in enumerate(self.__y) ] return [(self.__pos_tags[i][0], data) for i, data in enumerate(self.__y)]
[ "def", "get_ner", "(", "self", ",", "text", ":", "str", ",", "pos", ":", "bool", "=", "True", ")", "->", "Union", "[", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "List", "[", "Tuple", "[", "str", ",", "str", ",", "str", "]",...
Get named-entities in text :param string text: Thai text :param boolean pos: get Part-Of-Speech tag (True) or get not (False) :return: list of strings with name labels (and part-of-speech tags) **Example**:: >>> from pythainlp.tag.named_entity import ThaiNameTagger >>> ner = ThaiNameTagger() >>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.") [('วันที่', 'NOUN', 'O'), (' ', 'PUNCT', 'O'), ('15', 'NUM', 'B-DATE'), (' ', 'PUNCT', 'I-DATE'), ('ก.ย.', 'NOUN', 'I-DATE'), (' ', 'PUNCT', 'I-DATE'), ('61', 'NUM', 'I-DATE'), (' ', 'PUNCT', 'O'), ('ทดสอบ', 'VERB', 'O'), ('ระบบ', 'NOUN', 'O'), ('เวลา', 'NOUN', 'O'), (' ', 'PUNCT', 'O'), ('14', 'NOUN', 'B-TIME'), (':', 'PUNCT', 'I-TIME'), ('49', 'NUM', 'I-TIME'), (' ', 'PUNCT', 'I-TIME'), ('น.', 'NOUN', 'I-TIME')] >>> ner.get_ner("วันที่ 15 ก.ย. 61 ทดสอบระบบเวลา 14:49 น.", pos=False) [('วันที่', 'O'), (' ', 'O'), ('15', 'B-DATE'), (' ', 'I-DATE'), ('ก.ย.', 'I-DATE'), (' ', 'I-DATE'), ('61', 'I-DATE'), (' ', 'O'), ('ทดสอบ', 'O'), ('ระบบ', 'O'), ('เวลา', 'O'), (' ', 'O'), ('14', 'B-TIME'), (':', 'I-TIME'), ('49', 'I-TIME'), (' ', 'I-TIME'), ('น.', 'I-TIME')]
[ "Get", "named", "-", "entities", "in", "text" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tag/named_entity.py#L92-L133
235,822
PyThaiNLP/pythainlp
pythainlp/tokenize/multi_cut.py
find_all_segment
def find_all_segment(text: str, custom_dict: Trie = None) -> List[str]: """ Get all possible segment variations :param str text: input string to be tokenized :return: returns list of segment variations """ if not text or not isinstance(text, str): return [] ww = list(_multicut(text, custom_dict=custom_dict)) return list(_combine(ww))
python
def find_all_segment(text: str, custom_dict: Trie = None) -> List[str]: if not text or not isinstance(text, str): return [] ww = list(_multicut(text, custom_dict=custom_dict)) return list(_combine(ww))
[ "def", "find_all_segment", "(", "text", ":", "str", ",", "custom_dict", ":", "Trie", "=", "None", ")", "->", "List", "[", "str", "]", ":", "if", "not", "text", "or", "not", "isinstance", "(", "text", ",", "str", ")", ":", "return", "[", "]", "ww", ...
Get all possible segment variations :param str text: input string to be tokenized :return: returns list of segment variations
[ "Get", "all", "possible", "segment", "variations" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tokenize/multi_cut.py#L131-L143
235,823
PyThaiNLP/pythainlp
pythainlp/util/date.py
reign_year_to_ad
def reign_year_to_ad(reign_year: int, reign: int) -> int: """ Reign year of Chakri dynasty, Thailand """ if int(reign) == 10: ad = int(reign_year) + 2015 elif int(reign) == 9: ad = int(reign_year) + 1945 elif int(reign) == 8: ad = int(reign_year) + 1928 elif int(reign) == 7: ad = int(reign_year) + 1924 return ad
python
def reign_year_to_ad(reign_year: int, reign: int) -> int: if int(reign) == 10: ad = int(reign_year) + 2015 elif int(reign) == 9: ad = int(reign_year) + 1945 elif int(reign) == 8: ad = int(reign_year) + 1928 elif int(reign) == 7: ad = int(reign_year) + 1924 return ad
[ "def", "reign_year_to_ad", "(", "reign_year", ":", "int", ",", "reign", ":", "int", ")", "->", "int", ":", "if", "int", "(", "reign", ")", "==", "10", ":", "ad", "=", "int", "(", "reign_year", ")", "+", "2015", "elif", "int", "(", "reign", ")", "...
Reign year of Chakri dynasty, Thailand
[ "Reign", "year", "of", "Chakri", "dynasty", "Thailand" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/util/date.py#L281-L293
235,824
PyThaiNLP/pythainlp
pythainlp/word_vector/__init__.py
most_similar_cosmul
def most_similar_cosmul(positive: List[str], negative: List[str]): """ Word arithmetic operations If a word is not in the vocabulary, KeyError will be raised. :param list positive: a list of words to add :param list negative: a list of words to substract :return: the cosine similarity between the two word vectors """ return _MODEL.most_similar_cosmul(positive=positive, negative=negative)
python
def most_similar_cosmul(positive: List[str], negative: List[str]): return _MODEL.most_similar_cosmul(positive=positive, negative=negative)
[ "def", "most_similar_cosmul", "(", "positive", ":", "List", "[", "str", "]", ",", "negative", ":", "List", "[", "str", "]", ")", ":", "return", "_MODEL", ".", "most_similar_cosmul", "(", "positive", "=", "positive", ",", "negative", "=", "negative", ")" ]
Word arithmetic operations If a word is not in the vocabulary, KeyError will be raised. :param list positive: a list of words to add :param list negative: a list of words to substract :return: the cosine similarity between the two word vectors
[ "Word", "arithmetic", "operations", "If", "a", "word", "is", "not", "in", "the", "vocabulary", "KeyError", "will", "be", "raised", "." ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/word_vector/__init__.py#L38-L49
235,825
PyThaiNLP/pythainlp
pythainlp/word_vector/__init__.py
similarity
def similarity(word1: str, word2: str) -> float: """ Get cosine similarity between two words. If a word is not in the vocabulary, KeyError will be raised. :param string word1: first word :param string word2: second word :return: the cosine similarity between the two word vectors """ return _MODEL.similarity(word1, word2)
python
def similarity(word1: str, word2: str) -> float: return _MODEL.similarity(word1, word2)
[ "def", "similarity", "(", "word1", ":", "str", ",", "word2", ":", "str", ")", "->", "float", ":", "return", "_MODEL", ".", "similarity", "(", "word1", ",", "word2", ")" ]
Get cosine similarity between two words. If a word is not in the vocabulary, KeyError will be raised. :param string word1: first word :param string word2: second word :return: the cosine similarity between the two word vectors
[ "Get", "cosine", "similarity", "between", "two", "words", ".", "If", "a", "word", "is", "not", "in", "the", "vocabulary", "KeyError", "will", "be", "raised", "." ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/word_vector/__init__.py#L63-L72
235,826
PyThaiNLP/pythainlp
pythainlp/word_vector/__init__.py
sentence_vectorizer
def sentence_vectorizer(text: str, use_mean: bool = True): """ Get sentence vector from text If a word is not in the vocabulary, KeyError will be raised. :param string text: text input :param boolean use_mean: if `True` use mean of all word vectors else use summation :return: sentence vector of given input text """ words = word_tokenize(text, engine="ulmfit") vec = np.zeros((1, WV_DIM)) for word in words: if word == " ": word = "xxspace" elif word == "\n": word = "xxeol" if word in _MODEL.wv.index2word: vec += _MODEL.wv.word_vec(word) else: pass if use_mean: vec /= len(words) return vec
python
def sentence_vectorizer(text: str, use_mean: bool = True): words = word_tokenize(text, engine="ulmfit") vec = np.zeros((1, WV_DIM)) for word in words: if word == " ": word = "xxspace" elif word == "\n": word = "xxeol" if word in _MODEL.wv.index2word: vec += _MODEL.wv.word_vec(word) else: pass if use_mean: vec /= len(words) return vec
[ "def", "sentence_vectorizer", "(", "text", ":", "str", ",", "use_mean", ":", "bool", "=", "True", ")", ":", "words", "=", "word_tokenize", "(", "text", ",", "engine", "=", "\"ulmfit\"", ")", "vec", "=", "np", ".", "zeros", "(", "(", "1", ",", "WV_DIM...
Get sentence vector from text If a word is not in the vocabulary, KeyError will be raised. :param string text: text input :param boolean use_mean: if `True` use mean of all word vectors else use summation :return: sentence vector of given input text
[ "Get", "sentence", "vector", "from", "text", "If", "a", "word", "is", "not", "in", "the", "vocabulary", "KeyError", "will", "be", "raised", "." ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/word_vector/__init__.py#L75-L102
235,827
PyThaiNLP/pythainlp
pythainlp/util/keywords.py
rank
def rank(words: List[str], exclude_stopwords: bool = False) -> Counter: """ Sort words by frequency :param list words: a list of words :param bool exclude_stopwords: exclude stopwords :return: Counter """ if not words: return None if exclude_stopwords: words = [word for word in words if word not in _STOPWORDS] return Counter(words)
python
def rank(words: List[str], exclude_stopwords: bool = False) -> Counter: if not words: return None if exclude_stopwords: words = [word for word in words if word not in _STOPWORDS] return Counter(words)
[ "def", "rank", "(", "words", ":", "List", "[", "str", "]", ",", "exclude_stopwords", ":", "bool", "=", "False", ")", "->", "Counter", ":", "if", "not", "words", ":", "return", "None", "if", "exclude_stopwords", ":", "words", "=", "[", "word", "for", ...
Sort words by frequency :param list words: a list of words :param bool exclude_stopwords: exclude stopwords :return: Counter
[ "Sort", "words", "by", "frequency" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/util/keywords.py#L10-L24
235,828
PyThaiNLP/pythainlp
pythainlp/ulmfit/__init__.py
replace_rep_after
def replace_rep_after(text: str) -> str: "Replace repetitions at the character level in `text` after the repetition" def _replace_rep(m): c, cc = m.groups() return f"{c}{TK_REP}{len(cc)+1}" re_rep = re.compile(r"(\S)(\1{2,})") return re_rep.sub(_replace_rep, text)
python
def replace_rep_after(text: str) -> str: "Replace repetitions at the character level in `text` after the repetition" def _replace_rep(m): c, cc = m.groups() return f"{c}{TK_REP}{len(cc)+1}" re_rep = re.compile(r"(\S)(\1{2,})") return re_rep.sub(_replace_rep, text)
[ "def", "replace_rep_after", "(", "text", ":", "str", ")", "->", "str", ":", "def", "_replace_rep", "(", "m", ")", ":", "c", ",", "cc", "=", "m", ".", "groups", "(", ")", "return", "f\"{c}{TK_REP}{len(cc)+1}\"", "re_rep", "=", "re", ".", "compile", "(",...
Replace repetitions at the character level in `text` after the repetition
[ "Replace", "repetitions", "at", "the", "character", "level", "in", "text", "after", "the", "repetition" ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/ulmfit/__init__.py#L78-L87
235,829
PyThaiNLP/pythainlp
pythainlp/ulmfit/__init__.py
rm_brackets
def rm_brackets(text: str) -> str: "Remove all empty brackets from `t`." new_line = re.sub(r"\(\)", "", text) new_line = re.sub(r"\{\}", "", new_line) new_line = re.sub(r"\[\]", "", new_line) return new_line
python
def rm_brackets(text: str) -> str: "Remove all empty brackets from `t`." new_line = re.sub(r"\(\)", "", text) new_line = re.sub(r"\{\}", "", new_line) new_line = re.sub(r"\[\]", "", new_line) return new_line
[ "def", "rm_brackets", "(", "text", ":", "str", ")", "->", "str", ":", "new_line", "=", "re", ".", "sub", "(", "r\"\\(\\)\"", ",", "\"\"", ",", "text", ")", "new_line", "=", "re", ".", "sub", "(", "r\"\\{\\}\"", ",", "\"\"", ",", "new_line", ")", "n...
Remove all empty brackets from `t`.
[ "Remove", "all", "empty", "brackets", "from", "t", "." ]
e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/ulmfit/__init__.py#L96-L102
235,830
great-expectations/great_expectations
great_expectations/data_asset/base.py
_calc_validation_statistics
def _calc_validation_statistics(validation_results): """ Calculate summary statistics for the validation results and return ``ExpectationStatistics``. """ # calc stats successful_expectations = sum(exp["success"] for exp in validation_results) evaluated_expectations = len(validation_results) unsuccessful_expectations = evaluated_expectations - successful_expectations success = successful_expectations == evaluated_expectations try: success_percent = successful_expectations / evaluated_expectations * 100 except ZeroDivisionError: success_percent = float("nan") return ValidationStatistics( successful_expectations=successful_expectations, evaluated_expectations=evaluated_expectations, unsuccessful_expectations=unsuccessful_expectations, success=success, success_percent=success_percent, )
python
def _calc_validation_statistics(validation_results): # calc stats successful_expectations = sum(exp["success"] for exp in validation_results) evaluated_expectations = len(validation_results) unsuccessful_expectations = evaluated_expectations - successful_expectations success = successful_expectations == evaluated_expectations try: success_percent = successful_expectations / evaluated_expectations * 100 except ZeroDivisionError: success_percent = float("nan") return ValidationStatistics( successful_expectations=successful_expectations, evaluated_expectations=evaluated_expectations, unsuccessful_expectations=unsuccessful_expectations, success=success, success_percent=success_percent, )
[ "def", "_calc_validation_statistics", "(", "validation_results", ")", ":", "# calc stats", "successful_expectations", "=", "sum", "(", "exp", "[", "\"success\"", "]", "for", "exp", "in", "validation_results", ")", "evaluated_expectations", "=", "len", "(", "validation...
Calculate summary statistics for the validation results and return ``ExpectationStatistics``.
[ "Calculate", "summary", "statistics", "for", "the", "validation", "results", "and", "return", "ExpectationStatistics", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L1127-L1148
235,831
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset.expectation
def expectation(cls, method_arg_names): """Manages configuration and running of expectation objects. Expectation builds and saves a new expectation configuration to the DataAsset object. It is the core decorator \ used by great expectations to manage expectation configurations. Args: method_arg_names (List) : An ordered list of the arguments used by the method implementing the expectation \ (typically the result of inspection). Positional arguments are explicitly mapped to \ keyword arguments when the expectation is run. Notes: Intermediate decorators that call the core @expectation decorator will most likely need to pass their \ decorated methods' signature up to the expectation decorator. For example, the MetaPandasDataset \ column_map_expectation decorator relies on the DataAsset expectation decorator, but will pass through the \ signature from the implementing method. @expectation intercepts and takes action based on the following parameters: * include_config (boolean or None) : \ If True, then include the generated expectation config as part of the result object. \ For more detail, see :ref:`include_config`. * catch_exceptions (boolean or None) : \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. * result_format (str or None) : \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. * meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. """ def outer_wrapper(func): @wraps(func) def wrapper(self, *args, **kwargs): # Get the name of the method method_name = func.__name__ # Combine all arguments into a single new "kwargs" all_args = dict(zip(method_arg_names, args)) all_args.update(kwargs) # Unpack display parameters; remove them from all_args if appropriate if "include_config" in kwargs: include_config = kwargs["include_config"] del all_args["include_config"] else: include_config = self.default_expectation_args["include_config"] if "catch_exceptions" in kwargs: catch_exceptions = kwargs["catch_exceptions"] del all_args["catch_exceptions"] else: catch_exceptions = self.default_expectation_args["catch_exceptions"] if "result_format" in kwargs: result_format = kwargs["result_format"] else: result_format = self.default_expectation_args["result_format"] # Extract the meta object for use as a top-level expectation_config holder if "meta" in kwargs: meta = kwargs["meta"] del all_args["meta"] else: meta = None # Get the signature of the inner wrapper: if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] if "result_format" in argspec: all_args["result_format"] = result_format else: if "result_format" in all_args: del all_args["result_format"] all_args = recursively_convert_to_json_serializable(all_args) # Patch in PARAMETER args, and remove locally-supplied arguments # This will become the stored config expectation_args = copy.deepcopy(all_args) if "evaluation_parameters" in self._expectations_config: evaluation_args = self._build_evaluation_parameters(expectation_args, self._expectations_config["evaluation_parameters"]) # This will be passed to the evaluation else: evaluation_args = self._build_evaluation_parameters( expectation_args, None) # Construct the expectation_config object expectation_config = DotDict({ "expectation_type": method_name, "kwargs": expectation_args }) # Add meta to our expectation_config if meta is not None: expectation_config["meta"] = meta raised_exception = False exception_traceback = None exception_message = None # Finally, execute the expectation method itself try: return_obj = func(self, **evaluation_args) except Exception as err: if catch_exceptions: raised_exception = True exception_traceback = traceback.format_exc() exception_message = str(err) return_obj = { "success": False } else: raise(err) # Append the expectation to the config. self._append_expectation(expectation_config) if include_config: return_obj["expectation_config"] = copy.deepcopy( expectation_config) if catch_exceptions: return_obj["exception_info"] = { "raised_exception": raised_exception, "exception_message": exception_message, "exception_traceback": exception_traceback } # Add a "success" object to the config expectation_config["success_on_last_run"] = return_obj["success"] # Add meta to return object if meta is not None: return_obj['meta'] = meta return_obj = recursively_convert_to_json_serializable( return_obj) return return_obj return wrapper return outer_wrapper
python
def expectation(cls, method_arg_names): def outer_wrapper(func): @wraps(func) def wrapper(self, *args, **kwargs): # Get the name of the method method_name = func.__name__ # Combine all arguments into a single new "kwargs" all_args = dict(zip(method_arg_names, args)) all_args.update(kwargs) # Unpack display parameters; remove them from all_args if appropriate if "include_config" in kwargs: include_config = kwargs["include_config"] del all_args["include_config"] else: include_config = self.default_expectation_args["include_config"] if "catch_exceptions" in kwargs: catch_exceptions = kwargs["catch_exceptions"] del all_args["catch_exceptions"] else: catch_exceptions = self.default_expectation_args["catch_exceptions"] if "result_format" in kwargs: result_format = kwargs["result_format"] else: result_format = self.default_expectation_args["result_format"] # Extract the meta object for use as a top-level expectation_config holder if "meta" in kwargs: meta = kwargs["meta"] del all_args["meta"] else: meta = None # Get the signature of the inner wrapper: if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] if "result_format" in argspec: all_args["result_format"] = result_format else: if "result_format" in all_args: del all_args["result_format"] all_args = recursively_convert_to_json_serializable(all_args) # Patch in PARAMETER args, and remove locally-supplied arguments # This will become the stored config expectation_args = copy.deepcopy(all_args) if "evaluation_parameters" in self._expectations_config: evaluation_args = self._build_evaluation_parameters(expectation_args, self._expectations_config["evaluation_parameters"]) # This will be passed to the evaluation else: evaluation_args = self._build_evaluation_parameters( expectation_args, None) # Construct the expectation_config object expectation_config = DotDict({ "expectation_type": method_name, "kwargs": expectation_args }) # Add meta to our expectation_config if meta is not None: expectation_config["meta"] = meta raised_exception = False exception_traceback = None exception_message = None # Finally, execute the expectation method itself try: return_obj = func(self, **evaluation_args) except Exception as err: if catch_exceptions: raised_exception = True exception_traceback = traceback.format_exc() exception_message = str(err) return_obj = { "success": False } else: raise(err) # Append the expectation to the config. self._append_expectation(expectation_config) if include_config: return_obj["expectation_config"] = copy.deepcopy( expectation_config) if catch_exceptions: return_obj["exception_info"] = { "raised_exception": raised_exception, "exception_message": exception_message, "exception_traceback": exception_traceback } # Add a "success" object to the config expectation_config["success_on_last_run"] = return_obj["success"] # Add meta to return object if meta is not None: return_obj['meta'] = meta return_obj = recursively_convert_to_json_serializable( return_obj) return return_obj return wrapper return outer_wrapper
[ "def", "expectation", "(", "cls", ",", "method_arg_names", ")", ":", "def", "outer_wrapper", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Get the name of t...
Manages configuration and running of expectation objects. Expectation builds and saves a new expectation configuration to the DataAsset object. It is the core decorator \ used by great expectations to manage expectation configurations. Args: method_arg_names (List) : An ordered list of the arguments used by the method implementing the expectation \ (typically the result of inspection). Positional arguments are explicitly mapped to \ keyword arguments when the expectation is run. Notes: Intermediate decorators that call the core @expectation decorator will most likely need to pass their \ decorated methods' signature up to the expectation decorator. For example, the MetaPandasDataset \ column_map_expectation decorator relies on the DataAsset expectation decorator, but will pass through the \ signature from the implementing method. @expectation intercepts and takes action based on the following parameters: * include_config (boolean or None) : \ If True, then include the generated expectation config as part of the result object. \ For more detail, see :ref:`include_config`. * catch_exceptions (boolean or None) : \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. * result_format (str or None) : \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. * meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`.
[ "Manages", "configuration", "and", "running", "of", "expectation", "objects", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L52-L203
235,832
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset._append_expectation
def _append_expectation(self, expectation_config): """Appends an expectation to `DataAsset._expectations_config` and drops existing expectations of the same type. If `expectation_config` is a column expectation, this drops existing expectations that are specific to \ that column and only if it is the same expectation type as `expectation_config`. Otherwise, if it's not a \ column expectation, this drops existing expectations of the same type as `expectation config`. \ After expectations of the same type are dropped, `expectation_config` is appended to `DataAsset._expectations_config`. Args: expectation_config (json): \ The JSON-serializable expectation to be added to the DataAsset expectations in `_expectations_config`. Notes: May raise future errors once json-serializable tests are implemented to check for correct arg formatting """ expectation_type = expectation_config['expectation_type'] # Test to ensure the new expectation is serializable. # FIXME: If it's not, are we sure we want to raise an error? # FIXME: Should we allow users to override the error? # FIXME: Should we try to convert the object using something like recursively_convert_to_json_serializable? json.dumps(expectation_config) # Drop existing expectations with the same expectation_type. # For column_expectations, _append_expectation should only replace expectations # where the expectation_type AND the column match #!!! This is good default behavior, but #!!! it needs to be documented, and #!!! we need to provide syntax to override it. if 'column' in expectation_config['kwargs']: column = expectation_config['kwargs']['column'] self._expectations_config.expectations = [f for f in filter( lambda exp: (exp['expectation_type'] != expectation_type) or ( 'column' in exp['kwargs'] and exp['kwargs']['column'] != column), self._expectations_config.expectations )] else: self._expectations_config.expectations = [f for f in filter( lambda exp: exp['expectation_type'] != expectation_type, self._expectations_config.expectations )] self._expectations_config.expectations.append(expectation_config)
python
def _append_expectation(self, expectation_config): expectation_type = expectation_config['expectation_type'] # Test to ensure the new expectation is serializable. # FIXME: If it's not, are we sure we want to raise an error? # FIXME: Should we allow users to override the error? # FIXME: Should we try to convert the object using something like recursively_convert_to_json_serializable? json.dumps(expectation_config) # Drop existing expectations with the same expectation_type. # For column_expectations, _append_expectation should only replace expectations # where the expectation_type AND the column match #!!! This is good default behavior, but #!!! it needs to be documented, and #!!! we need to provide syntax to override it. if 'column' in expectation_config['kwargs']: column = expectation_config['kwargs']['column'] self._expectations_config.expectations = [f for f in filter( lambda exp: (exp['expectation_type'] != expectation_type) or ( 'column' in exp['kwargs'] and exp['kwargs']['column'] != column), self._expectations_config.expectations )] else: self._expectations_config.expectations = [f for f in filter( lambda exp: exp['expectation_type'] != expectation_type, self._expectations_config.expectations )] self._expectations_config.expectations.append(expectation_config)
[ "def", "_append_expectation", "(", "self", ",", "expectation_config", ")", ":", "expectation_type", "=", "expectation_config", "[", "'expectation_type'", "]", "# Test to ensure the new expectation is serializable.", "# FIXME: If it's not, are we sure we want to raise an error?", "# F...
Appends an expectation to `DataAsset._expectations_config` and drops existing expectations of the same type. If `expectation_config` is a column expectation, this drops existing expectations that are specific to \ that column and only if it is the same expectation type as `expectation_config`. Otherwise, if it's not a \ column expectation, this drops existing expectations of the same type as `expectation config`. \ After expectations of the same type are dropped, `expectation_config` is appended to `DataAsset._expectations_config`. Args: expectation_config (json): \ The JSON-serializable expectation to be added to the DataAsset expectations in `_expectations_config`. Notes: May raise future errors once json-serializable tests are implemented to check for correct arg formatting
[ "Appends", "an", "expectation", "to", "DataAsset", ".", "_expectations_config", "and", "drops", "existing", "expectations", "of", "the", "same", "type", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L262-L307
235,833
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset._copy_and_clean_up_expectation
def _copy_and_clean_up_expectation(self, expectation, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, ): """Returns copy of `expectation` without `success_on_last_run` and other specified key-value pairs removed Returns a copy of specified expectation will not have `success_on_last_run` key-value. The other key-value \ pairs will be removed by default but will remain in the copy if specified. Args: expectation (json): \ The expectation to copy and clean. discard_result_format_kwargs (boolean): \ if True, will remove the kwarg `output_format` key-value pair from the copied expectation. discard_include_configs_kwargs (boolean): if True, will remove the kwarg `include_configs` key-value pair from the copied expectation. discard_catch_exceptions_kwargs (boolean): if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation. Returns: A copy of the provided expectation with `success_on_last_run` and other specified key-value pairs removed """ new_expectation = copy.deepcopy(expectation) if "success_on_last_run" in new_expectation: del new_expectation["success_on_last_run"] if discard_result_format_kwargs: if "result_format" in new_expectation["kwargs"]: del new_expectation["kwargs"]["result_format"] # discards["result_format"] += 1 if discard_include_configs_kwargs: if "include_configs" in new_expectation["kwargs"]: del new_expectation["kwargs"]["include_configs"] # discards["include_configs"] += 1 if discard_catch_exceptions_kwargs: if "catch_exceptions" in new_expectation["kwargs"]: del new_expectation["kwargs"]["catch_exceptions"] # discards["catch_exceptions"] += 1 return new_expectation
python
def _copy_and_clean_up_expectation(self, expectation, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, ): new_expectation = copy.deepcopy(expectation) if "success_on_last_run" in new_expectation: del new_expectation["success_on_last_run"] if discard_result_format_kwargs: if "result_format" in new_expectation["kwargs"]: del new_expectation["kwargs"]["result_format"] # discards["result_format"] += 1 if discard_include_configs_kwargs: if "include_configs" in new_expectation["kwargs"]: del new_expectation["kwargs"]["include_configs"] # discards["include_configs"] += 1 if discard_catch_exceptions_kwargs: if "catch_exceptions" in new_expectation["kwargs"]: del new_expectation["kwargs"]["catch_exceptions"] # discards["catch_exceptions"] += 1 return new_expectation
[ "def", "_copy_and_clean_up_expectation", "(", "self", ",", "expectation", ",", "discard_result_format_kwargs", "=", "True", ",", "discard_include_configs_kwargs", "=", "True", ",", "discard_catch_exceptions_kwargs", "=", "True", ",", ")", ":", "new_expectation", "=", "c...
Returns copy of `expectation` without `success_on_last_run` and other specified key-value pairs removed Returns a copy of specified expectation will not have `success_on_last_run` key-value. The other key-value \ pairs will be removed by default but will remain in the copy if specified. Args: expectation (json): \ The expectation to copy and clean. discard_result_format_kwargs (boolean): \ if True, will remove the kwarg `output_format` key-value pair from the copied expectation. discard_include_configs_kwargs (boolean): if True, will remove the kwarg `include_configs` key-value pair from the copied expectation. discard_catch_exceptions_kwargs (boolean): if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation. Returns: A copy of the provided expectation with `success_on_last_run` and other specified key-value pairs removed
[ "Returns", "copy", "of", "expectation", "without", "success_on_last_run", "and", "other", "specified", "key", "-", "value", "pairs", "removed" ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L309-L353
235,834
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset._copy_and_clean_up_expectations_from_indexes
def _copy_and_clean_up_expectations_from_indexes( self, match_indexes, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, ): """Copies and cleans all expectations provided by their index in DataAsset._expectations_config.expectations. Applies the _copy_and_clean_up_expectation method to multiple expectations, provided by their index in \ `DataAsset,_expectations_config.expectations`. Returns a list of the copied and cleaned expectations. Args: match_indexes (List): \ Index numbers of the expectations from `expectation_config.expectations` to be copied and cleaned. discard_result_format_kwargs (boolean): \ if True, will remove the kwarg `output_format` key-value pair from the copied expectation. discard_include_configs_kwargs (boolean): if True, will remove the kwarg `include_configs` key-value pair from the copied expectation. discard_catch_exceptions_kwargs (boolean): if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation. Returns: A list of the copied expectations with `success_on_last_run` and other specified \ key-value pairs removed. See also: _copy_and_clean_expectation """ rval = [] for i in match_indexes: rval.append( self._copy_and_clean_up_expectation( self._expectations_config.expectations[i], discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs, ) ) return rval
python
def _copy_and_clean_up_expectations_from_indexes( self, match_indexes, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, ): rval = [] for i in match_indexes: rval.append( self._copy_and_clean_up_expectation( self._expectations_config.expectations[i], discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs, ) ) return rval
[ "def", "_copy_and_clean_up_expectations_from_indexes", "(", "self", ",", "match_indexes", ",", "discard_result_format_kwargs", "=", "True", ",", "discard_include_configs_kwargs", "=", "True", ",", "discard_catch_exceptions_kwargs", "=", "True", ",", ")", ":", "rval", "=",...
Copies and cleans all expectations provided by their index in DataAsset._expectations_config.expectations. Applies the _copy_and_clean_up_expectation method to multiple expectations, provided by their index in \ `DataAsset,_expectations_config.expectations`. Returns a list of the copied and cleaned expectations. Args: match_indexes (List): \ Index numbers of the expectations from `expectation_config.expectations` to be copied and cleaned. discard_result_format_kwargs (boolean): \ if True, will remove the kwarg `output_format` key-value pair from the copied expectation. discard_include_configs_kwargs (boolean): if True, will remove the kwarg `include_configs` key-value pair from the copied expectation. discard_catch_exceptions_kwargs (boolean): if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation. Returns: A list of the copied expectations with `success_on_last_run` and other specified \ key-value pairs removed. See also: _copy_and_clean_expectation
[ "Copies", "and", "cleans", "all", "expectations", "provided", "by", "their", "index", "in", "DataAsset", ".", "_expectations_config", ".", "expectations", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L355-L395
235,835
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset.get_expectations_config
def get_expectations_config(self, discard_failed_expectations=True, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, suppress_warnings=False ): """Returns _expectation_config as a JSON object, and perform some cleaning along the way. Args: discard_failed_expectations (boolean): \ Only include expectations with success_on_last_run=True in the exported config. Defaults to `True`. discard_result_format_kwargs (boolean): \ In returned expectation objects, suppress the `result_format` parameter. Defaults to `True`. discard_include_configs_kwargs (boolean): \ In returned expectation objects, suppress the `include_configs` parameter. Defaults to `True`. discard_catch_exceptions_kwargs (boolean): \ In returned expectation objects, suppress the `catch_exceptions` parameter. Defaults to `True`. Returns: An expectation config. Note: get_expectations_config does not affect the underlying config at all. The returned config is a copy of _expectations_config, not the original object. """ config = dict(self._expectations_config) config = copy.deepcopy(config) expectations = config["expectations"] discards = defaultdict(int) if discard_failed_expectations: new_expectations = [] for expectation in expectations: # Note: This is conservative logic. # Instead of retaining expectations IFF success==True, it discard expectations IFF success==False. # In cases where expectation["success"] is missing or None, expectations are *retained*. # Such a case could occur if expectations were loaded from a config file and never run. if "success_on_last_run" in expectation and expectation["success_on_last_run"] == False: discards["failed_expectations"] += 1 else: new_expectations.append(expectation) expectations = new_expectations for expectation in expectations: # FIXME: Factor this out into a new function. The logic is duplicated in remove_expectation, which calls _copy_and_clean_up_expectation if "success_on_last_run" in expectation: del expectation["success_on_last_run"] if discard_result_format_kwargs: if "result_format" in expectation["kwargs"]: del expectation["kwargs"]["result_format"] discards["result_format"] += 1 if discard_include_configs_kwargs: if "include_configs" in expectation["kwargs"]: del expectation["kwargs"]["include_configs"] discards["include_configs"] += 1 if discard_catch_exceptions_kwargs: if "catch_exceptions" in expectation["kwargs"]: del expectation["kwargs"]["catch_exceptions"] discards["catch_exceptions"] += 1 if not suppress_warnings: """ WARNING: get_expectations_config discarded 12 failing expectations 44 result_format kwargs 0 include_config kwargs 1 catch_exceptions kwargs If you wish to change this behavior, please set discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately. """ if any([discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs]): print("WARNING: get_expectations_config discarded") if discard_failed_expectations: print("\t%d failing expectations" % discards["failed_expectations"]) if discard_result_format_kwargs: print("\t%d result_format kwargs" % discards["result_format"]) if discard_include_configs_kwargs: print("\t%d include_configs kwargs" % discards["include_configs"]) if discard_catch_exceptions_kwargs: print("\t%d catch_exceptions kwargs" % discards["catch_exceptions"]) print("If you wish to change this behavior, please set discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately.") config["expectations"] = expectations return config
python
def get_expectations_config(self, discard_failed_expectations=True, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, suppress_warnings=False ): config = dict(self._expectations_config) config = copy.deepcopy(config) expectations = config["expectations"] discards = defaultdict(int) if discard_failed_expectations: new_expectations = [] for expectation in expectations: # Note: This is conservative logic. # Instead of retaining expectations IFF success==True, it discard expectations IFF success==False. # In cases where expectation["success"] is missing or None, expectations are *retained*. # Such a case could occur if expectations were loaded from a config file and never run. if "success_on_last_run" in expectation and expectation["success_on_last_run"] == False: discards["failed_expectations"] += 1 else: new_expectations.append(expectation) expectations = new_expectations for expectation in expectations: # FIXME: Factor this out into a new function. The logic is duplicated in remove_expectation, which calls _copy_and_clean_up_expectation if "success_on_last_run" in expectation: del expectation["success_on_last_run"] if discard_result_format_kwargs: if "result_format" in expectation["kwargs"]: del expectation["kwargs"]["result_format"] discards["result_format"] += 1 if discard_include_configs_kwargs: if "include_configs" in expectation["kwargs"]: del expectation["kwargs"]["include_configs"] discards["include_configs"] += 1 if discard_catch_exceptions_kwargs: if "catch_exceptions" in expectation["kwargs"]: del expectation["kwargs"]["catch_exceptions"] discards["catch_exceptions"] += 1 if not suppress_warnings: """ WARNING: get_expectations_config discarded 12 failing expectations 44 result_format kwargs 0 include_config kwargs 1 catch_exceptions kwargs If you wish to change this behavior, please set discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately. """ if any([discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs]): print("WARNING: get_expectations_config discarded") if discard_failed_expectations: print("\t%d failing expectations" % discards["failed_expectations"]) if discard_result_format_kwargs: print("\t%d result_format kwargs" % discards["result_format"]) if discard_include_configs_kwargs: print("\t%d include_configs kwargs" % discards["include_configs"]) if discard_catch_exceptions_kwargs: print("\t%d catch_exceptions kwargs" % discards["catch_exceptions"]) print("If you wish to change this behavior, please set discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, and discard_catch_exceptions_kwargs appropirately.") config["expectations"] = expectations return config
[ "def", "get_expectations_config", "(", "self", ",", "discard_failed_expectations", "=", "True", ",", "discard_result_format_kwargs", "=", "True", ",", "discard_include_configs_kwargs", "=", "True", ",", "discard_catch_exceptions_kwargs", "=", "True", ",", "suppress_warnings...
Returns _expectation_config as a JSON object, and perform some cleaning along the way. Args: discard_failed_expectations (boolean): \ Only include expectations with success_on_last_run=True in the exported config. Defaults to `True`. discard_result_format_kwargs (boolean): \ In returned expectation objects, suppress the `result_format` parameter. Defaults to `True`. discard_include_configs_kwargs (boolean): \ In returned expectation objects, suppress the `include_configs` parameter. Defaults to `True`. discard_catch_exceptions_kwargs (boolean): \ In returned expectation objects, suppress the `catch_exceptions` parameter. Defaults to `True`. Returns: An expectation config. Note: get_expectations_config does not affect the underlying config at all. The returned config is a copy of _expectations_config, not the original object.
[ "Returns", "_expectation_config", "as", "a", "JSON", "object", "and", "perform", "some", "cleaning", "along", "the", "way", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L581-L673
235,836
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset.save_expectations_config
def save_expectations_config( self, filepath=None, discard_failed_expectations=True, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, suppress_warnings=False ): """Writes ``_expectation_config`` to a JSON file. Writes the DataAsset's expectation config to the specified JSON ``filepath``. Failing expectations \ can be excluded from the JSON expectations config with ``discard_failed_expectations``. The kwarg key-value \ pairs :ref:`result_format`, :ref:`include_config`, and :ref:`catch_exceptions` are optionally excluded from the JSON \ expectations config. Args: filepath (string): \ The location and name to write the JSON config file to. discard_failed_expectations (boolean): \ If True, excludes expectations that do not return ``success = True``. \ If False, all expectations are written to the JSON config file. discard_result_format_kwargs (boolean): \ If True, the :ref:`result_format` attribute for each expectation is not written to the JSON config file. \ discard_include_configs_kwargs (boolean): \ If True, the :ref:`include_config` attribute for each expectation is not written to the JSON config file.\ discard_catch_exceptions_kwargs (boolean): \ If True, the :ref:`catch_exceptions` attribute for each expectation is not written to the JSON config \ file. suppress_warnings (boolean): \ It True, all warnings raised by Great Expectations, as a result of dropped expectations, are \ suppressed. """ if filepath == None: # FIXME: Fetch the proper filepath from the project config pass expectations_config = self.get_expectations_config( discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs, suppress_warnings ) expectation_config_str = json.dumps(expectations_config, indent=2) open(filepath, 'w').write(expectation_config_str)
python
def save_expectations_config( self, filepath=None, discard_failed_expectations=True, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, suppress_warnings=False ): if filepath == None: # FIXME: Fetch the proper filepath from the project config pass expectations_config = self.get_expectations_config( discard_failed_expectations, discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs, suppress_warnings ) expectation_config_str = json.dumps(expectations_config, indent=2) open(filepath, 'w').write(expectation_config_str)
[ "def", "save_expectations_config", "(", "self", ",", "filepath", "=", "None", ",", "discard_failed_expectations", "=", "True", ",", "discard_result_format_kwargs", "=", "True", ",", "discard_include_configs_kwargs", "=", "True", ",", "discard_catch_exceptions_kwargs", "="...
Writes ``_expectation_config`` to a JSON file. Writes the DataAsset's expectation config to the specified JSON ``filepath``. Failing expectations \ can be excluded from the JSON expectations config with ``discard_failed_expectations``. The kwarg key-value \ pairs :ref:`result_format`, :ref:`include_config`, and :ref:`catch_exceptions` are optionally excluded from the JSON \ expectations config. Args: filepath (string): \ The location and name to write the JSON config file to. discard_failed_expectations (boolean): \ If True, excludes expectations that do not return ``success = True``. \ If False, all expectations are written to the JSON config file. discard_result_format_kwargs (boolean): \ If True, the :ref:`result_format` attribute for each expectation is not written to the JSON config file. \ discard_include_configs_kwargs (boolean): \ If True, the :ref:`include_config` attribute for each expectation is not written to the JSON config file.\ discard_catch_exceptions_kwargs (boolean): \ If True, the :ref:`catch_exceptions` attribute for each expectation is not written to the JSON config \ file. suppress_warnings (boolean): \ It True, all warnings raised by Great Expectations, as a result of dropped expectations, are \ suppressed.
[ "Writes", "_expectation_config", "to", "a", "JSON", "file", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L675-L721
235,837
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset.validate
def validate(self, expectations_config=None, evaluation_parameters=None, catch_exceptions=True, result_format=None, only_return_failures=False): """Generates a JSON-formatted report describing the outcome of all expectations. Use the default expectations_config=None to validate the expectations config associated with the DataAsset. Args: expectations_config (json or None): \ If None, uses the expectations config generated with the DataAsset during the current session. \ If a JSON file, validates those expectations. evaluation_parameters (dict or None): \ If None, uses the evaluation_paramters from the expectations_config provided or as part of the data_asset. If a dict, uses the evaluation parameters in the dictionary. catch_exceptions (boolean): \ If True, exceptions raised by tests will not end validation and will be described in the returned report. result_format (string or None): \ If None, uses the default value ('BASIC' or as specified). \ If string, the returned expectation output follows the specified format ('BOOLEAN_ONLY','BASIC', etc.). include_config (boolean): \ If True, the returned results include the config information associated with each expectation, if \ it exists. only_return_failures (boolean): \ If True, expectation results are only returned when ``success = False`` \ Returns: A JSON-formatted dictionary containing a list of the validation results. \ An example of the returned format:: { "results": [ { "unexpected_list": [unexpected_value_1, unexpected_value_2], "expectation_type": "expect_*", "kwargs": { "column": "Column_Name", "output_format": "SUMMARY" }, "success": true, "raised_exception: false. "exception_traceback": null }, { ... (Second expectation results) }, ... (More expectations results) ], "success": true, "statistics": { "evaluated_expectations": n, "successful_expectations": m, "unsuccessful_expectations": n - m, "success_percent": m / n } } Notes: If the configuration object was built with a different version of great expectations then the current environment. \ If no version was found in the configuration file. Raises: AttributeError - if 'catch_exceptions'=None and an expectation throws an AttributeError """ results = [] if expectations_config is None: expectations_config = self.get_expectations_config( discard_failed_expectations=False, discard_result_format_kwargs=False, discard_include_configs_kwargs=False, discard_catch_exceptions_kwargs=False, ) elif isinstance(expectations_config, string_types): expectations_config = json.load(open(expectations_config, 'r')) if evaluation_parameters is None: # Use evaluation parameters from the (maybe provided) config if "evaluation_parameters" in expectations_config: evaluation_parameters = expectations_config["evaluation_parameters"] # Warn if our version is different from the version in the configuration try: if expectations_config['meta']['great_expectations.__version__'] != __version__: warnings.warn( "WARNING: This configuration object was built using version %s of great_expectations, but is currently being valided by version %s." % (expectations_config['meta']['great_expectations.__version__'], __version__)) except KeyError: warnings.warn( "WARNING: No great_expectations version found in configuration object.") for expectation in expectations_config['expectations']: try: expectation_method = getattr( self, expectation['expectation_type']) if result_format is not None: expectation['kwargs'].update({'result_format': result_format}) # Counting the number of unexpected values can be expensive when there is a large # number of np.nan values. # This only happens on expect_column_values_to_not_be_null expectations. # Since there is no reason to look for most common unexpected values in this case, # we will instruct the result formatting method to skip this step. if expectation['expectation_type'] in ['expect_column_values_to_not_be_null', 'expect_column_values_to_be_null']: expectation['kwargs']['result_format'] = parse_result_format(expectation['kwargs']['result_format']) expectation['kwargs']['result_format']['partial_unexpected_count'] = 0 # A missing parameter should raise a KeyError evaluation_args = self._build_evaluation_parameters( expectation['kwargs'], evaluation_parameters) result = expectation_method( catch_exceptions=catch_exceptions, **evaluation_args ) except Exception as err: if catch_exceptions: raised_exception = True exception_traceback = traceback.format_exc() result = { "success": False, "exception_info": { "raised_exception": raised_exception, "exception_traceback": exception_traceback, "exception_message": str(err) } } else: raise(err) # if include_config: result["expectation_config"] = copy.deepcopy(expectation) # Add an empty exception_info object if no exception was caught if catch_exceptions and ('exception_info' not in result): result["exception_info"] = { "raised_exception": False, "exception_traceback": None, "exception_message": None } results.append(result) statistics = _calc_validation_statistics(results) if only_return_failures: abbrev_results = [] for exp in results: if exp["success"] == False: abbrev_results.append(exp) results = abbrev_results result = { "results": results, "success": statistics.success, "statistics": { "evaluated_expectations": statistics.evaluated_expectations, "successful_expectations": statistics.successful_expectations, "unsuccessful_expectations": statistics.unsuccessful_expectations, "success_percent": statistics.success_percent, } } if evaluation_parameters is not None: result.update({"evaluation_parameters": evaluation_parameters}) return result
python
def validate(self, expectations_config=None, evaluation_parameters=None, catch_exceptions=True, result_format=None, only_return_failures=False): results = [] if expectations_config is None: expectations_config = self.get_expectations_config( discard_failed_expectations=False, discard_result_format_kwargs=False, discard_include_configs_kwargs=False, discard_catch_exceptions_kwargs=False, ) elif isinstance(expectations_config, string_types): expectations_config = json.load(open(expectations_config, 'r')) if evaluation_parameters is None: # Use evaluation parameters from the (maybe provided) config if "evaluation_parameters" in expectations_config: evaluation_parameters = expectations_config["evaluation_parameters"] # Warn if our version is different from the version in the configuration try: if expectations_config['meta']['great_expectations.__version__'] != __version__: warnings.warn( "WARNING: This configuration object was built using version %s of great_expectations, but is currently being valided by version %s." % (expectations_config['meta']['great_expectations.__version__'], __version__)) except KeyError: warnings.warn( "WARNING: No great_expectations version found in configuration object.") for expectation in expectations_config['expectations']: try: expectation_method = getattr( self, expectation['expectation_type']) if result_format is not None: expectation['kwargs'].update({'result_format': result_format}) # Counting the number of unexpected values can be expensive when there is a large # number of np.nan values. # This only happens on expect_column_values_to_not_be_null expectations. # Since there is no reason to look for most common unexpected values in this case, # we will instruct the result formatting method to skip this step. if expectation['expectation_type'] in ['expect_column_values_to_not_be_null', 'expect_column_values_to_be_null']: expectation['kwargs']['result_format'] = parse_result_format(expectation['kwargs']['result_format']) expectation['kwargs']['result_format']['partial_unexpected_count'] = 0 # A missing parameter should raise a KeyError evaluation_args = self._build_evaluation_parameters( expectation['kwargs'], evaluation_parameters) result = expectation_method( catch_exceptions=catch_exceptions, **evaluation_args ) except Exception as err: if catch_exceptions: raised_exception = True exception_traceback = traceback.format_exc() result = { "success": False, "exception_info": { "raised_exception": raised_exception, "exception_traceback": exception_traceback, "exception_message": str(err) } } else: raise(err) # if include_config: result["expectation_config"] = copy.deepcopy(expectation) # Add an empty exception_info object if no exception was caught if catch_exceptions and ('exception_info' not in result): result["exception_info"] = { "raised_exception": False, "exception_traceback": None, "exception_message": None } results.append(result) statistics = _calc_validation_statistics(results) if only_return_failures: abbrev_results = [] for exp in results: if exp["success"] == False: abbrev_results.append(exp) results = abbrev_results result = { "results": results, "success": statistics.success, "statistics": { "evaluated_expectations": statistics.evaluated_expectations, "successful_expectations": statistics.successful_expectations, "unsuccessful_expectations": statistics.unsuccessful_expectations, "success_percent": statistics.success_percent, } } if evaluation_parameters is not None: result.update({"evaluation_parameters": evaluation_parameters}) return result
[ "def", "validate", "(", "self", ",", "expectations_config", "=", "None", ",", "evaluation_parameters", "=", "None", ",", "catch_exceptions", "=", "True", ",", "result_format", "=", "None", ",", "only_return_failures", "=", "False", ")", ":", "results", "=", "[...
Generates a JSON-formatted report describing the outcome of all expectations. Use the default expectations_config=None to validate the expectations config associated with the DataAsset. Args: expectations_config (json or None): \ If None, uses the expectations config generated with the DataAsset during the current session. \ If a JSON file, validates those expectations. evaluation_parameters (dict or None): \ If None, uses the evaluation_paramters from the expectations_config provided or as part of the data_asset. If a dict, uses the evaluation parameters in the dictionary. catch_exceptions (boolean): \ If True, exceptions raised by tests will not end validation and will be described in the returned report. result_format (string or None): \ If None, uses the default value ('BASIC' or as specified). \ If string, the returned expectation output follows the specified format ('BOOLEAN_ONLY','BASIC', etc.). include_config (boolean): \ If True, the returned results include the config information associated with each expectation, if \ it exists. only_return_failures (boolean): \ If True, expectation results are only returned when ``success = False`` \ Returns: A JSON-formatted dictionary containing a list of the validation results. \ An example of the returned format:: { "results": [ { "unexpected_list": [unexpected_value_1, unexpected_value_2], "expectation_type": "expect_*", "kwargs": { "column": "Column_Name", "output_format": "SUMMARY" }, "success": true, "raised_exception: false. "exception_traceback": null }, { ... (Second expectation results) }, ... (More expectations results) ], "success": true, "statistics": { "evaluated_expectations": n, "successful_expectations": m, "unsuccessful_expectations": n - m, "success_percent": m / n } } Notes: If the configuration object was built with a different version of great expectations then the current environment. \ If no version was found in the configuration file. Raises: AttributeError - if 'catch_exceptions'=None and an expectation throws an AttributeError
[ "Generates", "a", "JSON", "-", "formatted", "report", "describing", "the", "outcome", "of", "all", "expectations", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L723-L893
235,838
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset.get_evaluation_parameter
def get_evaluation_parameter(self, parameter_name, default_value=None): """Get an evaluation parameter value that has been stored in meta. Args: parameter_name (string): The name of the parameter to store. default_value (any): The default value to be returned if the parameter is not found. Returns: The current value of the evaluation parameter. """ if "evaluation_parameters" in self._expectations_config and \ parameter_name in self._expectations_config['evaluation_parameters']: return self._expectations_config['evaluation_parameters'][parameter_name] else: return default_value
python
def get_evaluation_parameter(self, parameter_name, default_value=None): if "evaluation_parameters" in self._expectations_config and \ parameter_name in self._expectations_config['evaluation_parameters']: return self._expectations_config['evaluation_parameters'][parameter_name] else: return default_value
[ "def", "get_evaluation_parameter", "(", "self", ",", "parameter_name", ",", "default_value", "=", "None", ")", ":", "if", "\"evaluation_parameters\"", "in", "self", ".", "_expectations_config", "and", "parameter_name", "in", "self", ".", "_expectations_config", "[", ...
Get an evaluation parameter value that has been stored in meta. Args: parameter_name (string): The name of the parameter to store. default_value (any): The default value to be returned if the parameter is not found. Returns: The current value of the evaluation parameter.
[ "Get", "an", "evaluation", "parameter", "value", "that", "has", "been", "stored", "in", "meta", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L895-L909
235,839
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset.set_evaluation_parameter
def set_evaluation_parameter(self, parameter_name, parameter_value): """Provide a value to be stored in the data_asset evaluation_parameters object and used to evaluate parameterized expectations. Args: parameter_name (string): The name of the kwarg to be replaced at evaluation time parameter_value (any): The value to be used """ if 'evaluation_parameters' not in self._expectations_config: self._expectations_config['evaluation_parameters'] = {} self._expectations_config['evaluation_parameters'].update( {parameter_name: parameter_value})
python
def set_evaluation_parameter(self, parameter_name, parameter_value): if 'evaluation_parameters' not in self._expectations_config: self._expectations_config['evaluation_parameters'] = {} self._expectations_config['evaluation_parameters'].update( {parameter_name: parameter_value})
[ "def", "set_evaluation_parameter", "(", "self", ",", "parameter_name", ",", "parameter_value", ")", ":", "if", "'evaluation_parameters'", "not", "in", "self", ".", "_expectations_config", ":", "self", ".", "_expectations_config", "[", "'evaluation_parameters'", "]", "...
Provide a value to be stored in the data_asset evaluation_parameters object and used to evaluate parameterized expectations. Args: parameter_name (string): The name of the kwarg to be replaced at evaluation time parameter_value (any): The value to be used
[ "Provide", "a", "value", "to", "be", "stored", "in", "the", "data_asset", "evaluation_parameters", "object", "and", "used", "to", "evaluate", "parameterized", "expectations", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L911-L924
235,840
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset._build_evaluation_parameters
def _build_evaluation_parameters(self, expectation_args, evaluation_parameters): """Build a dictionary of parameters to evaluate, using the provided evaluation_paramters, AND mutate expectation_args by removing any parameter values passed in as temporary values during exploratory work. """ evaluation_args = copy.deepcopy(expectation_args) # Iterate over arguments, and replace $PARAMETER-defined args with their # specified parameters. for key, value in evaluation_args.items(): if isinstance(value, dict) and '$PARAMETER' in value: # First, check to see whether an argument was supplied at runtime # If it was, use that one, but remove it from the stored config if "$PARAMETER." + value["$PARAMETER"] in value: evaluation_args[key] = evaluation_args[key]["$PARAMETER." + value["$PARAMETER"]] del expectation_args[key]["$PARAMETER." + value["$PARAMETER"]] elif evaluation_parameters is not None and value["$PARAMETER"] in evaluation_parameters: evaluation_args[key] = evaluation_parameters[value['$PARAMETER']] else: raise KeyError( "No value found for $PARAMETER " + value["$PARAMETER"]) return evaluation_args
python
def _build_evaluation_parameters(self, expectation_args, evaluation_parameters): evaluation_args = copy.deepcopy(expectation_args) # Iterate over arguments, and replace $PARAMETER-defined args with their # specified parameters. for key, value in evaluation_args.items(): if isinstance(value, dict) and '$PARAMETER' in value: # First, check to see whether an argument was supplied at runtime # If it was, use that one, but remove it from the stored config if "$PARAMETER." + value["$PARAMETER"] in value: evaluation_args[key] = evaluation_args[key]["$PARAMETER." + value["$PARAMETER"]] del expectation_args[key]["$PARAMETER." + value["$PARAMETER"]] elif evaluation_parameters is not None and value["$PARAMETER"] in evaluation_parameters: evaluation_args[key] = evaluation_parameters[value['$PARAMETER']] else: raise KeyError( "No value found for $PARAMETER " + value["$PARAMETER"]) return evaluation_args
[ "def", "_build_evaluation_parameters", "(", "self", ",", "expectation_args", ",", "evaluation_parameters", ")", ":", "evaluation_args", "=", "copy", ".", "deepcopy", "(", "expectation_args", ")", "# Iterate over arguments, and replace $PARAMETER-defined args with their", "# spe...
Build a dictionary of parameters to evaluate, using the provided evaluation_paramters, AND mutate expectation_args by removing any parameter values passed in as temporary values during exploratory work.
[ "Build", "a", "dictionary", "of", "parameters", "to", "evaluate", "using", "the", "provided", "evaluation_paramters", "AND", "mutate", "expectation_args", "by", "removing", "any", "parameter", "values", "passed", "in", "as", "temporary", "values", "during", "explora...
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L934-L959
235,841
great-expectations/great_expectations
great_expectations/data_asset/base.py
DataAsset._calc_map_expectation_success
def _calc_map_expectation_success(self, success_count, nonnull_count, mostly): """Calculate success and percent_success for column_map_expectations Args: success_count (int): \ The number of successful values in the column nonnull_count (int): \ The number of nonnull values in the column mostly (float or None): \ A value between 0 and 1 (or None), indicating the percentage of successes required to pass the expectation as a whole\ If mostly=None, then all values must succeed in order for the expectation as a whole to succeed. Returns: success (boolean), percent_success (float) """ if nonnull_count > 0: # percent_success = float(success_count)/nonnull_count percent_success = success_count / nonnull_count if mostly != None: success = bool(percent_success >= mostly) else: success = bool(nonnull_count-success_count == 0) else: success = True percent_success = None return success, percent_success
python
def _calc_map_expectation_success(self, success_count, nonnull_count, mostly): if nonnull_count > 0: # percent_success = float(success_count)/nonnull_count percent_success = success_count / nonnull_count if mostly != None: success = bool(percent_success >= mostly) else: success = bool(nonnull_count-success_count == 0) else: success = True percent_success = None return success, percent_success
[ "def", "_calc_map_expectation_success", "(", "self", ",", "success_count", ",", "nonnull_count", ",", "mostly", ")", ":", "if", "nonnull_count", ">", "0", ":", "# percent_success = float(success_count)/nonnull_count", "percent_success", "=", "success_count", "/", "nonnull...
Calculate success and percent_success for column_map_expectations Args: success_count (int): \ The number of successful values in the column nonnull_count (int): \ The number of nonnull values in the column mostly (float or None): \ A value between 0 and 1 (or None), indicating the percentage of successes required to pass the expectation as a whole\ If mostly=None, then all values must succeed in order for the expectation as a whole to succeed. Returns: success (boolean), percent_success (float)
[ "Calculate", "success", "and", "percent_success", "for", "column_map_expectations" ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L1058-L1088
235,842
great-expectations/great_expectations
great_expectations/cli.py
validate
def validate(parsed_args): """ Read a dataset file and validate it using a config saved in another file. Uses parameters defined in the dispatch method. :param parsed_args: A Namespace object containing parsed arguments from the dispatch method. :return: The number of unsucessful expectations """ parsed_args = vars(parsed_args) data_set = parsed_args['dataset'] expectations_config_file = parsed_args['expectations_config_file'] expectations_config = json.load(open(expectations_config_file)) if parsed_args["evaluation_parameters"] is not None: evaluation_parameters = json.load( open(parsed_args["evaluation_parameters"])) else: evaluation_parameters = None # Use a custom dataasset module and class if provided. Otherwise infer from the config. if parsed_args["custom_dataset_module"]: sys.path.insert(0, os.path.dirname( parsed_args["custom_dataset_module"])) module_name = os.path.basename( parsed_args["custom_dataset_module"]).split('.')[0] custom_module = __import__(module_name) dataset_class = getattr( custom_module, parsed_args["custom_dataset_class"]) elif "data_asset_type" in expectations_config: if expectations_config["data_asset_type"] == "Dataset" or expectations_config["data_asset_type"] == "PandasDataset": dataset_class = PandasDataset elif expectations_config["data_asset_type"].endswith("Dataset"): logger.info("Using PandasDataset to validate dataset of type %s." % expectations_config["data_asset_type"]) dataset_class = PandasDataset elif expectations_config["data_asset_type"] == "FileDataAsset": dataset_class = FileDataAsset else: logger.critical("Unrecognized data_asset_type %s. You may need to specifcy custom_dataset_module and custom_dataset_class." % expectations_config["data_asset_type"]) return -1 else: dataset_class = PandasDataset if issubclass(dataset_class, Dataset): da = read_csv(data_set, expectations_config=expectations_config, dataset_class=dataset_class) else: da = dataset_class(data_set, config=expectations_config) result = da.validate( evaluation_parameters=evaluation_parameters, result_format=parsed_args["result_format"], catch_exceptions=parsed_args["catch_exceptions"], only_return_failures=parsed_args["only_return_failures"], ) print(json.dumps(result, indent=2)) return result['statistics']['unsuccessful_expectations']
python
def validate(parsed_args): parsed_args = vars(parsed_args) data_set = parsed_args['dataset'] expectations_config_file = parsed_args['expectations_config_file'] expectations_config = json.load(open(expectations_config_file)) if parsed_args["evaluation_parameters"] is not None: evaluation_parameters = json.load( open(parsed_args["evaluation_parameters"])) else: evaluation_parameters = None # Use a custom dataasset module and class if provided. Otherwise infer from the config. if parsed_args["custom_dataset_module"]: sys.path.insert(0, os.path.dirname( parsed_args["custom_dataset_module"])) module_name = os.path.basename( parsed_args["custom_dataset_module"]).split('.')[0] custom_module = __import__(module_name) dataset_class = getattr( custom_module, parsed_args["custom_dataset_class"]) elif "data_asset_type" in expectations_config: if expectations_config["data_asset_type"] == "Dataset" or expectations_config["data_asset_type"] == "PandasDataset": dataset_class = PandasDataset elif expectations_config["data_asset_type"].endswith("Dataset"): logger.info("Using PandasDataset to validate dataset of type %s." % expectations_config["data_asset_type"]) dataset_class = PandasDataset elif expectations_config["data_asset_type"] == "FileDataAsset": dataset_class = FileDataAsset else: logger.critical("Unrecognized data_asset_type %s. You may need to specifcy custom_dataset_module and custom_dataset_class." % expectations_config["data_asset_type"]) return -1 else: dataset_class = PandasDataset if issubclass(dataset_class, Dataset): da = read_csv(data_set, expectations_config=expectations_config, dataset_class=dataset_class) else: da = dataset_class(data_set, config=expectations_config) result = da.validate( evaluation_parameters=evaluation_parameters, result_format=parsed_args["result_format"], catch_exceptions=parsed_args["catch_exceptions"], only_return_failures=parsed_args["only_return_failures"], ) print(json.dumps(result, indent=2)) return result['statistics']['unsuccessful_expectations']
[ "def", "validate", "(", "parsed_args", ")", ":", "parsed_args", "=", "vars", "(", "parsed_args", ")", "data_set", "=", "parsed_args", "[", "'dataset'", "]", "expectations_config_file", "=", "parsed_args", "[", "'expectations_config_file'", "]", "expectations_config", ...
Read a dataset file and validate it using a config saved in another file. Uses parameters defined in the dispatch method. :param parsed_args: A Namespace object containing parsed arguments from the dispatch method. :return: The number of unsucessful expectations
[ "Read", "a", "dataset", "file", "and", "validate", "it", "using", "a", "config", "saved", "in", "another", "file", ".", "Uses", "parameters", "defined", "in", "the", "dispatch", "method", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/cli.py#L55-L112
235,843
great-expectations/great_expectations
great_expectations/dataset/util.py
categorical_partition_data
def categorical_partition_data(data): """Convenience method for creating weights from categorical data. Args: data (list-like): The data from which to construct the estimate. Returns: A new partition object:: { "partition": (list) The categorical values present in the data "weights": (list) The weights of the values in the partition. } """ # Make dropna explicit (even though it defaults to true) series = pd.Series(data) value_counts = series.value_counts(dropna=True) # Compute weights using denominator only of nonnull values null_indexes = series.isnull() nonnull_count = (null_indexes == False).sum() weights = value_counts.values / nonnull_count return { "values": value_counts.index.tolist(), "weights": weights }
python
def categorical_partition_data(data): # Make dropna explicit (even though it defaults to true) series = pd.Series(data) value_counts = series.value_counts(dropna=True) # Compute weights using denominator only of nonnull values null_indexes = series.isnull() nonnull_count = (null_indexes == False).sum() weights = value_counts.values / nonnull_count return { "values": value_counts.index.tolist(), "weights": weights }
[ "def", "categorical_partition_data", "(", "data", ")", ":", "# Make dropna explicit (even though it defaults to true)", "series", "=", "pd", ".", "Series", "(", "data", ")", "value_counts", "=", "series", ".", "value_counts", "(", "dropna", "=", "True", ")", "# Comp...
Convenience method for creating weights from categorical data. Args: data (list-like): The data from which to construct the estimate. Returns: A new partition object:: { "partition": (list) The categorical values present in the data "weights": (list) The weights of the values in the partition. }
[ "Convenience", "method", "for", "creating", "weights", "from", "categorical", "data", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L56-L83
235,844
great-expectations/great_expectations
great_expectations/dataset/util.py
kde_partition_data
def kde_partition_data(data, estimate_tails=True): """Convenience method for building a partition and weights using a gaussian Kernel Density Estimate and default bandwidth. Args: data (list-like): The data from which to construct the estimate estimate_tails (bool): Whether to estimate the tails of the distribution to keep the partition object finite Returns: A new partition_object:: { "partition": (list) The endpoints of the partial partition of reals, "weights": (list) The densities of the bins implied by the partition. } """ kde = stats.kde.gaussian_kde(data) evaluation_bins = np.linspace(start=np.min(data) - (kde.covariance_factor() / 2), stop=np.max(data) + (kde.covariance_factor() / 2), num=np.floor(((np.max(data) - np.min(data)) / kde.covariance_factor()) + 1).astype(int)) cdf_vals = [kde.integrate_box_1d(-np.inf, x) for x in evaluation_bins] evaluation_weights = np.diff(cdf_vals) if estimate_tails: bins = np.concatenate(([np.min(data) - (1.5 * kde.covariance_factor())], evaluation_bins, [np.max(data) + (1.5 * kde.covariance_factor())])) else: bins = np.concatenate(([-np.inf], evaluation_bins, [np.inf])) weights = np.concatenate( ([cdf_vals[0]], evaluation_weights, [1 - cdf_vals[-1]])) return { "bins": bins, "weights": weights }
python
def kde_partition_data(data, estimate_tails=True): kde = stats.kde.gaussian_kde(data) evaluation_bins = np.linspace(start=np.min(data) - (kde.covariance_factor() / 2), stop=np.max(data) + (kde.covariance_factor() / 2), num=np.floor(((np.max(data) - np.min(data)) / kde.covariance_factor()) + 1).astype(int)) cdf_vals = [kde.integrate_box_1d(-np.inf, x) for x in evaluation_bins] evaluation_weights = np.diff(cdf_vals) if estimate_tails: bins = np.concatenate(([np.min(data) - (1.5 * kde.covariance_factor())], evaluation_bins, [np.max(data) + (1.5 * kde.covariance_factor())])) else: bins = np.concatenate(([-np.inf], evaluation_bins, [np.inf])) weights = np.concatenate( ([cdf_vals[0]], evaluation_weights, [1 - cdf_vals[-1]])) return { "bins": bins, "weights": weights }
[ "def", "kde_partition_data", "(", "data", ",", "estimate_tails", "=", "True", ")", ":", "kde", "=", "stats", ".", "kde", ".", "gaussian_kde", "(", "data", ")", "evaluation_bins", "=", "np", ".", "linspace", "(", "start", "=", "np", ".", "min", "(", "da...
Convenience method for building a partition and weights using a gaussian Kernel Density Estimate and default bandwidth. Args: data (list-like): The data from which to construct the estimate estimate_tails (bool): Whether to estimate the tails of the distribution to keep the partition object finite Returns: A new partition_object:: { "partition": (list) The endpoints of the partial partition of reals, "weights": (list) The densities of the bins implied by the partition. }
[ "Convenience", "method", "for", "building", "a", "partition", "and", "weights", "using", "a", "gaussian", "Kernel", "Density", "Estimate", "and", "default", "bandwidth", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L86-L122
235,845
great-expectations/great_expectations
great_expectations/dataset/util.py
continuous_partition_data
def continuous_partition_data(data, bins='auto', n_bins=10): """Convenience method for building a partition object on continuous data Args: data (list-like): The data from which to construct the estimate. bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-spaced bins), or 'auto' (for automatically spaced bins) n_bins (int): Ignored if bins is auto. Returns: A new partition_object:: { "bins": (list) The endpoints of the partial partition of reals, "weights": (list) The densities of the bins implied by the partition. } """ if bins == 'uniform': bins = np.linspace(start=np.min(data), stop=np.max(data), num=n_bins+1) elif bins == 'ntile': bins = np.percentile(data, np.linspace( start=0, stop=100, num=n_bins+1)) elif bins != 'auto': raise ValueError("Invalid parameter for bins argument") hist, bin_edges = np.histogram(data, bins, density=False) return { "bins": bin_edges, "weights": hist / len(data) }
python
def continuous_partition_data(data, bins='auto', n_bins=10): if bins == 'uniform': bins = np.linspace(start=np.min(data), stop=np.max(data), num=n_bins+1) elif bins == 'ntile': bins = np.percentile(data, np.linspace( start=0, stop=100, num=n_bins+1)) elif bins != 'auto': raise ValueError("Invalid parameter for bins argument") hist, bin_edges = np.histogram(data, bins, density=False) return { "bins": bin_edges, "weights": hist / len(data) }
[ "def", "continuous_partition_data", "(", "data", ",", "bins", "=", "'auto'", ",", "n_bins", "=", "10", ")", ":", "if", "bins", "==", "'uniform'", ":", "bins", "=", "np", ".", "linspace", "(", "start", "=", "np", ".", "min", "(", "data", ")", ",", "...
Convenience method for building a partition object on continuous data Args: data (list-like): The data from which to construct the estimate. bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-spaced bins), or 'auto' (for automatically spaced bins) n_bins (int): Ignored if bins is auto. Returns: A new partition_object:: { "bins": (list) The endpoints of the partial partition of reals, "weights": (list) The densities of the bins implied by the partition. }
[ "Convenience", "method", "for", "building", "a", "partition", "object", "on", "continuous", "data" ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L131-L160
235,846
great-expectations/great_expectations
great_expectations/dataset/util.py
infer_distribution_parameters
def infer_distribution_parameters(data, distribution, params=None): """Convenience method for determining the shape parameters of a given distribution Args: data (list-like): The data to build shape parameters from. distribution (string): Scipy distribution, determines which parameters to build. params (dict or None): The known parameters. Parameters given here will not be altered. \ Keep as None to infer all necessary parameters from the data data. Returns: A dictionary of named parameters:: { "mean": (float), "std_dev": (float), "loc": (float), "scale": (float), "alpha": (float), "beta": (float), "min": (float), "max": (float), "df": (float) } See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kstest.html#scipy.stats.kstest """ if params is None: params = dict() elif not isinstance(params, dict): raise TypeError( "params must be a dictionary object, see great_expectations documentation") if 'mean' not in params.keys(): params['mean'] = data.mean() if 'std_dev' not in params.keys(): params['std_dev'] = data.std() if distribution == "beta": # scipy cdf(x, a, b, loc=0, scale=1) if 'alpha' not in params.keys(): # from https://stats.stackexchange.com/questions/12232/calculating-the-parameters-of-a-beta-distribution-using-the-mean-and-variance params['alpha'] = (params['mean'] ** 2) * ( ((1 - params['mean']) / params['std_dev'] ** 2) - (1 / params['mean'])) if 'beta' not in params.keys(): params['beta'] = params['alpha'] * ((1 / params['mean']) - 1) elif distribution == 'gamma': # scipy cdf(x, a, loc=0, scale=1) if 'alpha' not in params.keys(): # Using https://en.wikipedia.org/wiki/Gamma_distribution params['alpha'] = (params['mean'] / params.get('scale', 1)) # elif distribution == 'poisson': # if 'lambda' not in params.keys(): # params['lambda'] = params['mean'] elif distribution == 'uniform': # scipy cdf(x, loc=0, scale=1) if 'min' not in params.keys(): if 'loc' in params.keys(): params['min'] = params['loc'] else: params['min'] = min(data) if 'max' not in params.keys(): if 'scale' in params.keys(): params['max'] = params['scale'] else: params['max'] = max(data) - params['min'] elif distribution == 'chi2': # scipy cdf(x, df, loc=0, scale=1) if 'df' not in params.keys(): # from https://en.wikipedia.org/wiki/Chi-squared_distribution params['df'] = params['mean'] # Expon only uses loc and scale, use default # elif distribution == 'expon': # scipy cdf(x, loc=0, scale=1) # if 'lambda' in params.keys(): # Lambda is optional # params['scale'] = 1 / params['lambda'] elif distribution is not 'norm': raise AttributeError( "Unsupported distribution type. Please refer to Great Expectations Documentation") params['loc'] = params.get('loc', 0) params['scale'] = params.get('scale', 1) return params
python
def infer_distribution_parameters(data, distribution, params=None): if params is None: params = dict() elif not isinstance(params, dict): raise TypeError( "params must be a dictionary object, see great_expectations documentation") if 'mean' not in params.keys(): params['mean'] = data.mean() if 'std_dev' not in params.keys(): params['std_dev'] = data.std() if distribution == "beta": # scipy cdf(x, a, b, loc=0, scale=1) if 'alpha' not in params.keys(): # from https://stats.stackexchange.com/questions/12232/calculating-the-parameters-of-a-beta-distribution-using-the-mean-and-variance params['alpha'] = (params['mean'] ** 2) * ( ((1 - params['mean']) / params['std_dev'] ** 2) - (1 / params['mean'])) if 'beta' not in params.keys(): params['beta'] = params['alpha'] * ((1 / params['mean']) - 1) elif distribution == 'gamma': # scipy cdf(x, a, loc=0, scale=1) if 'alpha' not in params.keys(): # Using https://en.wikipedia.org/wiki/Gamma_distribution params['alpha'] = (params['mean'] / params.get('scale', 1)) # elif distribution == 'poisson': # if 'lambda' not in params.keys(): # params['lambda'] = params['mean'] elif distribution == 'uniform': # scipy cdf(x, loc=0, scale=1) if 'min' not in params.keys(): if 'loc' in params.keys(): params['min'] = params['loc'] else: params['min'] = min(data) if 'max' not in params.keys(): if 'scale' in params.keys(): params['max'] = params['scale'] else: params['max'] = max(data) - params['min'] elif distribution == 'chi2': # scipy cdf(x, df, loc=0, scale=1) if 'df' not in params.keys(): # from https://en.wikipedia.org/wiki/Chi-squared_distribution params['df'] = params['mean'] # Expon only uses loc and scale, use default # elif distribution == 'expon': # scipy cdf(x, loc=0, scale=1) # if 'lambda' in params.keys(): # Lambda is optional # params['scale'] = 1 / params['lambda'] elif distribution is not 'norm': raise AttributeError( "Unsupported distribution type. Please refer to Great Expectations Documentation") params['loc'] = params.get('loc', 0) params['scale'] = params.get('scale', 1) return params
[ "def", "infer_distribution_parameters", "(", "data", ",", "distribution", ",", "params", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "dict", "(", ")", "elif", "not", "isinstance", "(", "params", ",", "dict", ")", ":", "raise"...
Convenience method for determining the shape parameters of a given distribution Args: data (list-like): The data to build shape parameters from. distribution (string): Scipy distribution, determines which parameters to build. params (dict or None): The known parameters. Parameters given here will not be altered. \ Keep as None to infer all necessary parameters from the data data. Returns: A dictionary of named parameters:: { "mean": (float), "std_dev": (float), "loc": (float), "scale": (float), "alpha": (float), "beta": (float), "min": (float), "max": (float), "df": (float) } See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kstest.html#scipy.stats.kstest
[ "Convenience", "method", "for", "determining", "the", "shape", "parameters", "of", "a", "given", "distribution" ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L163-L253
235,847
great-expectations/great_expectations
great_expectations/dataset/util.py
_scipy_distribution_positional_args_from_dict
def _scipy_distribution_positional_args_from_dict(distribution, params): """Helper function that returns positional arguments for a scipy distribution using a dict of parameters. See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\ to see an example of scipy's positional arguments. This function returns the arguments specified by the \ scipy.stat.distribution.cdf() for tha distribution. Args: distribution (string): \ The scipy distribution name. params (dict): \ A dict of named parameters. Raises: AttributeError: \ If an unsupported distribution is provided. """ params['loc'] = params.get('loc', 0) if 'scale' not in params: params['scale'] = 1 if distribution == 'norm': return params['mean'], params['std_dev'] elif distribution == 'beta': return params['alpha'], params['beta'], params['loc'], params['scale'] elif distribution == 'gamma': return params['alpha'], params['loc'], params['scale'] # elif distribution == 'poisson': # return params['lambda'], params['loc'] elif distribution == 'uniform': return params['min'], params['max'] elif distribution == 'chi2': return params['df'], params['loc'], params['scale'] elif distribution == 'expon': return params['loc'], params['scale']
python
def _scipy_distribution_positional_args_from_dict(distribution, params): params['loc'] = params.get('loc', 0) if 'scale' not in params: params['scale'] = 1 if distribution == 'norm': return params['mean'], params['std_dev'] elif distribution == 'beta': return params['alpha'], params['beta'], params['loc'], params['scale'] elif distribution == 'gamma': return params['alpha'], params['loc'], params['scale'] # elif distribution == 'poisson': # return params['lambda'], params['loc'] elif distribution == 'uniform': return params['min'], params['max'] elif distribution == 'chi2': return params['df'], params['loc'], params['scale'] elif distribution == 'expon': return params['loc'], params['scale']
[ "def", "_scipy_distribution_positional_args_from_dict", "(", "distribution", ",", "params", ")", ":", "params", "[", "'loc'", "]", "=", "params", ".", "get", "(", "'loc'", ",", "0", ")", "if", "'scale'", "not", "in", "params", ":", "params", "[", "'scale'", ...
Helper function that returns positional arguments for a scipy distribution using a dict of parameters. See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\ to see an example of scipy's positional arguments. This function returns the arguments specified by the \ scipy.stat.distribution.cdf() for tha distribution. Args: distribution (string): \ The scipy distribution name. params (dict): \ A dict of named parameters. Raises: AttributeError: \ If an unsupported distribution is provided.
[ "Helper", "function", "that", "returns", "positional", "arguments", "for", "a", "scipy", "distribution", "using", "a", "dict", "of", "parameters", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L256-L291
235,848
great-expectations/great_expectations
great_expectations/dataset/util.py
create_multiple_expectations
def create_multiple_expectations(df, columns, expectation_type, *args, **kwargs): """Creates an identical expectation for each of the given columns with the specified arguments, if any. Args: df (great_expectations.dataset): A great expectations dataset object. columns (list): A list of column names represented as strings. expectation_type (string): The expectation type. Raises: KeyError if the provided column does not exist. AttributeError if the provided expectation type does not exist or df is not a valid great expectations dataset. Returns: A list of expectation results. """ expectation = getattr(df, expectation_type) results = list() for column in columns: results.append(expectation(column, *args, **kwargs)) return results
python
def create_multiple_expectations(df, columns, expectation_type, *args, **kwargs): expectation = getattr(df, expectation_type) results = list() for column in columns: results.append(expectation(column, *args, **kwargs)) return results
[ "def", "create_multiple_expectations", "(", "df", ",", "columns", ",", "expectation_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "expectation", "=", "getattr", "(", "df", ",", "expectation_type", ")", "results", "=", "list", "(", ")", "for",...
Creates an identical expectation for each of the given columns with the specified arguments, if any. Args: df (great_expectations.dataset): A great expectations dataset object. columns (list): A list of column names represented as strings. expectation_type (string): The expectation type. Raises: KeyError if the provided column does not exist. AttributeError if the provided expectation type does not exist or df is not a valid great expectations dataset. Returns: A list of expectation results.
[ "Creates", "an", "identical", "expectation", "for", "each", "of", "the", "given", "columns", "with", "the", "specified", "arguments", "if", "any", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/util.py#L422-L445
235,849
great-expectations/great_expectations
great_expectations/dataset/autoinspect.py
columns_exist
def columns_exist(inspect_dataset): """ This function will take a dataset and add expectations that each column present exists. Args: inspect_dataset (great_expectations.dataset): The dataset to inspect and to which to add expectations. """ # Attempt to get column names. For pandas, columns is just a list of strings if not hasattr(inspect_dataset, "columns"): warnings.warn( "No columns list found in dataset; no autoinspection performed.") return elif isinstance(inspect_dataset.columns[0], string_types): columns = inspect_dataset.columns elif isinstance(inspect_dataset.columns[0], dict) and "name" in inspect_dataset.columns[0]: columns = [col['name'] for col in inspect_dataset.columns] else: raise AutoInspectError( "Unable to determine column names for this dataset.") create_multiple_expectations( inspect_dataset, columns, "expect_column_to_exist")
python
def columns_exist(inspect_dataset): # Attempt to get column names. For pandas, columns is just a list of strings if not hasattr(inspect_dataset, "columns"): warnings.warn( "No columns list found in dataset; no autoinspection performed.") return elif isinstance(inspect_dataset.columns[0], string_types): columns = inspect_dataset.columns elif isinstance(inspect_dataset.columns[0], dict) and "name" in inspect_dataset.columns[0]: columns = [col['name'] for col in inspect_dataset.columns] else: raise AutoInspectError( "Unable to determine column names for this dataset.") create_multiple_expectations( inspect_dataset, columns, "expect_column_to_exist")
[ "def", "columns_exist", "(", "inspect_dataset", ")", ":", "# Attempt to get column names. For pandas, columns is just a list of strings", "if", "not", "hasattr", "(", "inspect_dataset", ",", "\"columns\"", ")", ":", "warnings", ".", "warn", "(", "\"No columns list found in da...
This function will take a dataset and add expectations that each column present exists. Args: inspect_dataset (great_expectations.dataset): The dataset to inspect and to which to add expectations.
[ "This", "function", "will", "take", "a", "dataset", "and", "add", "expectations", "that", "each", "column", "present", "exists", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/autoinspect.py#L23-L45
235,850
great-expectations/great_expectations
great_expectations/dataset/sqlalchemy_dataset.py
SqlAlchemyDataset.column_reflection_fallback
def column_reflection_fallback(self): """If we can't reflect the table, use a query to at least get column names.""" sql = sa.select([sa.text("*")]).select_from(self._table) col_names = self.engine.execute(sql).keys() col_dict = [{'name': col_name} for col_name in col_names] return col_dict
python
def column_reflection_fallback(self): sql = sa.select([sa.text("*")]).select_from(self._table) col_names = self.engine.execute(sql).keys() col_dict = [{'name': col_name} for col_name in col_names] return col_dict
[ "def", "column_reflection_fallback", "(", "self", ")", ":", "sql", "=", "sa", ".", "select", "(", "[", "sa", ".", "text", "(", "\"*\"", ")", "]", ")", ".", "select_from", "(", "self", ".", "_table", ")", "col_names", "=", "self", ".", "engine", ".", ...
If we can't reflect the table, use a query to at least get column names.
[ "If", "we", "can", "t", "reflect", "the", "table", "use", "a", "query", "to", "at", "least", "get", "column", "names", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/sqlalchemy_dataset.py#L303-L308
235,851
great-expectations/great_expectations
great_expectations/data_asset/util.py
parse_result_format
def parse_result_format(result_format): """This is a simple helper utility that can be used to parse a string result_format into the dict format used internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where there is no need to specify a custom partial_unexpected_count.""" if isinstance(result_format, string_types): result_format = { 'result_format': result_format, 'partial_unexpected_count': 20 } else: if 'partial_unexpected_count' not in result_format: result_format['partial_unexpected_count'] = 20 return result_format
python
def parse_result_format(result_format): if isinstance(result_format, string_types): result_format = { 'result_format': result_format, 'partial_unexpected_count': 20 } else: if 'partial_unexpected_count' not in result_format: result_format['partial_unexpected_count'] = 20 return result_format
[ "def", "parse_result_format", "(", "result_format", ")", ":", "if", "isinstance", "(", "result_format", ",", "string_types", ")", ":", "result_format", "=", "{", "'result_format'", ":", "result_format", ",", "'partial_unexpected_count'", ":", "20", "}", "else", ":...
This is a simple helper utility that can be used to parse a string result_format into the dict format used internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where there is no need to specify a custom partial_unexpected_count.
[ "This", "is", "a", "simple", "helper", "utility", "that", "can", "be", "used", "to", "parse", "a", "string", "result_format", "into", "the", "dict", "format", "used", "internally", "by", "great_expectations", ".", "It", "is", "not", "necessary", "but", "allo...
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/util.py#L18-L31
235,852
great-expectations/great_expectations
great_expectations/data_asset/util.py
recursively_convert_to_json_serializable
def recursively_convert_to_json_serializable(test_obj): """ Helper function to convert a dict object to one that is serializable Args: test_obj: an object to attempt to convert a corresponding json-serializable object Returns: (dict) A converted test_object Warning: test_obj may also be converted in place. """ # Validate that all aruguments are of approved types, coerce if it's easy, else exception # print(type(test_obj), test_obj) # Note: Not 100% sure I've resolved this correctly... try: if not isinstance(test_obj, list) and np.isnan(test_obj): # np.isnan is functionally vectorized, but we only want to apply this to single objects # Hence, why we test for `not isinstance(list))` return None except TypeError: pass except ValueError: pass if isinstance(test_obj, (string_types, integer_types, float, bool)): # No problem to encode json return test_obj elif isinstance(test_obj, dict): new_dict = {} for key in test_obj: # A pandas index can be numeric, and a dict key can be numeric, but a json key must be a string new_dict[str(key)] = recursively_convert_to_json_serializable( test_obj[key]) return new_dict elif isinstance(test_obj, (list, tuple, set)): new_list = [] for val in test_obj: new_list.append(recursively_convert_to_json_serializable(val)) return new_list elif isinstance(test_obj, (np.ndarray, pd.Index)): #test_obj[key] = test_obj[key].tolist() # If we have an array or index, convert it first to a list--causing coercion to float--and then round # to the number of digits for which the string representation will equal the float representation return [recursively_convert_to_json_serializable(x) for x in test_obj.tolist()] # Note: This clause has to come after checking for np.ndarray or we get: # `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()` elif test_obj is None: # No problem to encode json return test_obj elif isinstance(test_obj, (datetime.datetime, datetime.date)): return str(test_obj) # Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html # https://github.com/numpy/numpy/pull/9505 elif np.issubdtype(type(test_obj), np.bool_): return bool(test_obj) elif np.issubdtype(type(test_obj), np.integer) or np.issubdtype(type(test_obj), np.uint): return int(test_obj) elif np.issubdtype(type(test_obj), np.floating): # Note: Use np.floating to avoid FutureWarning from numpy return float(round(test_obj, sys.float_info.dig)) elif isinstance(test_obj, pd.DataFrame): return recursively_convert_to_json_serializable(test_obj.to_dict(orient='records')) # elif np.issubdtype(type(test_obj), np.complexfloating): # Note: Use np.complexfloating to avoid Future Warning from numpy # Complex numbers consist of two floating point numbers # return complex( # float(round(test_obj.real, sys.float_info.dig)), # float(round(test_obj.imag, sys.float_info.dig))) elif isinstance(test_obj, decimal.Decimal): return float(test_obj) else: raise TypeError('%s is of type %s which cannot be serialized.' % ( str(test_obj), type(test_obj).__name__))
python
def recursively_convert_to_json_serializable(test_obj): # Validate that all aruguments are of approved types, coerce if it's easy, else exception # print(type(test_obj), test_obj) # Note: Not 100% sure I've resolved this correctly... try: if not isinstance(test_obj, list) and np.isnan(test_obj): # np.isnan is functionally vectorized, but we only want to apply this to single objects # Hence, why we test for `not isinstance(list))` return None except TypeError: pass except ValueError: pass if isinstance(test_obj, (string_types, integer_types, float, bool)): # No problem to encode json return test_obj elif isinstance(test_obj, dict): new_dict = {} for key in test_obj: # A pandas index can be numeric, and a dict key can be numeric, but a json key must be a string new_dict[str(key)] = recursively_convert_to_json_serializable( test_obj[key]) return new_dict elif isinstance(test_obj, (list, tuple, set)): new_list = [] for val in test_obj: new_list.append(recursively_convert_to_json_serializable(val)) return new_list elif isinstance(test_obj, (np.ndarray, pd.Index)): #test_obj[key] = test_obj[key].tolist() # If we have an array or index, convert it first to a list--causing coercion to float--and then round # to the number of digits for which the string representation will equal the float representation return [recursively_convert_to_json_serializable(x) for x in test_obj.tolist()] # Note: This clause has to come after checking for np.ndarray or we get: # `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()` elif test_obj is None: # No problem to encode json return test_obj elif isinstance(test_obj, (datetime.datetime, datetime.date)): return str(test_obj) # Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html # https://github.com/numpy/numpy/pull/9505 elif np.issubdtype(type(test_obj), np.bool_): return bool(test_obj) elif np.issubdtype(type(test_obj), np.integer) or np.issubdtype(type(test_obj), np.uint): return int(test_obj) elif np.issubdtype(type(test_obj), np.floating): # Note: Use np.floating to avoid FutureWarning from numpy return float(round(test_obj, sys.float_info.dig)) elif isinstance(test_obj, pd.DataFrame): return recursively_convert_to_json_serializable(test_obj.to_dict(orient='records')) # elif np.issubdtype(type(test_obj), np.complexfloating): # Note: Use np.complexfloating to avoid Future Warning from numpy # Complex numbers consist of two floating point numbers # return complex( # float(round(test_obj.real, sys.float_info.dig)), # float(round(test_obj.imag, sys.float_info.dig))) elif isinstance(test_obj, decimal.Decimal): return float(test_obj) else: raise TypeError('%s is of type %s which cannot be serialized.' % ( str(test_obj), type(test_obj).__name__))
[ "def", "recursively_convert_to_json_serializable", "(", "test_obj", ")", ":", "# Validate that all aruguments are of approved types, coerce if it's easy, else exception", "# print(type(test_obj), test_obj)", "# Note: Not 100% sure I've resolved this correctly...", "try", ":", "if", "not", ...
Helper function to convert a dict object to one that is serializable Args: test_obj: an object to attempt to convert a corresponding json-serializable object Returns: (dict) A converted test_object Warning: test_obj may also be converted in place.
[ "Helper", "function", "to", "convert", "a", "dict", "object", "to", "one", "that", "is", "serializable" ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/util.py#L106-L195
235,853
great-expectations/great_expectations
great_expectations/util.py
read_excel
def read_excel( filename, dataset_class=dataset.pandas_dataset.PandasDataset, expectations_config=None, autoinspect_func=None, *args, **kwargs ): """Read a file using Pandas read_excel and return a great_expectations dataset. Args: filename (string): path to file to read dataset_class (Dataset class): class to which to convert resulting Pandas df expectations_config (string): path to great_expectations config file Returns: great_expectations dataset or ordered dict of great_expectations datasets, if multiple worksheets are imported """ df = pd.read_excel(filename, *args, **kwargs) if isinstance(df, dict): for key in df: df[key] = _convert_to_dataset_class( df[key], dataset_class, expectations_config, autoinspect_func) else: df = _convert_to_dataset_class( df, dataset_class, expectations_config, autoinspect_func) return df
python
def read_excel( filename, dataset_class=dataset.pandas_dataset.PandasDataset, expectations_config=None, autoinspect_func=None, *args, **kwargs ): df = pd.read_excel(filename, *args, **kwargs) if isinstance(df, dict): for key in df: df[key] = _convert_to_dataset_class( df[key], dataset_class, expectations_config, autoinspect_func) else: df = _convert_to_dataset_class( df, dataset_class, expectations_config, autoinspect_func) return df
[ "def", "read_excel", "(", "filename", ",", "dataset_class", "=", "dataset", ".", "pandas_dataset", ".", "PandasDataset", ",", "expectations_config", "=", "None", ",", "autoinspect_func", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "df",...
Read a file using Pandas read_excel and return a great_expectations dataset. Args: filename (string): path to file to read dataset_class (Dataset class): class to which to convert resulting Pandas df expectations_config (string): path to great_expectations config file Returns: great_expectations dataset or ordered dict of great_expectations datasets, if multiple worksheets are imported
[ "Read", "a", "file", "using", "Pandas", "read_excel", "and", "return", "a", "great_expectations", "dataset", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/util.py#L60-L86
235,854
great-expectations/great_expectations
great_expectations/util.py
from_pandas
def from_pandas(pandas_df, dataset_class=dataset.pandas_dataset.PandasDataset, expectations_config=None, autoinspect_func=None ): """Read a Pandas data frame and return a great_expectations dataset. Args: pandas_df (Pandas df): Pandas data frame dataset_class (Dataset class) = dataset.pandas_dataset.PandasDataset: class to which to convert resulting Pandas df expectations_config (string) = None: path to great_expectations config file autoinspect_func (function) = None: The autoinspection function that should be run on the dataset to establish baseline expectations. Returns: great_expectations dataset """ return _convert_to_dataset_class( pandas_df, dataset_class, expectations_config, autoinspect_func )
python
def from_pandas(pandas_df, dataset_class=dataset.pandas_dataset.PandasDataset, expectations_config=None, autoinspect_func=None ): return _convert_to_dataset_class( pandas_df, dataset_class, expectations_config, autoinspect_func )
[ "def", "from_pandas", "(", "pandas_df", ",", "dataset_class", "=", "dataset", ".", "pandas_dataset", ".", "PandasDataset", ",", "expectations_config", "=", "None", ",", "autoinspect_func", "=", "None", ")", ":", "return", "_convert_to_dataset_class", "(", "pandas_df...
Read a Pandas data frame and return a great_expectations dataset. Args: pandas_df (Pandas df): Pandas data frame dataset_class (Dataset class) = dataset.pandas_dataset.PandasDataset: class to which to convert resulting Pandas df expectations_config (string) = None: path to great_expectations config file autoinspect_func (function) = None: The autoinspection function that should be run on the dataset to establish baseline expectations. Returns: great_expectations dataset
[ "Read", "a", "Pandas", "data", "frame", "and", "return", "a", "great_expectations", "dataset", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/util.py#L135-L158
235,855
great-expectations/great_expectations
great_expectations/data_asset/file_data_asset.py
MetaFileDataAsset.file_lines_map_expectation
def file_lines_map_expectation(cls, func): """Constructs an expectation using file lines map semantics. The file_lines_map_expectations decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on an line by line basis in a file. Args: func (function): \ The function implementing an expectation that will be applied line by line across a file. The function should take a file and return information about how many lines met expectations. Notes: Users can specify skip value k that will cause the expectation function to disregard the first k lines of the file. file_lines_map_expectation will add a kwarg _lines to the called function with the nonnull lines \ to process. null_lines_regex defines a regex used to skip lines, but can be overridden See also: :func:`expect_file_line_regex_match_count_to_be_between <great_expectations.data_asset.base.DataAsset.expect_file_line_regex_match_count_to_be_between>` \ for an example of a file_lines_map_expectation """ if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, skip=None, mostly=None, null_lines_regex=r"^\s*$", result_format=None, *args, **kwargs): try: f = open(self._path, "r") except: raise if result_format is None: result_format = self.default_expectation_args["result_format"] result_format = parse_result_format(result_format) lines = f.readlines() #Read in file lines #Skip k initial lines designated by the user if skip is not None and skip <= len(lines): try: assert float(skip).is_integer() assert float(skip) >= 0 except: raise ValueError("skip must be a positive integer") for i in range(1, skip+1): lines.pop(0) if lines: if null_lines_regex is not None: null_lines = re.compile(null_lines_regex) #Ignore lines that are empty or have only white space ("null values" in the line-map context) boolean_mapped_null_lines = np.array( [bool(null_lines.match(line)) for line in lines]) else: boolean_mapped_null_lines = np.zeros(len(lines), dtype=bool) element_count = int(len(lines)) if element_count > sum(boolean_mapped_null_lines): nonnull_lines = list(compress(lines, np.invert(boolean_mapped_null_lines))) nonnull_count = int((boolean_mapped_null_lines == False).sum()) boolean_mapped_success_lines = np.array( func(self, _lines=nonnull_lines, *args, **kwargs)) success_count = np.count_nonzero(boolean_mapped_success_lines) unexpected_list = list(compress(nonnull_lines, \ np.invert(boolean_mapped_success_lines))) nonnull_lines_index = range(0, len(nonnull_lines)+1) unexpected_index_list = list(compress(nonnull_lines_index, np.invert(boolean_mapped_success_lines))) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list, unexpected_index_list ) else: return_obj = self._format_map_output( result_format=result_format, success=None, element_count=element_count, nonnull_count=0, unexpected_count=0, unexpected_list=[], unexpected_index_list=[] ) else: return_obj = self._format_map_output(result_format=result_format, success=None, element_count=0, nonnull_count=0, unexpected_count=0, unexpected_list=[], unexpected_index_list=[]) f.close() return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
python
def file_lines_map_expectation(cls, func): if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, skip=None, mostly=None, null_lines_regex=r"^\s*$", result_format=None, *args, **kwargs): try: f = open(self._path, "r") except: raise if result_format is None: result_format = self.default_expectation_args["result_format"] result_format = parse_result_format(result_format) lines = f.readlines() #Read in file lines #Skip k initial lines designated by the user if skip is not None and skip <= len(lines): try: assert float(skip).is_integer() assert float(skip) >= 0 except: raise ValueError("skip must be a positive integer") for i in range(1, skip+1): lines.pop(0) if lines: if null_lines_regex is not None: null_lines = re.compile(null_lines_regex) #Ignore lines that are empty or have only white space ("null values" in the line-map context) boolean_mapped_null_lines = np.array( [bool(null_lines.match(line)) for line in lines]) else: boolean_mapped_null_lines = np.zeros(len(lines), dtype=bool) element_count = int(len(lines)) if element_count > sum(boolean_mapped_null_lines): nonnull_lines = list(compress(lines, np.invert(boolean_mapped_null_lines))) nonnull_count = int((boolean_mapped_null_lines == False).sum()) boolean_mapped_success_lines = np.array( func(self, _lines=nonnull_lines, *args, **kwargs)) success_count = np.count_nonzero(boolean_mapped_success_lines) unexpected_list = list(compress(nonnull_lines, \ np.invert(boolean_mapped_success_lines))) nonnull_lines_index = range(0, len(nonnull_lines)+1) unexpected_index_list = list(compress(nonnull_lines_index, np.invert(boolean_mapped_success_lines))) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list, unexpected_index_list ) else: return_obj = self._format_map_output( result_format=result_format, success=None, element_count=element_count, nonnull_count=0, unexpected_count=0, unexpected_list=[], unexpected_index_list=[] ) else: return_obj = self._format_map_output(result_format=result_format, success=None, element_count=0, nonnull_count=0, unexpected_count=0, unexpected_list=[], unexpected_index_list=[]) f.close() return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
[ "def", "file_lines_map_expectation", "(", "cls", ",", "func", ")", ":", "if", "PY3", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "[", "0", "]", "[", "1", ":", "]", "else", ":", "argspec", "=", "inspect", ".", "getargspec", ...
Constructs an expectation using file lines map semantics. The file_lines_map_expectations decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on an line by line basis in a file. Args: func (function): \ The function implementing an expectation that will be applied line by line across a file. The function should take a file and return information about how many lines met expectations. Notes: Users can specify skip value k that will cause the expectation function to disregard the first k lines of the file. file_lines_map_expectation will add a kwarg _lines to the called function with the nonnull lines \ to process. null_lines_regex defines a regex used to skip lines, but can be overridden See also: :func:`expect_file_line_regex_match_count_to_be_between <great_expectations.data_asset.base.DataAsset.expect_file_line_regex_match_count_to_be_between>` \ for an example of a file_lines_map_expectation
[ "Constructs", "an", "expectation", "using", "file", "lines", "map", "semantics", ".", "The", "file_lines_map_expectations", "decorator", "handles", "boilerplate", "issues", "surrounding", "the", "common", "pattern", "of", "evaluating", "truthiness", "of", "some", "con...
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L28-L132
235,856
great-expectations/great_expectations
great_expectations/data_asset/file_data_asset.py
FileDataAsset.expect_file_hash_to_equal
def expect_file_hash_to_equal(self, value, hash_alg='md5', result_format=None, include_config=False, catch_exceptions=None, meta=None): """ Expect computed file hash to equal some given value. Args: value: A string to compare with the computed hash value Keyword Args: hash_alg (string): Indicates the hash algorithm to use result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ success = False try: hash = hashlib.new(hash_alg) # Limit file reads to 64 KB chunks at a time BLOCKSIZE = 65536 try: with open(self._path, 'rb') as file: file_buffer = file.read(BLOCKSIZE) while file_buffer: hash.update(file_buffer) file_buffer = file.read(BLOCKSIZE) success = hash.hexdigest() == value except IOError: raise except ValueError: raise return {"success":success}
python
def expect_file_hash_to_equal(self, value, hash_alg='md5', result_format=None, include_config=False, catch_exceptions=None, meta=None): success = False try: hash = hashlib.new(hash_alg) # Limit file reads to 64 KB chunks at a time BLOCKSIZE = 65536 try: with open(self._path, 'rb') as file: file_buffer = file.read(BLOCKSIZE) while file_buffer: hash.update(file_buffer) file_buffer = file.read(BLOCKSIZE) success = hash.hexdigest() == value except IOError: raise except ValueError: raise return {"success":success}
[ "def", "expect_file_hash_to_equal", "(", "self", ",", "value", ",", "hash_alg", "=", "'md5'", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ")", ":", "success", "=", ...
Expect computed file hash to equal some given value. Args: value: A string to compare with the computed hash value Keyword Args: hash_alg (string): Indicates the hash algorithm to use result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Expect", "computed", "file", "hash", "to", "equal", "some", "given", "value", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L336-L387
235,857
great-expectations/great_expectations
great_expectations/data_asset/file_data_asset.py
FileDataAsset.expect_file_size_to_be_between
def expect_file_size_to_be_between(self, minsize=0, maxsize=None, result_format=None, include_config=False, catch_exceptions=None, meta=None): """ Expect file size to be between a user specified maxsize and minsize. Args: minsize(integer): minimum expected file size maxsize(integer): maximum expected file size Keyword Args: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ try: size = os.path.getsize(self._path) except OSError: raise # We want string or float or int versions of numbers, but # they must be representable as clean integers. try: if not float(minsize).is_integer(): raise ValueError('minsize must be an integer') minsize = int(float(minsize)) if maxsize is not None and not float(maxsize).is_integer(): raise ValueError('maxsize must be an integer') elif maxsize is not None: maxsize = int(float(maxsize)) except TypeError: raise if minsize < 0: raise ValueError('minsize must be greater than or equal to 0') if maxsize is not None and maxsize < 0: raise ValueError('maxsize must be greater than or equal to 0') if maxsize is not None and minsize > maxsize: raise ValueError('maxsize must be greater than or equal to minsize') if maxsize is None and size >= minsize: success = True elif (size >= minsize) and (size <= maxsize): success = True else: success = False return { "success": success, "details": { "filesize": size } }
python
def expect_file_size_to_be_between(self, minsize=0, maxsize=None, result_format=None, include_config=False, catch_exceptions=None, meta=None): try: size = os.path.getsize(self._path) except OSError: raise # We want string or float or int versions of numbers, but # they must be representable as clean integers. try: if not float(minsize).is_integer(): raise ValueError('minsize must be an integer') minsize = int(float(minsize)) if maxsize is not None and not float(maxsize).is_integer(): raise ValueError('maxsize must be an integer') elif maxsize is not None: maxsize = int(float(maxsize)) except TypeError: raise if minsize < 0: raise ValueError('minsize must be greater than or equal to 0') if maxsize is not None and maxsize < 0: raise ValueError('maxsize must be greater than or equal to 0') if maxsize is not None and minsize > maxsize: raise ValueError('maxsize must be greater than or equal to minsize') if maxsize is None and size >= minsize: success = True elif (size >= minsize) and (size <= maxsize): success = True else: success = False return { "success": success, "details": { "filesize": size } }
[ "def", "expect_file_size_to_be_between", "(", "self", ",", "minsize", "=", "0", ",", "maxsize", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ")", ":", "...
Expect file size to be between a user specified maxsize and minsize. Args: minsize(integer): minimum expected file size maxsize(integer): maximum expected file size Keyword Args: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Expect", "file", "size", "to", "be", "between", "a", "user", "specified", "maxsize", "and", "minsize", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L390-L464
235,858
great-expectations/great_expectations
great_expectations/data_asset/file_data_asset.py
FileDataAsset.expect_file_to_exist
def expect_file_to_exist(self, filepath=None, result_format=None, include_config=False, catch_exceptions=None, meta=None): """ Checks to see if a file specified by the user actually exists Args: filepath (str or None): \ The filepath to evalutate. If none, will check the currently-configured path object of this FileDataAsset. Keyword Args: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ if filepath is not None and os.path.isfile(filepath): success = True elif self._path is not None and os.path.isfile(self._path): success = True else: success = False return {"success":success}
python
def expect_file_to_exist(self, filepath=None, result_format=None, include_config=False, catch_exceptions=None, meta=None): if filepath is not None and os.path.isfile(filepath): success = True elif self._path is not None and os.path.isfile(self._path): success = True else: success = False return {"success":success}
[ "def", "expect_file_to_exist", "(", "self", ",", "filepath", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ")", ":", "if", "filepath", "is", "not", "None...
Checks to see if a file specified by the user actually exists Args: filepath (str or None): \ The filepath to evalutate. If none, will check the currently-configured path object of this FileDataAsset. Keyword Args: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Checks", "to", "see", "if", "a", "file", "specified", "by", "the", "user", "actually", "exists" ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L467-L511
235,859
great-expectations/great_expectations
great_expectations/data_asset/file_data_asset.py
FileDataAsset.expect_file_to_have_valid_table_header
def expect_file_to_have_valid_table_header(self, regex, skip=None, result_format=None, include_config=False, catch_exceptions=None, meta=None): """ Checks to see if a file has a line with unique delimited values, such a line may be used as a table header. Keyword Args: skip (nonnegative integer): \ Integer specifying the first lines in the file the method should skip before assessing expectations regex (string): A string that can be compiled as valid regular expression. Used to specify the elements of the table header (the column headers) result_format (str or None): Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ try: comp_regex = re.compile(regex) except: raise ValueError("Must enter valid regular expression for regex") success = False try: with open(self._path, 'r') as f: lines = f.readlines() #Read in file lines except IOError: raise #Skip k initial lines designated by the user if skip is not None and skip <= len(lines): try: assert float(skip).is_integer() assert float(skip) >= 0 except: raise ValueError("skip must be a positive integer") lines = lines[skip:] header_line = lines[0].strip() header_names = comp_regex.split(header_line) if len(set(header_names)) == len(header_names): success = True return {"success":success}
python
def expect_file_to_have_valid_table_header(self, regex, skip=None, result_format=None, include_config=False, catch_exceptions=None, meta=None): try: comp_regex = re.compile(regex) except: raise ValueError("Must enter valid regular expression for regex") success = False try: with open(self._path, 'r') as f: lines = f.readlines() #Read in file lines except IOError: raise #Skip k initial lines designated by the user if skip is not None and skip <= len(lines): try: assert float(skip).is_integer() assert float(skip) >= 0 except: raise ValueError("skip must be a positive integer") lines = lines[skip:] header_line = lines[0].strip() header_names = comp_regex.split(header_line) if len(set(header_names)) == len(header_names): success = True return {"success":success}
[ "def", "expect_file_to_have_valid_table_header", "(", "self", ",", "regex", ",", "skip", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ")", ":", "try", ":"...
Checks to see if a file has a line with unique delimited values, such a line may be used as a table header. Keyword Args: skip (nonnegative integer): \ Integer specifying the first lines in the file the method should skip before assessing expectations regex (string): A string that can be compiled as valid regular expression. Used to specify the elements of the table header (the column headers) result_format (str or None): Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Checks", "to", "see", "if", "a", "file", "has", "a", "line", "with", "unique", "delimited", "values", "such", "a", "line", "may", "be", "used", "as", "a", "table", "header", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/file_data_asset.py#L514-L584
235,860
great-expectations/great_expectations
great_expectations/data_context/__init__.py
get_data_context
def get_data_context(context_type, options, *args, **kwargs): """Return a data_context object which exposes options to list datasets and get a dataset from that context. This is a new API in Great Expectations 0.4, and is subject to rapid change. :param context_type: (string) one of "SqlAlchemy" or "PandasCSV" :param options: options to be passed to the data context's connect method. :return: a new DataContext object """ if context_type == "SqlAlchemy": return SqlAlchemyDataContext(options, *args, **kwargs) elif context_type == "PandasCSV": return PandasCSVDataContext(options, *args, **kwargs) else: raise ValueError("Unknown data context.")
python
def get_data_context(context_type, options, *args, **kwargs): if context_type == "SqlAlchemy": return SqlAlchemyDataContext(options, *args, **kwargs) elif context_type == "PandasCSV": return PandasCSVDataContext(options, *args, **kwargs) else: raise ValueError("Unknown data context.")
[ "def", "get_data_context", "(", "context_type", ",", "options", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "context_type", "==", "\"SqlAlchemy\"", ":", "return", "SqlAlchemyDataContext", "(", "options", ",", "*", "args", ",", "*", "*", "kwa...
Return a data_context object which exposes options to list datasets and get a dataset from that context. This is a new API in Great Expectations 0.4, and is subject to rapid change. :param context_type: (string) one of "SqlAlchemy" or "PandasCSV" :param options: options to be passed to the data context's connect method. :return: a new DataContext object
[ "Return", "a", "data_context", "object", "which", "exposes", "options", "to", "list", "datasets", "and", "get", "a", "dataset", "from", "that", "context", ".", "This", "is", "a", "new", "API", "in", "Great", "Expectations", "0", ".", "4", "and", "is", "s...
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_context/__init__.py#L5-L18
235,861
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset._initialize_expectations
def _initialize_expectations(self, config=None, data_asset_name=None): """Override data_asset_type with "Dataset" """ super(Dataset, self)._initialize_expectations(config=config, data_asset_name=data_asset_name) self._expectations_config["data_asset_type"] = "Dataset"
python
def _initialize_expectations(self, config=None, data_asset_name=None): super(Dataset, self)._initialize_expectations(config=config, data_asset_name=data_asset_name) self._expectations_config["data_asset_type"] = "Dataset"
[ "def", "_initialize_expectations", "(", "self", ",", "config", "=", "None", ",", "data_asset_name", "=", "None", ")", ":", "super", "(", "Dataset", ",", "self", ")", ".", "_initialize_expectations", "(", "config", "=", "config", ",", "data_asset_name", "=", ...
Override data_asset_type with "Dataset"
[ "Override", "data_asset_type", "with", "Dataset" ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L9-L13
235,862
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_to_exist
def expect_column_to_exist( self, column, column_index=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect the specified column to exist. expect_column_to_exist is a :func:`expectation <great_expectations.data_asset.dataset.Dataset.expectation>`, not a \ `column_map_expectation` or `column_aggregate_expectation`. Args: column (str): \ The column name. Other Parameters: column_index (int or None): \ If not None, checks the order of the columns. The expectation will fail if the \ column is not in location column_index (zero-indexed). result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ raise NotImplementedError
python
def expect_column_to_exist( self, column, column_index=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_to_exist", "(", "self", ",", "column", ",", "column_index", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ")", ":", "raise", "NotImpl...
Expect the specified column to exist. expect_column_to_exist is a :func:`expectation <great_expectations.data_asset.dataset.Dataset.expectation>`, not a \ `column_map_expectation` or `column_aggregate_expectation`. Args: column (str): \ The column name. Other Parameters: column_index (int or None): \ If not None, checks the order of the columns. The expectation will fail if the \ column is not in location column_index (zero-indexed). result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Expect", "the", "specified", "column", "to", "exist", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L111-L149
235,863
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_table_row_count_to_be_between
def expect_table_row_count_to_be_between(self, min_value=0, max_value=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect the number of rows to be between two values. expect_table_row_count_to_be_between is a :func:`expectation <great_expectations.data_asset.dataset.Dataset.expectation>`, \ not a `column_map_expectation` or `column_aggregate_expectation`. Keyword Args: min_value (int or None): \ The minimum number of rows, inclusive. max_value (int or None): \ The maximum number of rows, inclusive. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Notes: * min_value and max_value are both inclusive. * If min_value is None, then max_value is treated as an upper bound, and the number of acceptable rows has no minimum. * If max_value is None, then min_value is treated as a lower bound, and the number of acceptable rows has no maximum. See Also: expect_table_row_count_to_equal """ raise NotImplementedError
python
def expect_table_row_count_to_be_between(self, min_value=0, max_value=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_table_row_count_to_be_between", "(", "self", ",", "min_value", "=", "0", ",", "max_value", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ")", ...
Expect the number of rows to be between two values. expect_table_row_count_to_be_between is a :func:`expectation <great_expectations.data_asset.dataset.Dataset.expectation>`, \ not a `column_map_expectation` or `column_aggregate_expectation`. Keyword Args: min_value (int or None): \ The minimum number of rows, inclusive. max_value (int or None): \ The maximum number of rows, inclusive. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Notes: * min_value and max_value are both inclusive. * If min_value is None, then max_value is treated as an upper bound, and the number of acceptable rows has no minimum. * If max_value is None, then min_value is treated as a lower bound, and the number of acceptable rows has no maximum. See Also: expect_table_row_count_to_equal
[ "Expect", "the", "number", "of", "rows", "to", "be", "between", "two", "values", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L188-L232
235,864
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_values_to_be_of_type
def expect_column_values_to_be_of_type( self, column, type_, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect each column entry to be a specified data type. expect_column_values_to_be_of_type is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. type\_ (str): \ A string representing the data type that each column should have as entries. For example, "double integer" refers to an integer with double precision. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Warning: expect_column_values_to_be_of_type is slated for major changes in future versions of great_expectations. As of v0.3, great_expectations is exclusively based on pandas, which handles typing in its own peculiar way. Future versions of great_expectations will allow for Datasets in SQL, spark, etc. When we make that change, we expect some breaking changes in parts of the codebase that are based strongly on pandas notions of typing. See also: expect_column_values_to_be_in_type_list """ raise NotImplementedError
python
def expect_column_values_to_be_of_type( self, column, type_, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_values_to_be_of_type", "(", "self", ",", "column", ",", "type_", ",", "mostly", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ")", ":...
Expect each column entry to be a specified data type. expect_column_values_to_be_of_type is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. type\_ (str): \ A string representing the data type that each column should have as entries. For example, "double integer" refers to an integer with double precision. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Warning: expect_column_values_to_be_of_type is slated for major changes in future versions of great_expectations. As of v0.3, great_expectations is exclusively based on pandas, which handles typing in its own peculiar way. Future versions of great_expectations will allow for Datasets in SQL, spark, etc. When we make that change, we expect some breaking changes in parts of the codebase that are based strongly on pandas notions of typing. See also: expect_column_values_to_be_in_type_list
[ "Expect", "each", "column", "entry", "to", "be", "a", "specified", "data", "type", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L409-L462
235,865
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_values_to_be_in_type_list
def expect_column_values_to_be_in_type_list( self, column, type_list, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect each column entry to match a list of specified data types. expect_column_values_to_be_in_type_list is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. type_list (list of str): \ A list of strings representing the data type that each column should have as entries. For example, "double integer" refers to an integer with double precision. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Warning: expect_column_values_to_be_in_type_list is slated for major changes in future versions of great_expectations. As of v0.3, great_expectations is exclusively based on pandas, which handles typing in its own peculiar way. Future versions of great_expectations will allow for Datasets in SQL, spark, etc. When we make that change, we expect some breaking changes in parts of the codebase that are based strongly on pandas notions of typing. See also: expect_column_values_to_be_of_type """ raise NotImplementedError
python
def expect_column_values_to_be_in_type_list( self, column, type_list, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_values_to_be_in_type_list", "(", "self", ",", "column", ",", "type_list", ",", "mostly", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ...
Expect each column entry to match a list of specified data types. expect_column_values_to_be_in_type_list is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. type_list (list of str): \ A list of strings representing the data type that each column should have as entries. For example, "double integer" refers to an integer with double precision. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Warning: expect_column_values_to_be_in_type_list is slated for major changes in future versions of great_expectations. As of v0.3, great_expectations is exclusively based on pandas, which handles typing in its own peculiar way. Future versions of great_expectations will allow for Datasets in SQL, spark, etc. When we make that change, we expect some breaking changes in parts of the codebase that are based strongly on pandas notions of typing. See also: expect_column_values_to_be_of_type
[ "Expect", "each", "column", "entry", "to", "match", "a", "list", "of", "specified", "data", "types", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L464-L517
235,866
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_values_to_be_in_set
def expect_column_values_to_be_in_set(self, column, value_set, mostly=None, parse_strings_as_datetimes=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect each column value to be in a given set. For example: :: # my_df.my_col = [1,2,2,3,3,3] >>> my_df.expect_column_values_to_be_in_set( "my_col", [2,3] ) { "success": false "result": { "unexpected_count": 1 "unexpected_percent": 0.16666666666666666, "unexpected_percent_nonmissing": 0.16666666666666666, "partial_unexpected_list": [ 1 ], }, } expect_column_values_to_be_in_set is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. value_set (set-like): \ A set of objects used for comparison. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. parse_strings_as_datetimes (boolean or None) : If True values provided in value_set will be parsed as \ datetimes before making comparisons. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_not_be_in_set """ raise NotImplementedError
python
def expect_column_values_to_be_in_set(self, column, value_set, mostly=None, parse_strings_as_datetimes=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_values_to_be_in_set", "(", "self", ",", "column", ",", "value_set", ",", "mostly", "=", "None", ",", "parse_strings_as_datetimes", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "...
Expect each column value to be in a given set. For example: :: # my_df.my_col = [1,2,2,3,3,3] >>> my_df.expect_column_values_to_be_in_set( "my_col", [2,3] ) { "success": false "result": { "unexpected_count": 1 "unexpected_percent": 0.16666666666666666, "unexpected_percent_nonmissing": 0.16666666666666666, "partial_unexpected_list": [ 1 ], }, } expect_column_values_to_be_in_set is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. value_set (set-like): \ A set of objects used for comparison. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. parse_strings_as_datetimes (boolean or None) : If True values provided in value_set will be parsed as \ datetimes before making comparisons. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_not_be_in_set
[ "Expect", "each", "column", "value", "to", "be", "in", "a", "given", "set", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L521-L589
235,867
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_values_to_be_decreasing
def expect_column_values_to_be_decreasing(self, column, strictly=None, parse_strings_as_datetimes=None, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect column values to be decreasing. By default, this expectation only works for numeric or datetime data. When `parse_strings_as_datetimes=True`, it can also parse strings to datetimes. If `strictly=True`, then this expectation is only satisfied if each consecutive value is strictly decreasing--equal values are treated as failures. expect_column_values_to_be_decreasing is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. Keyword Args: strictly (Boolean or None): \ If True, values must be strictly greater than previous values parse_strings_as_datetimes (boolean or None) : \ If True, all non-null column values to datetimes before making comparisons mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_be_increasing """ raise NotImplementedError
python
def expect_column_values_to_be_decreasing(self, column, strictly=None, parse_strings_as_datetimes=None, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_values_to_be_decreasing", "(", "self", ",", "column", ",", "strictly", "=", "None", ",", "parse_strings_as_datetimes", "=", "None", ",", "mostly", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "ca...
Expect column values to be decreasing. By default, this expectation only works for numeric or datetime data. When `parse_strings_as_datetimes=True`, it can also parse strings to datetimes. If `strictly=True`, then this expectation is only satisfied if each consecutive value is strictly decreasing--equal values are treated as failures. expect_column_values_to_be_decreasing is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. Keyword Args: strictly (Boolean or None): \ If True, values must be strictly greater than previous values parse_strings_as_datetimes (boolean or None) : \ If True, all non-null column values to datetimes before making comparisons mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_be_increasing
[ "Expect", "column", "values", "to", "be", "decreasing", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L776-L830
235,868
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_values_to_match_regex_list
def expect_column_values_to_match_regex_list(self, column, regex_list, match_on="any", mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect the column entries to be strings that can be matched to either any of or all of a list of regular expressions. Matches can be anywhere in the string. expect_column_values_to_match_regex_list is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. regex_list (list): \ The list of regular expressions which the column entries should match Keyword Args: match_on= (string): \ "any" or "all". Use "any" if the value should match at least one regular expression in the list. Use "all" if it should match each regular expression in the list. mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_match_regex expect_column_values_to_not_match_regex """ raise NotImplementedError
python
def expect_column_values_to_match_regex_list(self, column, regex_list, match_on="any", mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_values_to_match_regex_list", "(", "self", ",", "column", ",", "regex_list", ",", "match_on", "=", "\"any\"", ",", "mostly", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "...
Expect the column entries to be strings that can be matched to either any of or all of a list of regular expressions. Matches can be anywhere in the string. expect_column_values_to_match_regex_list is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. regex_list (list): \ The list of regular expressions which the column entries should match Keyword Args: match_on= (string): \ "any" or "all". Use "any" if the value should match at least one regular expression in the list. Use "all" if it should match each regular expression in the list. mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_match_regex expect_column_values_to_not_match_regex
[ "Expect", "the", "column", "entries", "to", "be", "strings", "that", "can", "be", "matched", "to", "either", "any", "of", "or", "all", "of", "a", "list", "of", "regular", "expressions", ".", "Matches", "can", "be", "anywhere", "in", "the", "string", "." ...
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L1035-L1086
235,869
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_values_to_not_match_regex_list
def expect_column_values_to_not_match_regex_list(self, column, regex_list, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None): """Expect the column entries to be strings that do not match any of a list of regular expressions. Matches can \ be anywhere in the string. expect_column_values_to_not_match_regex_list is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. regex_list (list): \ The list of regular expressions which the column entries should not match Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_match_regex_list """ raise NotImplementedError
python
def expect_column_values_to_not_match_regex_list(self, column, regex_list, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None): raise NotImplementedError
[ "def", "expect_column_values_to_not_match_regex_list", "(", "self", ",", "column", ",", "regex_list", ",", "mostly", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "Non...
Expect the column entries to be strings that do not match any of a list of regular expressions. Matches can \ be anywhere in the string. expect_column_values_to_not_match_regex_list is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. regex_list (list): \ The list of regular expressions which the column entries should not match Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_match_regex_list
[ "Expect", "the", "column", "entries", "to", "be", "strings", "that", "do", "not", "match", "any", "of", "a", "list", "of", "regular", "expressions", ".", "Matches", "can", "\\", "be", "anywhere", "in", "the", "string", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L1088-L1131
235,870
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_values_to_match_strftime_format
def expect_column_values_to_match_strftime_format(self, column, strftime_format, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect column entries to be strings representing a date or time with a given format. expect_column_values_to_match_strftime_format is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. strftime_format (str): \ A strftime format string to use for matching Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ raise NotImplementedError
python
def expect_column_values_to_match_strftime_format(self, column, strftime_format, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_values_to_match_strftime_format", "(", "self", ",", "column", ",", "strftime_format", ",", "mostly", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", ...
Expect column entries to be strings representing a date or time with a given format. expect_column_values_to_match_strftime_format is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. strftime_format (str): \ A strftime format string to use for matching Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Expect", "column", "entries", "to", "be", "strings", "representing", "a", "date", "or", "time", "with", "a", "given", "format", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L1135-L1177
235,871
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_values_to_be_dateutil_parseable
def expect_column_values_to_be_dateutil_parseable(self, column, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect column entries to be parseable using dateutil. expect_column_values_to_be_dateutil_parseable is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ raise NotImplementedError
python
def expect_column_values_to_be_dateutil_parseable(self, column, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_values_to_be_dateutil_parseable", "(", "self", ",", "column", ",", "mostly", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ")", ":", "r...
Expect column entries to be parseable using dateutil. expect_column_values_to_be_dateutil_parseable is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Expect", "column", "entries", "to", "be", "parseable", "using", "dateutil", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L1179-L1217
235,872
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_values_to_match_json_schema
def expect_column_values_to_match_json_schema(self, column, json_schema, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect column entries to be JSON objects matching a given JSON schema. expect_column_values_to_match_json_schema is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_be_json_parseable The JSON-schema docs at: http://json-schema.org/ """ raise NotImplementedError
python
def expect_column_values_to_match_json_schema(self, column, json_schema, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_values_to_match_json_schema", "(", "self", ",", "column", ",", "json_schema", ",", "mostly", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None"...
Expect column entries to be JSON objects matching a given JSON schema. expect_column_values_to_match_json_schema is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`. Args: column (str): \ The column name. Keyword Args: mostly (None or a float between 0 and 1): \ Return `"success": True` if at least mostly percent of values match the expectation. \ For more detail, see :ref:`mostly`. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. See Also: expect_column_values_to_be_json_parseable The JSON-schema docs at: http://json-schema.org/
[ "Expect", "column", "entries", "to", "be", "JSON", "objects", "matching", "a", "given", "JSON", "schema", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L1262-L1306
235,873
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_most_common_value_to_be_in_set
def expect_column_most_common_value_to_be_in_set(self, column, value_set, ties_okay=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect the most common value to be within the designated value set expect_column_most_common_value_to_be_in_set is a :func:`column_aggregate_expectation <great_expectations.data_asset.dataset.Dataset.column_aggregate_expectation>`. Args: column (str): \ The column name value_set (set-like): \ A list of potential values to match Keyword Args: ties_okay (boolean or None): \ If True, then the expectation will still succeed if values outside the designated set are as common (but not more common) than designated values Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Notes: These fields in the result object are customized for this expectation: :: { "observed_value": (list) The most common values in the column } `observed_value` contains a list of the most common values. Often, this will just be a single element. But if there's a tie for most common among multiple values, `observed_value` will contain a single copy of each most common value. """ raise NotImplementedError
python
def expect_column_most_common_value_to_be_in_set(self, column, value_set, ties_okay=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_most_common_value_to_be_in_set", "(", "self", ",", "column", ",", "value_set", ",", "ties_okay", "=", "None", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "N...
Expect the most common value to be within the designated value set expect_column_most_common_value_to_be_in_set is a :func:`column_aggregate_expectation <great_expectations.data_asset.dataset.Dataset.column_aggregate_expectation>`. Args: column (str): \ The column name value_set (set-like): \ A list of potential values to match Keyword Args: ties_okay (boolean or None): \ If True, then the expectation will still succeed if values outside the designated set are as common (but not more common) than designated values Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Notes: These fields in the result object are customized for this expectation: :: { "observed_value": (list) The most common values in the column } `observed_value` contains a list of the most common values. Often, this will just be a single element. But if there's a tie for most common among multiple values, `observed_value` will contain a single copy of each most common value.
[ "Expect", "the", "most", "common", "value", "to", "be", "within", "the", "designated", "value", "set" ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L1666-L1719
235,874
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_min_to_be_between
def expect_column_min_to_be_between(self, column, min_value=None, max_value=None, parse_strings_as_datetimes=None, output_strftime_format=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): """Expect the column to sum to be between an min and max value expect_column_min_to_be_between is a :func:`column_aggregate_expectation <great_expectations.data_asset.dataset.Dataset.column_aggregate_expectation>`. Args: column (str): \ The column name min_value (comparable type or None): \ The minimum number of unique values allowed. max_value (comparable type or None): \ The maximum number of unique values allowed. Keyword Args: parse_strings_as_datetimes (Boolean or None): \ If True, parse min_value, max_values, and all non-null column values to datetimes before making comparisons. output_strftime_format (str or None): \ A valid strfime format for datetime output. Only used if parse_strings_as_datetimes=True. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Notes: These fields in the result object are customized for this expectation: :: { "observed_value": (list) The actual column min } * min_value and max_value are both inclusive. * If min_value is None, then max_value is treated as an upper bound * If max_value is None, then min_value is treated as a lower bound """ raise NotImplementedError
python
def expect_column_min_to_be_between(self, column, min_value=None, max_value=None, parse_strings_as_datetimes=None, output_strftime_format=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_min_to_be_between", "(", "self", ",", "column", ",", "min_value", "=", "None", ",", "max_value", "=", "None", ",", "parse_strings_as_datetimes", "=", "None", ",", "output_strftime_format", "=", "None", ",", "result_format", "=", "None", ",", ...
Expect the column to sum to be between an min and max value expect_column_min_to_be_between is a :func:`column_aggregate_expectation <great_expectations.data_asset.dataset.Dataset.column_aggregate_expectation>`. Args: column (str): \ The column name min_value (comparable type or None): \ The minimum number of unique values allowed. max_value (comparable type or None): \ The maximum number of unique values allowed. Keyword Args: parse_strings_as_datetimes (Boolean or None): \ If True, parse min_value, max_values, and all non-null column values to datetimes before making comparisons. output_strftime_format (str or None): \ A valid strfime format for datetime output. Only used if parse_strings_as_datetimes=True. Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. Notes: These fields in the result object are customized for this expectation: :: { "observed_value": (list) The actual column min } * min_value and max_value are both inclusive. * If min_value is None, then max_value is treated as an upper bound * If max_value is None, then min_value is treated as a lower bound
[ "Expect", "the", "column", "to", "sum", "to", "be", "between", "an", "min", "and", "max", "value" ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L1775-L1835
235,875
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_pair_values_to_be_equal
def expect_column_pair_values_to_be_equal(self, column_A, column_B, ignore_row_if="both_values_are_missing", result_format=None, include_config=False, catch_exceptions=None, meta=None ): """ Expect the values in column A to be the same as column B. Args: column_A (str): The first column name column_B (str): The second column name Keyword Args: ignore_row_if (str): "both_values_are_missing", "either_value_is_missing", "neither" Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ raise NotImplementedError
python
def expect_column_pair_values_to_be_equal(self, column_A, column_B, ignore_row_if="both_values_are_missing", result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_pair_values_to_be_equal", "(", "self", ",", "column_A", ",", "column_B", ",", "ignore_row_if", "=", "\"both_values_are_missing\"", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", ...
Expect the values in column A to be the same as column B. Args: column_A (str): The first column name column_B (str): The second column name Keyword Args: ignore_row_if (str): "both_values_are_missing", "either_value_is_missing", "neither" Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Expect", "the", "values", "in", "column", "A", "to", "be", "the", "same", "as", "column", "B", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L2165-L2202
235,876
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_pair_values_A_to_be_greater_than_B
def expect_column_pair_values_A_to_be_greater_than_B(self, column_A, column_B, or_equal=None, parse_strings_as_datetimes=None, allow_cross_type_comparisons=None, ignore_row_if="both_values_are_missing", result_format=None, include_config=False, catch_exceptions=None, meta=None ): """ Expect values in column A to be greater than column B. Args: column_A (str): The first column name column_B (str): The second column name or_equal (boolean or None): If True, then values can be equal, not strictly greater Keyword Args: allow_cross_type_comparisons (boolean or None) : If True, allow comparisons between types (e.g. integer and\ string). Otherwise, attempting such comparisons will raise an exception. Keyword Args: ignore_row_if (str): "both_values_are_missing", "either_value_is_missing", "neither Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ raise NotImplementedError
python
def expect_column_pair_values_A_to_be_greater_than_B(self, column_A, column_B, or_equal=None, parse_strings_as_datetimes=None, allow_cross_type_comparisons=None, ignore_row_if="both_values_are_missing", result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_pair_values_A_to_be_greater_than_B", "(", "self", ",", "column_A", ",", "column_B", ",", "or_equal", "=", "None", ",", "parse_strings_as_datetimes", "=", "None", ",", "allow_cross_type_comparisons", "=", "None", ",", "ignore_row_if", "=", "\"both_v...
Expect values in column A to be greater than column B. Args: column_A (str): The first column name column_B (str): The second column name or_equal (boolean or None): If True, then values can be equal, not strictly greater Keyword Args: allow_cross_type_comparisons (boolean or None) : If True, allow comparisons between types (e.g. integer and\ string). Otherwise, attempting such comparisons will raise an exception. Keyword Args: ignore_row_if (str): "both_values_are_missing", "either_value_is_missing", "neither Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Expect", "values", "in", "column", "A", "to", "be", "greater", "than", "column", "B", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L2204-L2249
235,877
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_column_pair_values_to_be_in_set
def expect_column_pair_values_to_be_in_set(self, column_A, column_B, value_pairs_set, ignore_row_if="both_values_are_missing", result_format=None, include_config=False, catch_exceptions=None, meta=None ): """ Expect paired values from columns A and B to belong to a set of valid pairs. Args: column_A (str): The first column name column_B (str): The second column name value_pairs_set (list of tuples): All the valid pairs to be matched Keyword Args: ignore_row_if (str): "both_values_are_missing", "either_value_is_missing", "never" Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ raise NotImplementedError
python
def expect_column_pair_values_to_be_in_set(self, column_A, column_B, value_pairs_set, ignore_row_if="both_values_are_missing", result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_column_pair_values_to_be_in_set", "(", "self", ",", "column_A", ",", "column_B", ",", "value_pairs_set", ",", "ignore_row_if", "=", "\"both_values_are_missing\"", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptio...
Expect paired values from columns A and B to belong to a set of valid pairs. Args: column_A (str): The first column name column_B (str): The second column name value_pairs_set (list of tuples): All the valid pairs to be matched Keyword Args: ignore_row_if (str): "both_values_are_missing", "either_value_is_missing", "never" Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Expect", "paired", "values", "from", "columns", "A", "and", "B", "to", "belong", "to", "a", "set", "of", "valid", "pairs", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L2251-L2290
235,878
great-expectations/great_expectations
great_expectations/dataset/dataset.py
Dataset.expect_multicolumn_values_to_be_unique
def expect_multicolumn_values_to_be_unique(self, column_list, ignore_row_if="all_values_are_missing", result_format=None, include_config=False, catch_exceptions=None, meta=None ): """ Expect the values for each row to be unique across the columns listed. Args: column_list (tuple or list): The first column name Keyword Args: ignore_row_if (str): "all_values_are_missing", "any_value_is_missing", "never" Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`. """ raise NotImplementedError
python
def expect_multicolumn_values_to_be_unique(self, column_list, ignore_row_if="all_values_are_missing", result_format=None, include_config=False, catch_exceptions=None, meta=None ): raise NotImplementedError
[ "def", "expect_multicolumn_values_to_be_unique", "(", "self", ",", "column_list", ",", "ignore_row_if", "=", "\"all_values_are_missing\"", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", ...
Expect the values for each row to be unique across the columns listed. Args: column_list (tuple or list): The first column name Keyword Args: ignore_row_if (str): "all_values_are_missing", "any_value_is_missing", "never" Other Parameters: result_format (str or None): \ Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`. include_config (boolean): \ If True, then include the expectation config as part of the result object. \ For more detail, see :ref:`include_config`. catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see :ref:`catch_exceptions`. meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see :ref:`meta`. Returns: A JSON-serializable expectation result object. Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
[ "Expect", "the", "values", "for", "each", "row", "to", "be", "unique", "across", "the", "columns", "listed", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L2294-L2329
235,879
great-expectations/great_expectations
great_expectations/dataset/pandas_dataset.py
MetaPandasDataset.column_map_expectation
def column_map_expectation(cls, func): """Constructs an expectation using column-map semantics. The MetaPandasDataset implementation replaces the "column" parameter supplied by the user with a pandas Series object containing the actual column from the relevant pandas dataframe. This simplifies the implementing expectation logic while preserving the standard Dataset signature and expected behavior. See :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>` \ for full documentation of this function. """ if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, column, mostly=None, result_format=None, *args, **kwargs): if result_format is None: result_format = self.default_expectation_args["result_format"] result_format = parse_result_format(result_format) # FIXME temporary fix for missing/ignored value ignore_values = [None, np.nan] if func.__name__ in ['expect_column_values_to_not_be_null', 'expect_column_values_to_be_null']: ignore_values = [] result_format['partial_unexpected_count'] = 0 # Optimization to avoid meaningless computation for these expectations series = self[column] # FIXME rename to mapped_ignore_values? if len(ignore_values) == 0: boolean_mapped_null_values = np.array( [False for value in series]) else: boolean_mapped_null_values = np.array([True if (value in ignore_values) or (pd.isnull(value)) else False for value in series]) element_count = int(len(series)) # FIXME rename nonnull to non_ignored? nonnull_values = series[boolean_mapped_null_values == False] nonnull_count = int((boolean_mapped_null_values == False).sum()) boolean_mapped_success_values = func( self, nonnull_values, *args, **kwargs) success_count = np.count_nonzero(boolean_mapped_success_values) unexpected_list = list( nonnull_values[boolean_mapped_success_values == False]) unexpected_index_list = list( nonnull_values[boolean_mapped_success_values == False].index) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list, unexpected_index_list ) # FIXME Temp fix for result format if func.__name__ in ['expect_column_values_to_not_be_null', 'expect_column_values_to_be_null']: del return_obj['result']['unexpected_percent_nonmissing'] try: del return_obj['result']['partial_unexpected_counts'] except KeyError: pass return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
python
def column_map_expectation(cls, func): if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, column, mostly=None, result_format=None, *args, **kwargs): if result_format is None: result_format = self.default_expectation_args["result_format"] result_format = parse_result_format(result_format) # FIXME temporary fix for missing/ignored value ignore_values = [None, np.nan] if func.__name__ in ['expect_column_values_to_not_be_null', 'expect_column_values_to_be_null']: ignore_values = [] result_format['partial_unexpected_count'] = 0 # Optimization to avoid meaningless computation for these expectations series = self[column] # FIXME rename to mapped_ignore_values? if len(ignore_values) == 0: boolean_mapped_null_values = np.array( [False for value in series]) else: boolean_mapped_null_values = np.array([True if (value in ignore_values) or (pd.isnull(value)) else False for value in series]) element_count = int(len(series)) # FIXME rename nonnull to non_ignored? nonnull_values = series[boolean_mapped_null_values == False] nonnull_count = int((boolean_mapped_null_values == False).sum()) boolean_mapped_success_values = func( self, nonnull_values, *args, **kwargs) success_count = np.count_nonzero(boolean_mapped_success_values) unexpected_list = list( nonnull_values[boolean_mapped_success_values == False]) unexpected_index_list = list( nonnull_values[boolean_mapped_success_values == False].index) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list, unexpected_index_list ) # FIXME Temp fix for result format if func.__name__ in ['expect_column_values_to_not_be_null', 'expect_column_values_to_be_null']: del return_obj['result']['unexpected_percent_nonmissing'] try: del return_obj['result']['partial_unexpected_counts'] except KeyError: pass return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
[ "def", "column_map_expectation", "(", "cls", ",", "func", ")", ":", "if", "PY3", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "[", "0", "]", "[", "1", ":", "]", "else", ":", "argspec", "=", "inspect", ".", "getargspec", "(...
Constructs an expectation using column-map semantics. The MetaPandasDataset implementation replaces the "column" parameter supplied by the user with a pandas Series object containing the actual column from the relevant pandas dataframe. This simplifies the implementing expectation logic while preserving the standard Dataset signature and expected behavior. See :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>` \ for full documentation of this function.
[ "Constructs", "an", "expectation", "using", "column", "-", "map", "semantics", "." ]
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/pandas_dataset.py#L43-L122
235,880
great-expectations/great_expectations
great_expectations/dataset/pandas_dataset.py
MetaPandasDataset.column_pair_map_expectation
def column_pair_map_expectation(cls, func): """ The column_pair_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a pair of columns. """ if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, column_A, column_B, mostly=None, ignore_row_if="both_values_are_missing", result_format=None, *args, **kwargs): if result_format is None: result_format = self.default_expectation_args["result_format"] series_A = self[column_A] series_B = self[column_B] if ignore_row_if == "both_values_are_missing": boolean_mapped_null_values = series_A.isnull() & series_B.isnull() elif ignore_row_if == "either_value_is_missing": boolean_mapped_null_values = series_A.isnull() | series_B.isnull() elif ignore_row_if == "never": boolean_mapped_null_values = series_A.map(lambda x: False) else: raise ValueError( "Unknown value of ignore_row_if: %s", (ignore_row_if,)) assert len(series_A) == len( series_B), "Series A and B must be the same length" # This next bit only works if series_A and _B are the same length element_count = int(len(series_A)) nonnull_count = (boolean_mapped_null_values == False).sum() nonnull_values_A = series_A[boolean_mapped_null_values == False] nonnull_values_B = series_B[boolean_mapped_null_values == False] nonnull_values = [value_pair for value_pair in zip( list(nonnull_values_A), list(nonnull_values_B) )] boolean_mapped_success_values = func( self, nonnull_values_A, nonnull_values_B, *args, **kwargs) success_count = boolean_mapped_success_values.sum() unexpected_list = [value_pair for value_pair in zip( list(series_A[(boolean_mapped_success_values == False) & ( boolean_mapped_null_values == False)]), list(series_B[(boolean_mapped_success_values == False) & ( boolean_mapped_null_values == False)]) )] unexpected_index_list = list(series_A[(boolean_mapped_success_values == False) & ( boolean_mapped_null_values == False)].index) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list, unexpected_index_list ) return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
python
def column_pair_map_expectation(cls, func): if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, column_A, column_B, mostly=None, ignore_row_if="both_values_are_missing", result_format=None, *args, **kwargs): if result_format is None: result_format = self.default_expectation_args["result_format"] series_A = self[column_A] series_B = self[column_B] if ignore_row_if == "both_values_are_missing": boolean_mapped_null_values = series_A.isnull() & series_B.isnull() elif ignore_row_if == "either_value_is_missing": boolean_mapped_null_values = series_A.isnull() | series_B.isnull() elif ignore_row_if == "never": boolean_mapped_null_values = series_A.map(lambda x: False) else: raise ValueError( "Unknown value of ignore_row_if: %s", (ignore_row_if,)) assert len(series_A) == len( series_B), "Series A and B must be the same length" # This next bit only works if series_A and _B are the same length element_count = int(len(series_A)) nonnull_count = (boolean_mapped_null_values == False).sum() nonnull_values_A = series_A[boolean_mapped_null_values == False] nonnull_values_B = series_B[boolean_mapped_null_values == False] nonnull_values = [value_pair for value_pair in zip( list(nonnull_values_A), list(nonnull_values_B) )] boolean_mapped_success_values = func( self, nonnull_values_A, nonnull_values_B, *args, **kwargs) success_count = boolean_mapped_success_values.sum() unexpected_list = [value_pair for value_pair in zip( list(series_A[(boolean_mapped_success_values == False) & ( boolean_mapped_null_values == False)]), list(series_B[(boolean_mapped_success_values == False) & ( boolean_mapped_null_values == False)]) )] unexpected_index_list = list(series_A[(boolean_mapped_success_values == False) & ( boolean_mapped_null_values == False)].index) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list, unexpected_index_list ) return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
[ "def", "column_pair_map_expectation", "(", "cls", ",", "func", ")", ":", "if", "PY3", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "[", "0", "]", "[", "1", ":", "]", "else", ":", "argspec", "=", "inspect", ".", "getargspec",...
The column_pair_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a pair of columns.
[ "The", "column_pair_map_expectation", "decorator", "handles", "boilerplate", "issues", "surrounding", "the", "common", "pattern", "of", "evaluating", "truthiness", "of", "some", "condition", "on", "a", "per", "row", "basis", "across", "a", "pair", "of", "columns", ...
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/pandas_dataset.py#L125-L196
235,881
great-expectations/great_expectations
great_expectations/dataset/pandas_dataset.py
MetaPandasDataset.multicolumn_map_expectation
def multicolumn_map_expectation(cls, func): """ The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a set of columns. """ if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, column_list, mostly=None, ignore_row_if="all_values_are_missing", result_format=None, *args, **kwargs): if result_format is None: result_format = self.default_expectation_args["result_format"] test_df = self[column_list] if ignore_row_if == "all_values_are_missing": boolean_mapped_skip_values = test_df.isnull().all(axis=1) elif ignore_row_if == "any_value_is_missing": boolean_mapped_skip_values = test_df.isnull().any(axis=1) elif ignore_row_if == "never": boolean_mapped_skip_values = pd.Series([False] * len(test_df)) else: raise ValueError( "Unknown value of ignore_row_if: %s", (ignore_row_if,)) boolean_mapped_success_values = func( self, test_df[boolean_mapped_skip_values == False], *args, **kwargs) success_count = boolean_mapped_success_values.sum() nonnull_count = (~boolean_mapped_skip_values).sum() element_count = len(test_df) unexpected_list = test_df[(boolean_mapped_skip_values == False) & (boolean_mapped_success_values == False)] unexpected_index_list = list(unexpected_list.index) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list.to_dict(orient='records'), unexpected_index_list ) return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
python
def multicolumn_map_expectation(cls, func): if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, column_list, mostly=None, ignore_row_if="all_values_are_missing", result_format=None, *args, **kwargs): if result_format is None: result_format = self.default_expectation_args["result_format"] test_df = self[column_list] if ignore_row_if == "all_values_are_missing": boolean_mapped_skip_values = test_df.isnull().all(axis=1) elif ignore_row_if == "any_value_is_missing": boolean_mapped_skip_values = test_df.isnull().any(axis=1) elif ignore_row_if == "never": boolean_mapped_skip_values = pd.Series([False] * len(test_df)) else: raise ValueError( "Unknown value of ignore_row_if: %s", (ignore_row_if,)) boolean_mapped_success_values = func( self, test_df[boolean_mapped_skip_values == False], *args, **kwargs) success_count = boolean_mapped_success_values.sum() nonnull_count = (~boolean_mapped_skip_values).sum() element_count = len(test_df) unexpected_list = test_df[(boolean_mapped_skip_values == False) & (boolean_mapped_success_values == False)] unexpected_index_list = list(unexpected_list.index) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list.to_dict(orient='records'), unexpected_index_list ) return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
[ "def", "multicolumn_map_expectation", "(", "cls", ",", "func", ")", ":", "if", "PY3", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "[", "0", "]", "[", "1", ":", "]", "else", ":", "argspec", "=", "inspect", ".", "getargspec",...
The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a set of columns.
[ "The", "multicolumn_map_expectation", "decorator", "handles", "boilerplate", "issues", "surrounding", "the", "common", "pattern", "of", "evaluating", "truthiness", "of", "some", "condition", "on", "a", "per", "row", "basis", "across", "a", "set", "of", "columns", ...
08385c40529d4f14a1c46916788aecc47f33ee9d
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/pandas_dataset.py#L199-L252
235,882
splunk/splunk-sdk-python
splunklib/searchcommands/search_command.py
dispatch
def dispatch(command_class, argv=sys.argv, input_file=sys.stdin, output_file=sys.stdout, module_name=None): """ Instantiates and executes a search command class This function implements a `conditional script stanza <https://docs.python.org/2/library/__main__.html>`_ based on the value of :code:`module_name`:: if module_name is None or module_name == '__main__': # execute command Call this function at module scope with :code:`module_name=__name__`, if you would like your module to act as either a reusable module or a standalone program. Otherwise, if you wish this function to unconditionally instantiate and execute :code:`command_class`, pass :const:`None` as the value of :code:`module_name`. :param command_class: Search command class to instantiate and execute. :type command_class: type :param argv: List of arguments to the command. :type argv: list or tuple :param input_file: File from which the command will read data. :type input_file: :code:`file` :param output_file: File to which the command will write data. :type output_file: :code:`file` :param module_name: Name of the module calling :code:`dispatch` or :const:`None`. :type module_name: :code:`basestring` :returns: :const:`None` **Example** .. code-block:: python :linenos: #!/usr/bin/env python from splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option, validators @Configuration() class SomeStreamingCommand(StreamingCommand): ... def stream(records): ... dispatch(SomeStreamingCommand, module_name=__name__) Dispatches the :code:`SomeStreamingCommand`, if and only if :code:`__name__` is equal to :code:`'__main__'`. **Example** .. code-block:: python :linenos: from splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option, validators @Configuration() class SomeStreamingCommand(StreamingCommand): ... def stream(records): ... dispatch(SomeStreamingCommand) Unconditionally dispatches :code:`SomeStreamingCommand`. """ assert issubclass(command_class, SearchCommand) if module_name is None or module_name == '__main__': command_class().process(argv, input_file, output_file)
python
def dispatch(command_class, argv=sys.argv, input_file=sys.stdin, output_file=sys.stdout, module_name=None): assert issubclass(command_class, SearchCommand) if module_name is None or module_name == '__main__': command_class().process(argv, input_file, output_file)
[ "def", "dispatch", "(", "command_class", ",", "argv", "=", "sys", ".", "argv", ",", "input_file", "=", "sys", ".", "stdin", ",", "output_file", "=", "sys", ".", "stdout", ",", "module_name", "=", "None", ")", ":", "assert", "issubclass", "(", "command_cl...
Instantiates and executes a search command class This function implements a `conditional script stanza <https://docs.python.org/2/library/__main__.html>`_ based on the value of :code:`module_name`:: if module_name is None or module_name == '__main__': # execute command Call this function at module scope with :code:`module_name=__name__`, if you would like your module to act as either a reusable module or a standalone program. Otherwise, if you wish this function to unconditionally instantiate and execute :code:`command_class`, pass :const:`None` as the value of :code:`module_name`. :param command_class: Search command class to instantiate and execute. :type command_class: type :param argv: List of arguments to the command. :type argv: list or tuple :param input_file: File from which the command will read data. :type input_file: :code:`file` :param output_file: File to which the command will write data. :type output_file: :code:`file` :param module_name: Name of the module calling :code:`dispatch` or :const:`None`. :type module_name: :code:`basestring` :returns: :const:`None` **Example** .. code-block:: python :linenos: #!/usr/bin/env python from splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option, validators @Configuration() class SomeStreamingCommand(StreamingCommand): ... def stream(records): ... dispatch(SomeStreamingCommand, module_name=__name__) Dispatches the :code:`SomeStreamingCommand`, if and only if :code:`__name__` is equal to :code:`'__main__'`. **Example** .. code-block:: python :linenos: from splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option, validators @Configuration() class SomeStreamingCommand(StreamingCommand): ... def stream(records): ... dispatch(SomeStreamingCommand) Unconditionally dispatches :code:`SomeStreamingCommand`.
[ "Instantiates", "and", "executes", "a", "search", "command", "class" ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/searchcommands/search_command.py#L1056-L1116
235,883
splunk/splunk-sdk-python
splunklib/searchcommands/search_command.py
SearchCommand.search_results_info
def search_results_info(self): """ Returns the search results info for this command invocation. The search results info object is created from the search results info file associated with the command invocation. :return: Search results info:const:`None`, if the search results info file associated with the command invocation is inaccessible. :rtype: SearchResultsInfo or NoneType """ if self._search_results_info is not None: return self._search_results_info if self._protocol_version == 1: try: path = self._input_header['infoPath'] except KeyError: return None else: assert self._protocol_version == 2 try: dispatch_dir = self._metadata.searchinfo.dispatch_dir except AttributeError: return None path = os.path.join(dispatch_dir, 'info.csv') try: with io.open(path, 'r') as f: reader = csv.reader(f, dialect=CsvDialect) fields = next(reader) values = next(reader) except IOError as error: if error.errno == 2: self.logger.error('Search results info file {} does not exist.'.format(json_encode_string(path))) return raise def convert_field(field): return (field[1:] if field[0] == '_' else field).replace('.', '_') decode = MetadataDecoder().decode def convert_value(value): try: return decode(value) if len(value) > 0 else value except ValueError: return value info = ObjectView(dict(imap(lambda f_v: (convert_field(f_v[0]), convert_value(f_v[1])), izip(fields, values)))) try: count_map = info.countMap except AttributeError: pass else: count_map = count_map.split(';') n = len(count_map) info.countMap = dict(izip(islice(count_map, 0, n, 2), islice(count_map, 1, n, 2))) try: msg_type = info.msgType msg_text = info.msg except AttributeError: pass else: messages = ifilter(lambda t_m: t_m[0] or t_m[1], izip(msg_type.split('\n'), msg_text.split('\n'))) info.msg = [Message(message) for message in messages] del info.msgType try: info.vix_families = ElementTree.fromstring(info.vix_families) except AttributeError: pass self._search_results_info = info return info
python
def search_results_info(self): if self._search_results_info is not None: return self._search_results_info if self._protocol_version == 1: try: path = self._input_header['infoPath'] except KeyError: return None else: assert self._protocol_version == 2 try: dispatch_dir = self._metadata.searchinfo.dispatch_dir except AttributeError: return None path = os.path.join(dispatch_dir, 'info.csv') try: with io.open(path, 'r') as f: reader = csv.reader(f, dialect=CsvDialect) fields = next(reader) values = next(reader) except IOError as error: if error.errno == 2: self.logger.error('Search results info file {} does not exist.'.format(json_encode_string(path))) return raise def convert_field(field): return (field[1:] if field[0] == '_' else field).replace('.', '_') decode = MetadataDecoder().decode def convert_value(value): try: return decode(value) if len(value) > 0 else value except ValueError: return value info = ObjectView(dict(imap(lambda f_v: (convert_field(f_v[0]), convert_value(f_v[1])), izip(fields, values)))) try: count_map = info.countMap except AttributeError: pass else: count_map = count_map.split(';') n = len(count_map) info.countMap = dict(izip(islice(count_map, 0, n, 2), islice(count_map, 1, n, 2))) try: msg_type = info.msgType msg_text = info.msg except AttributeError: pass else: messages = ifilter(lambda t_m: t_m[0] or t_m[1], izip(msg_type.split('\n'), msg_text.split('\n'))) info.msg = [Message(message) for message in messages] del info.msgType try: info.vix_families = ElementTree.fromstring(info.vix_families) except AttributeError: pass self._search_results_info = info return info
[ "def", "search_results_info", "(", "self", ")", ":", "if", "self", ".", "_search_results_info", "is", "not", "None", ":", "return", "self", ".", "_search_results_info", "if", "self", ".", "_protocol_version", "==", "1", ":", "try", ":", "path", "=", "self", ...
Returns the search results info for this command invocation. The search results info object is created from the search results info file associated with the command invocation. :return: Search results info:const:`None`, if the search results info file associated with the command invocation is inaccessible. :rtype: SearchResultsInfo or NoneType
[ "Returns", "the", "search", "results", "info", "for", "this", "command", "invocation", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/searchcommands/search_command.py#L252-L330
235,884
splunk/splunk-sdk-python
splunklib/searchcommands/search_command.py
SearchCommand.process
def process(self, argv=sys.argv, ifile=sys.stdin, ofile=sys.stdout): """ Process data. :param argv: Command line arguments. :type argv: list or tuple :param ifile: Input data file. :type ifile: file :param ofile: Output data file. :type ofile: file :return: :const:`None` :rtype: NoneType """ if len(argv) > 1: self._process_protocol_v1(argv, ifile, ofile) else: self._process_protocol_v2(argv, ifile, ofile)
python
def process(self, argv=sys.argv, ifile=sys.stdin, ofile=sys.stdout): if len(argv) > 1: self._process_protocol_v1(argv, ifile, ofile) else: self._process_protocol_v2(argv, ifile, ofile)
[ "def", "process", "(", "self", ",", "argv", "=", "sys", ".", "argv", ",", "ifile", "=", "sys", ".", "stdin", ",", "ofile", "=", "sys", ".", "stdout", ")", ":", "if", "len", "(", "argv", ")", ">", "1", ":", "self", ".", "_process_protocol_v1", "("...
Process data. :param argv: Command line arguments. :type argv: list or tuple :param ifile: Input data file. :type ifile: file :param ofile: Output data file. :type ofile: file :return: :const:`None` :rtype: NoneType
[ "Process", "data", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/searchcommands/search_command.py#L415-L434
235,885
splunk/splunk-sdk-python
splunklib/searchcommands/search_command.py
SearchCommand._execute
def _execute(self, ifile, process): """ Default processing loop :param ifile: Input file object. :type ifile: file :param process: Bound method to call in processing loop. :type process: instancemethod :return: :const:`None`. :rtype: NoneType """ self._record_writer.write_records(process(self._records(ifile))) self.finish()
python
def _execute(self, ifile, process): self._record_writer.write_records(process(self._records(ifile))) self.finish()
[ "def", "_execute", "(", "self", ",", "ifile", ",", "process", ")", ":", "self", ".", "_record_writer", ".", "write_records", "(", "process", "(", "self", ".", "_records", "(", "ifile", ")", ")", ")", "self", ".", "finish", "(", ")" ]
Default processing loop :param ifile: Input file object. :type ifile: file :param process: Bound method to call in processing loop. :type process: instancemethod :return: :const:`None`. :rtype: NoneType
[ "Default", "processing", "loop" ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/searchcommands/search_command.py#L835-L849
235,886
splunk/splunk-sdk-python
utils/__init__.py
parse
def parse(argv, rules=None, config=None, **kwargs): """Parse the given arg vector with the default Splunk command rules.""" parser_ = parser(rules, **kwargs) if config is not None: parser_.loadrc(config) return parser_.parse(argv).result
python
def parse(argv, rules=None, config=None, **kwargs): parser_ = parser(rules, **kwargs) if config is not None: parser_.loadrc(config) return parser_.parse(argv).result
[ "def", "parse", "(", "argv", ",", "rules", "=", "None", ",", "config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "parser_", "=", "parser", "(", "rules", ",", "*", "*", "kwargs", ")", "if", "config", "is", "not", "None", ":", "parser_", ".",...
Parse the given arg vector with the default Splunk command rules.
[ "Parse", "the", "given", "arg", "vector", "with", "the", "default", "Splunk", "command", "rules", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/utils/__init__.py#L99-L103
235,887
splunk/splunk-sdk-python
utils/__init__.py
parser
def parser(rules=None, **kwargs): """Instantiate a parser with the default Splunk command rules.""" rules = RULES_SPLUNK if rules is None else dict(RULES_SPLUNK, **rules) return Parser(rules, **kwargs)
python
def parser(rules=None, **kwargs): rules = RULES_SPLUNK if rules is None else dict(RULES_SPLUNK, **rules) return Parser(rules, **kwargs)
[ "def", "parser", "(", "rules", "=", "None", ",", "*", "*", "kwargs", ")", ":", "rules", "=", "RULES_SPLUNK", "if", "rules", "is", "None", "else", "dict", "(", "RULES_SPLUNK", ",", "*", "*", "rules", ")", "return", "Parser", "(", "rules", ",", "*", ...
Instantiate a parser with the default Splunk command rules.
[ "Instantiate", "a", "parser", "with", "the", "default", "Splunk", "command", "rules", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/utils/__init__.py#L105-L108
235,888
splunk/splunk-sdk-python
utils/cmdopts.py
cmdline
def cmdline(argv, rules=None, config=None, **kwargs): """Simplified cmdopts interface that does not default any parsing rules and that does not allow compounding calls to the parser.""" parser = Parser(rules, **kwargs) if config is not None: parser.loadrc(config) return parser.parse(argv).result
python
def cmdline(argv, rules=None, config=None, **kwargs): parser = Parser(rules, **kwargs) if config is not None: parser.loadrc(config) return parser.parse(argv).result
[ "def", "cmdline", "(", "argv", ",", "rules", "=", "None", ",", "config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "parser", "=", "Parser", "(", "rules", ",", "*", "*", "kwargs", ")", "if", "config", "is", "not", "None", ":", "parser", ".",...
Simplified cmdopts interface that does not default any parsing rules and that does not allow compounding calls to the parser.
[ "Simplified", "cmdopts", "interface", "that", "does", "not", "default", "any", "parsing", "rules", "and", "that", "does", "not", "allow", "compounding", "calls", "to", "the", "parser", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/utils/cmdopts.py#L113-L118
235,889
splunk/splunk-sdk-python
utils/cmdopts.py
Parser.init
def init(self, rules): """Initialize the parser with the given command rules.""" # Initialize the option parser for dest in rules.keys(): rule = rules[dest] # Assign defaults ourselves here, instead of in the option parser # itself in order to allow for multiple calls to parse (dont want # subsequent calls to override previous values with default vals). if 'default' in rule: self.result['kwargs'][dest] = rule['default'] flags = rule['flags'] kwargs = { 'action': rule.get('action', "store") } # NOTE: Don't provision the parser with defaults here, per above. for key in ['callback', 'help', 'metavar', 'type']: if key in rule: kwargs[key] = rule[key] self.add_option(*flags, dest=dest, **kwargs) # Remember the dest vars that we see, so that we can merge results self.dests.add(dest)
python
def init(self, rules): # Initialize the option parser for dest in rules.keys(): rule = rules[dest] # Assign defaults ourselves here, instead of in the option parser # itself in order to allow for multiple calls to parse (dont want # subsequent calls to override previous values with default vals). if 'default' in rule: self.result['kwargs'][dest] = rule['default'] flags = rule['flags'] kwargs = { 'action': rule.get('action', "store") } # NOTE: Don't provision the parser with defaults here, per above. for key in ['callback', 'help', 'metavar', 'type']: if key in rule: kwargs[key] = rule[key] self.add_option(*flags, dest=dest, **kwargs) # Remember the dest vars that we see, so that we can merge results self.dests.add(dest)
[ "def", "init", "(", "self", ",", "rules", ")", ":", "# Initialize the option parser", "for", "dest", "in", "rules", ".", "keys", "(", ")", ":", "rule", "=", "rules", "[", "dest", "]", "# Assign defaults ourselves here, instead of in the option parser", "# itself in ...
Initialize the parser with the given command rules.
[ "Initialize", "the", "parser", "with", "the", "given", "command", "rules", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/utils/cmdopts.py#L49-L69
235,890
splunk/splunk-sdk-python
utils/cmdopts.py
Parser.loadif
def loadif(self, filepath): """Load the given filepath if it exists, otherwise ignore.""" if path.isfile(filepath): self.load(filepath) return self
python
def loadif(self, filepath): if path.isfile(filepath): self.load(filepath) return self
[ "def", "loadif", "(", "self", ",", "filepath", ")", ":", "if", "path", ".", "isfile", "(", "filepath", ")", ":", "self", ".", "load", "(", "filepath", ")", "return", "self" ]
Load the given filepath if it exists, otherwise ignore.
[ "Load", "the", "given", "filepath", "if", "it", "exists", "otherwise", "ignore", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/utils/cmdopts.py#L88-L91
235,891
splunk/splunk-sdk-python
utils/cmdopts.py
Parser.parse
def parse(self, argv): """Parse the given argument vector.""" kwargs, args = self.parse_args(argv) self.result['args'] += args # Annoying that parse_args doesn't just return a dict for dest in self.dests: value = getattr(kwargs, dest) if value is not None: self.result['kwargs'][dest] = value return self
python
def parse(self, argv): kwargs, args = self.parse_args(argv) self.result['args'] += args # Annoying that parse_args doesn't just return a dict for dest in self.dests: value = getattr(kwargs, dest) if value is not None: self.result['kwargs'][dest] = value return self
[ "def", "parse", "(", "self", ",", "argv", ")", ":", "kwargs", ",", "args", "=", "self", ".", "parse_args", "(", "argv", ")", "self", ".", "result", "[", "'args'", "]", "+=", "args", "# Annoying that parse_args doesn't just return a dict", "for", "dest", "in"...
Parse the given argument vector.
[ "Parse", "the", "given", "argument", "vector", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/utils/cmdopts.py#L98-L107
235,892
splunk/splunk-sdk-python
examples/genevents.py
feed_index
def feed_index(service, opts): """Feed the named index in a specific manner.""" indexname = opts.args[0] itype = opts.kwargs['ingest'] # get index handle try: index = service.indexes[indexname] except KeyError: print("Index %s not found" % indexname) return if itype in ["stream", "submit"]: stream = index.attach() else: # create a tcp input if one doesn't exist input_host = opts.kwargs.get("inputhost", SPLUNK_HOST) input_port = int(opts.kwargs.get("inputport", SPLUNK_PORT)) input_name = "tcp:%s" % (input_port) if input_name not in service.inputs.list(): service.inputs.create("tcp", input_port, index=indexname) # connect to socket ingest = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ingest.connect((input_host, input_port)) count = 0 lastevent = "" try: for i in range(0, 10): for j in range(0, 5000): lastevent = "%s: event bunch %d, number %d\n" % \ (datetime.datetime.now().isoformat(), i, j) if itype == "stream": stream.write(lastevent + "\n") elif itype == "submit": index.submit(lastevent + "\n") else: ingest.send(lastevent + "\n") count = count + 1 print("submitted %d events, sleeping 1 second" % count) time.sleep(1) except KeyboardInterrupt: print("^C detected, last event written:") print(lastevent)
python
def feed_index(service, opts): indexname = opts.args[0] itype = opts.kwargs['ingest'] # get index handle try: index = service.indexes[indexname] except KeyError: print("Index %s not found" % indexname) return if itype in ["stream", "submit"]: stream = index.attach() else: # create a tcp input if one doesn't exist input_host = opts.kwargs.get("inputhost", SPLUNK_HOST) input_port = int(opts.kwargs.get("inputport", SPLUNK_PORT)) input_name = "tcp:%s" % (input_port) if input_name not in service.inputs.list(): service.inputs.create("tcp", input_port, index=indexname) # connect to socket ingest = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ingest.connect((input_host, input_port)) count = 0 lastevent = "" try: for i in range(0, 10): for j in range(0, 5000): lastevent = "%s: event bunch %d, number %d\n" % \ (datetime.datetime.now().isoformat(), i, j) if itype == "stream": stream.write(lastevent + "\n") elif itype == "submit": index.submit(lastevent + "\n") else: ingest.send(lastevent + "\n") count = count + 1 print("submitted %d events, sleeping 1 second" % count) time.sleep(1) except KeyboardInterrupt: print("^C detected, last event written:") print(lastevent)
[ "def", "feed_index", "(", "service", ",", "opts", ")", ":", "indexname", "=", "opts", ".", "args", "[", "0", "]", "itype", "=", "opts", ".", "kwargs", "[", "'ingest'", "]", "# get index handle", "try", ":", "index", "=", "service", ".", "indexes", "[",...
Feed the named index in a specific manner.
[ "Feed", "the", "named", "index", "in", "a", "specific", "manner", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/genevents.py#L58-L106
235,893
splunk/splunk-sdk-python
splunklib/modularinput/utils.py
xml_compare
def xml_compare(expected, found): """Checks equality of two ``ElementTree`` objects. :param expected: An ``ElementTree`` object. :param found: An ``ElementTree`` object. :return: ``Boolean``, whether the two objects are equal. """ # if comparing the same ET object if expected == found: return True # compare element attributes, ignoring order if set(expected.items()) != set(found.items()): return False # check for equal number of children expected_children = list(expected) found_children = list(found) if len(expected_children) != len(found_children): return False # compare children if not all([xml_compare(a, b) for a, b in zip(expected_children, found_children)]): return False # compare elements, if there is no text node, return True if (expected.text is None or expected.text.strip() == "") \ and (found.text is None or found.text.strip() == ""): return True else: return expected.tag == found.tag and expected.text == found.text \ and expected.attrib == found.attrib
python
def xml_compare(expected, found): # if comparing the same ET object if expected == found: return True # compare element attributes, ignoring order if set(expected.items()) != set(found.items()): return False # check for equal number of children expected_children = list(expected) found_children = list(found) if len(expected_children) != len(found_children): return False # compare children if not all([xml_compare(a, b) for a, b in zip(expected_children, found_children)]): return False # compare elements, if there is no text node, return True if (expected.text is None or expected.text.strip() == "") \ and (found.text is None or found.text.strip() == ""): return True else: return expected.tag == found.tag and expected.text == found.text \ and expected.attrib == found.attrib
[ "def", "xml_compare", "(", "expected", ",", "found", ")", ":", "# if comparing the same ET object", "if", "expected", "==", "found", ":", "return", "True", "# compare element attributes, ignoring order", "if", "set", "(", "expected", ".", "items", "(", ")", ")", "...
Checks equality of two ``ElementTree`` objects. :param expected: An ``ElementTree`` object. :param found: An ``ElementTree`` object. :return: ``Boolean``, whether the two objects are equal.
[ "Checks", "equality", "of", "two", "ElementTree", "objects", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/modularinput/utils.py#L19-L51
235,894
splunk/splunk-sdk-python
examples/job.py
cmdline
def cmdline(argv, flags): """A cmdopts wrapper that takes a list of flags and builds the corresponding cmdopts rules to match those flags.""" rules = dict([(flag, {'flags': ["--%s" % flag]}) for flag in flags]) return parse(argv, rules)
python
def cmdline(argv, flags): rules = dict([(flag, {'flags': ["--%s" % flag]}) for flag in flags]) return parse(argv, rules)
[ "def", "cmdline", "(", "argv", ",", "flags", ")", ":", "rules", "=", "dict", "(", "[", "(", "flag", ",", "{", "'flags'", ":", "[", "\"--%s\"", "%", "flag", "]", "}", ")", "for", "flag", "in", "flags", "]", ")", "return", "parse", "(", "argv", "...
A cmdopts wrapper that takes a list of flags and builds the corresponding cmdopts rules to match those flags.
[ "A", "cmdopts", "wrapper", "that", "takes", "a", "list", "of", "flags", "and", "builds", "the", "corresponding", "cmdopts", "rules", "to", "match", "those", "flags", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L107-L111
235,895
splunk/splunk-sdk-python
examples/job.py
output
def output(stream): """Write the contents of the given stream to stdout.""" while True: content = stream.read(1024) if len(content) == 0: break sys.stdout.write(content)
python
def output(stream): while True: content = stream.read(1024) if len(content) == 0: break sys.stdout.write(content)
[ "def", "output", "(", "stream", ")", ":", "while", "True", ":", "content", "=", "stream", ".", "read", "(", "1024", ")", "if", "len", "(", "content", ")", "==", "0", ":", "break", "sys", ".", "stdout", ".", "write", "(", "content", ")" ]
Write the contents of the given stream to stdout.
[ "Write", "the", "contents", "of", "the", "given", "stream", "to", "stdout", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L113-L118
235,896
splunk/splunk-sdk-python
examples/job.py
Program.create
def create(self, argv): """Create a search job.""" opts = cmdline(argv, FLAGS_CREATE) if len(opts.args) != 1: error("Command requires a search expression", 2) query = opts.args[0] job = self.service.jobs.create(opts.args[0], **opts.kwargs) print(job.sid)
python
def create(self, argv): opts = cmdline(argv, FLAGS_CREATE) if len(opts.args) != 1: error("Command requires a search expression", 2) query = opts.args[0] job = self.service.jobs.create(opts.args[0], **opts.kwargs) print(job.sid)
[ "def", "create", "(", "self", ",", "argv", ")", ":", "opts", "=", "cmdline", "(", "argv", ",", "FLAGS_CREATE", ")", "if", "len", "(", "opts", ".", "args", ")", "!=", "1", ":", "error", "(", "\"Command requires a search expression\"", ",", "2", ")", "qu...
Create a search job.
[ "Create", "a", "search", "job", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L127-L134
235,897
splunk/splunk-sdk-python
examples/job.py
Program.events
def events(self, argv): """Retrieve events for the specified search jobs.""" opts = cmdline(argv, FLAGS_EVENTS) self.foreach(opts.args, lambda job: output(job.events(**opts.kwargs)))
python
def events(self, argv): opts = cmdline(argv, FLAGS_EVENTS) self.foreach(opts.args, lambda job: output(job.events(**opts.kwargs)))
[ "def", "events", "(", "self", ",", "argv", ")", ":", "opts", "=", "cmdline", "(", "argv", ",", "FLAGS_EVENTS", ")", "self", ".", "foreach", "(", "opts", ".", "args", ",", "lambda", "job", ":", "output", "(", "job", ".", "events", "(", "*", "*", "...
Retrieve events for the specified search jobs.
[ "Retrieve", "events", "for", "the", "specified", "search", "jobs", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L136-L140
235,898
splunk/splunk-sdk-python
examples/job.py
Program.foreach
def foreach(self, argv, func): """Apply the function to each job specified in the argument vector.""" if len(argv) == 0: error("Command requires a search specifier.", 2) for item in argv: job = self.lookup(item) if job is None: error("Search job '%s' does not exist" % item, 2) func(job)
python
def foreach(self, argv, func): if len(argv) == 0: error("Command requires a search specifier.", 2) for item in argv: job = self.lookup(item) if job is None: error("Search job '%s' does not exist" % item, 2) func(job)
[ "def", "foreach", "(", "self", ",", "argv", ",", "func", ")", ":", "if", "len", "(", "argv", ")", "==", "0", ":", "error", "(", "\"Command requires a search specifier.\"", ",", "2", ")", "for", "item", "in", "argv", ":", "job", "=", "self", ".", "loo...
Apply the function to each job specified in the argument vector.
[ "Apply", "the", "function", "to", "each", "job", "specified", "in", "the", "argument", "vector", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L146-L154
235,899
splunk/splunk-sdk-python
examples/job.py
Program.list
def list(self, argv): """List all current search jobs if no jobs specified, otherwise list the properties of the specified jobs.""" def read(job): for key in sorted(job.content.keys()): # Ignore some fields that make the output hard to read and # that are available via other commands. if key in ["performance"]: continue print("%s: %s" % (key, job.content[key])) if len(argv) == 0: index = 0 for job in self.service.jobs: print("@%d : %s" % (index, job.sid)) index += 1 return self.foreach(argv, read)
python
def list(self, argv): def read(job): for key in sorted(job.content.keys()): # Ignore some fields that make the output hard to read and # that are available via other commands. if key in ["performance"]: continue print("%s: %s" % (key, job.content[key])) if len(argv) == 0: index = 0 for job in self.service.jobs: print("@%d : %s" % (index, job.sid)) index += 1 return self.foreach(argv, read)
[ "def", "list", "(", "self", ",", "argv", ")", ":", "def", "read", "(", "job", ")", ":", "for", "key", "in", "sorted", "(", "job", ".", "content", ".", "keys", "(", ")", ")", ":", "# Ignore some fields that make the output hard to read and", "# that are avail...
List all current search jobs if no jobs specified, otherwise list the properties of the specified jobs.
[ "List", "all", "current", "search", "jobs", "if", "no", "jobs", "specified", "otherwise", "list", "the", "properties", "of", "the", "specified", "jobs", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L156-L174