partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
random_bytes
Returns n random bytes generated with given seed --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/octet-stream responses: 200: description: Bytes.
httpbin/core.py
def random_bytes(n): """Returns n random bytes generated with given seed --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/octet-stream responses: 200: description: Bytes. """ n = min(n, 100 * 1024) ...
def random_bytes(n): """Returns n random bytes generated with given seed --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/octet-stream responses: 200: description: Bytes. """ n = min(n, 100 * 1024) ...
[ "Returns", "n", "random", "bytes", "generated", "with", "given", "seed", "---", "tags", ":", "-", "Dynamic", "data", "parameters", ":", "-", "in", ":", "path", "name", ":", "n", "type", ":", "int", "produces", ":", "-", "application", "/", "octet", "-"...
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L1423-L1450
[ "def", "random_bytes", "(", "n", ")", ":", "n", "=", "min", "(", "n", ",", "100", "*", "1024", ")", "# set 100KB limit", "params", "=", "CaseInsensitiveDict", "(", "request", ".", "args", ".", "items", "(", ")", ")", "if", "\"seed\"", "in", "params", ...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
stream_random_bytes
Streams n random bytes generated with given seed, at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/octet-stream responses: 200: description: Bytes.
httpbin/core.py
def stream_random_bytes(n): """Streams n random bytes generated with given seed, at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/octet-stream responses: 200: description: Byt...
def stream_random_bytes(n): """Streams n random bytes generated with given seed, at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/octet-stream responses: 200: description: Byt...
[ "Streams", "n", "random", "bytes", "generated", "with", "given", "seed", "at", "given", "chunk", "size", "per", "packet", ".", "---", "tags", ":", "-", "Dynamic", "data", "parameters", ":", "-", "in", ":", "path", "name", ":", "n", "type", ":", "int", ...
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L1454-L1494
[ "def", "stream_random_bytes", "(", "n", ")", ":", "n", "=", "min", "(", "n", ",", "100", "*", "1024", ")", "# set 100KB limit", "params", "=", "CaseInsensitiveDict", "(", "request", ".", "args", ".", "items", "(", ")", ")", "if", "\"seed\"", "in", "par...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
range_request
Streams n random bytes generated with given seed, at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: numbytes type: int produces: - application/octet-stream responses: 200: description: Bytes.
httpbin/core.py
def range_request(numbytes): """Streams n random bytes generated with given seed, at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: numbytes type: int produces: - application/octet-stream responses: 200: descript...
def range_request(numbytes): """Streams n random bytes generated with given seed, at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: numbytes type: int produces: - application/octet-stream responses: 200: descript...
[ "Streams", "n", "random", "bytes", "generated", "with", "given", "seed", "at", "given", "chunk", "size", "per", "packet", ".", "---", "tags", ":", "-", "Dynamic", "data", "parameters", ":", "-", "in", ":", "path", "name", ":", "numbytes", "type", ":", ...
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L1498-L1584
[ "def", "range_request", "(", "numbytes", ")", ":", "if", "numbytes", "<=", "0", "or", "numbytes", ">", "(", "100", "*", "1024", ")", ":", "response", "=", "Response", "(", "headers", "=", "{", "\"ETag\"", ":", "\"range%d\"", "%", "numbytes", ",", "\"Ac...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
link_page
Generate a page containing n links to other pages which do the same. --- tags: - Dynamic data parameters: - in: path name: n type: int - in: path name: offset type: int produces: - text/html responses: 200: description: HTML links...
httpbin/core.py
def link_page(n, offset): """Generate a page containing n links to other pages which do the same. --- tags: - Dynamic data parameters: - in: path name: n type: int - in: path name: offset type: int produces: - text/html responses: 200...
def link_page(n, offset): """Generate a page containing n links to other pages which do the same. --- tags: - Dynamic data parameters: - in: path name: n type: int - in: path name: offset type: int produces: - text/html responses: 200...
[ "Generate", "a", "page", "containing", "n", "links", "to", "other", "pages", "which", "do", "the", "same", ".", "---", "tags", ":", "-", "Dynamic", "data", "parameters", ":", "-", "in", ":", "path", "name", ":", "n", "type", ":", "int", "-", "in", ...
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L1588-L1618
[ "def", "link_page", "(", "n", ",", "offset", ")", ":", "n", "=", "min", "(", "max", "(", "1", ",", "n", ")", ",", "200", ")", "# limit to between 1 and 200 links", "link", "=", "\"<a href='{0}'>{1}</a> \"", "html", "=", "[", "\"<html><head><title>Links</title>...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
image
Returns a simple image of the type suggest by the Accept header. --- tags: - Images produces: - image/webp - image/svg+xml - image/jpeg - image/png - image/* responses: 200: description: An image.
httpbin/core.py
def image(): """Returns a simple image of the type suggest by the Accept header. --- tags: - Images produces: - image/webp - image/svg+xml - image/jpeg - image/png - image/* responses: 200: description: An image. """ headers = get_headers() ...
def image(): """Returns a simple image of the type suggest by the Accept header. --- tags: - Images produces: - image/webp - image/svg+xml - image/jpeg - image/png - image/* responses: 200: description: An image. """ headers = get_headers() ...
[ "Returns", "a", "simple", "image", "of", "the", "type", "suggest", "by", "the", "Accept", "header", ".", "---", "tags", ":", "-", "Images", "produces", ":", "-", "image", "/", "webp", "-", "image", "/", "svg", "+", "xml", "-", "image", "/", "jpeg", ...
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L1628-L1659
[ "def", "image", "(", ")", ":", "headers", "=", "get_headers", "(", ")", "if", "\"accept\"", "not", "in", "headers", ":", "return", "image_png", "(", ")", "# Default media type to png", "accept", "=", "headers", "[", "\"accept\"", "]", ".", "lower", "(", ")...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
weighted_choice
Returns a value from choices chosen by weighted random selection choices should be a list of (value, weight) tuples. eg. weighted_choice([('val1', 5), ('val2', 0.3), ('val3', 1)])
httpbin/utils.py
def weighted_choice(choices): """Returns a value from choices chosen by weighted random selection choices should be a list of (value, weight) tuples. eg. weighted_choice([('val1', 5), ('val2', 0.3), ('val3', 1)]) """ values, weights = zip(*choices) total = 0 cum_weights = [] for w in ...
def weighted_choice(choices): """Returns a value from choices chosen by weighted random selection choices should be a list of (value, weight) tuples. eg. weighted_choice([('val1', 5), ('val2', 0.3), ('val3', 1)]) """ values, weights = zip(*choices) total = 0 cum_weights = [] for w in ...
[ "Returns", "a", "value", "from", "choices", "chosen", "by", "weighted", "random", "selection" ]
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/utils.py#L14-L30
[ "def", "weighted_choice", "(", "choices", ")", ":", "values", ",", "weights", "=", "zip", "(", "*", "choices", ")", "total", "=", "0", "cum_weights", "=", "[", "]", "for", "w", "in", "weights", ":", "total", "+=", "w", "cum_weights", ".", "append", "...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
x_runtime
X-Runtime Flask Response Decorator.
httpbin/filters.py
def x_runtime(f, *args, **kwargs): """X-Runtime Flask Response Decorator.""" _t0 = now() r = f(*args, **kwargs) _t1 = now() r.headers['X-Runtime'] = '{0}s'.format(Decimal(str(_t1 - _t0))) return r
def x_runtime(f, *args, **kwargs): """X-Runtime Flask Response Decorator.""" _t0 = now() r = f(*args, **kwargs) _t1 = now() r.headers['X-Runtime'] = '{0}s'.format(Decimal(str(_t1 - _t0))) return r
[ "X", "-", "Runtime", "Flask", "Response", "Decorator", "." ]
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/filters.py#L27-L35
[ "def", "x_runtime", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_t0", "=", "now", "(", ")", "r", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "_t1", "=", "now", "(", ")", "r", ".", "headers", "[", "'X-Runtim...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
gzip
GZip Flask Response Decorator.
httpbin/filters.py
def gzip(f, *args, **kwargs): """GZip Flask Response Decorator.""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data gzip_buffer = BytesIO() gzip_file = gzip2.GzipFile( mode='wb', compresslevel=4, fileobj=...
def gzip(f, *args, **kwargs): """GZip Flask Response Decorator.""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data gzip_buffer = BytesIO() gzip_file = gzip2.GzipFile( mode='wb', compresslevel=4, fileobj=...
[ "GZip", "Flask", "Response", "Decorator", "." ]
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/filters.py#L39-L67
[ "def", "gzip", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "data", ",", "Response", ")", ":", "content", "=", "data", ".", "data", "...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
deflate
Deflate Flask Response Decorator.
httpbin/filters.py
def deflate(f, *args, **kwargs): """Deflate Flask Response Decorator.""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data deflater = zlib.compressobj() deflated_data = deflater.compress(content) deflated_data += deflater.flu...
def deflate(f, *args, **kwargs): """Deflate Flask Response Decorator.""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data deflater = zlib.compressobj() deflated_data = deflater.compress(content) deflated_data += deflater.flu...
[ "Deflate", "Flask", "Response", "Decorator", "." ]
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/filters.py#L71-L92
[ "def", "deflate", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "data", ",", "Response", ")", ":", "content", "=", "data", ".", "data", ...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
brotli
Brotli Flask Response Decorator
httpbin/filters.py
def brotli(f, *args, **kwargs): """Brotli Flask Response Decorator""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data deflated_data = _brotli.compress(content) if isinstance(data, Response): data.data = deflated_data ...
def brotli(f, *args, **kwargs): """Brotli Flask Response Decorator""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data deflated_data = _brotli.compress(content) if isinstance(data, Response): data.data = deflated_data ...
[ "Brotli", "Flask", "Response", "Decorator" ]
postmanlabs/httpbin
python
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/filters.py#L96-L115
[ "def", "brotli", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "data", ",", "Response", ")", ":", "content", "=", "data", ".", "data", ...
f8ec666b4d1b654e4ff6aedd356f510dcac09f83
train
get_version
Parses the version out of libjsonnet.h
setup.py
def get_version(): """ Parses the version out of libjsonnet.h """ with open(os.path.join(DIR, 'include/libjsonnet.h')) as f: for line in f: if '#define' in line and 'LIB_JSONNET_VERSION' in line: v_code = line.partition('LIB_JSONNET_VERSION')[2].strip('\n "') ...
def get_version(): """ Parses the version out of libjsonnet.h """ with open(os.path.join(DIR, 'include/libjsonnet.h')) as f: for line in f: if '#define' in line and 'LIB_JSONNET_VERSION' in line: v_code = line.partition('LIB_JSONNET_VERSION')[2].strip('\n "') ...
[ "Parses", "the", "version", "out", "of", "libjsonnet", ".", "h" ]
google/jsonnet
python
https://github.com/google/jsonnet/blob/c323f5ce5b8aa663585d23dc0fb94d4b166c6f16/setup.py#L37-L47
[ "def", "get_version", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "DIR", ",", "'include/libjsonnet.h'", ")", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "'#define'", "in", "line", "and", "'LIB_JSONNET_VERSION'...
c323f5ce5b8aa663585d23dc0fb94d4b166c6f16
train
handle_fractal
Get fractal coordinates from query string, call mandelbrot to generate image. Returns: The image, wrapped in an HTML response.
case_studies/micro_fractal/tilegen/mandelbrot_service.py
def handle_fractal(): """Get fractal coordinates from query string, call mandelbrot to generate image. Returns: The image, wrapped in an HTML response. """ if check_etag(): return flask.make_response(), 304 level = int(flask.request.args.get("l", "0")) x = float(int(flask.requ...
def handle_fractal(): """Get fractal coordinates from query string, call mandelbrot to generate image. Returns: The image, wrapped in an HTML response. """ if check_etag(): return flask.make_response(), 304 level = int(flask.request.args.get("l", "0")) x = float(int(flask.requ...
[ "Get", "fractal", "coordinates", "from", "query", "string", "call", "mandelbrot", "to", "generate", "image", "." ]
google/jsonnet
python
https://github.com/google/jsonnet/blob/c323f5ce5b8aa663585d23dc0fb94d4b166c6f16/case_studies/micro_fractal/tilegen/mandelbrot_service.py#L66-L104
[ "def", "handle_fractal", "(", ")", ":", "if", "check_etag", "(", ")", ":", "return", "flask", ".", "make_response", "(", ")", ",", "304", "level", "=", "int", "(", "flask", ".", "request", ".", "args", ".", "get", "(", "\"l\"", ",", "\"0\"", ")", "...
c323f5ce5b8aa663585d23dc0fb94d4b166c6f16
train
preprocess
Return a copy of the config with ${-} handled.
case_studies/micromanage/micromanage.py
def preprocess(config): """Return a copy of the config with ${-} handled.""" def aux(ctx, service_name, service): compiler, _ = get_compiler(config, service) r2 = compiler.preprocess(ctx, service_name, service) ctx = ctx + [service_name] for child_name, child in compiler.childre...
def preprocess(config): """Return a copy of the config with ${-} handled.""" def aux(ctx, service_name, service): compiler, _ = get_compiler(config, service) r2 = compiler.preprocess(ctx, service_name, service) ctx = ctx + [service_name] for child_name, child in compiler.childre...
[ "Return", "a", "copy", "of", "the", "config", "with", "$", "{", "-", "}", "handled", "." ]
google/jsonnet
python
https://github.com/google/jsonnet/blob/c323f5ce5b8aa663585d23dc0fb94d4b166c6f16/case_studies/micromanage/micromanage.py#L152-L170
[ "def", "preprocess", "(", "config", ")", ":", "def", "aux", "(", "ctx", ",", "service_name", ",", "service", ")", ":", "compiler", ",", "_", "=", "get_compiler", "(", "config", ",", "service", ")", "r2", "=", "compiler", ".", "preprocess", "(", "ctx", ...
c323f5ce5b8aa663585d23dc0fb94d4b166c6f16
train
get_build_artefacts
Create all required build artefacts, modify config to refer to them.
case_studies/micromanage/micromanage.py
def get_build_artefacts(config): """Create all required build artefacts, modify config to refer to them.""" def aux(ctx, service_name, service): compiler, environment = get_compiler(config, service) new_service, service_barts = compiler.getBuildArtefacts(environment, ctx, service) ctx =...
def get_build_artefacts(config): """Create all required build artefacts, modify config to refer to them.""" def aux(ctx, service_name, service): compiler, environment = get_compiler(config, service) new_service, service_barts = compiler.getBuildArtefacts(environment, ctx, service) ctx =...
[ "Create", "all", "required", "build", "artefacts", "modify", "config", "to", "refer", "to", "them", "." ]
google/jsonnet
python
https://github.com/google/jsonnet/blob/c323f5ce5b8aa663585d23dc0fb94d4b166c6f16/case_studies/micromanage/micromanage.py#L173-L194
[ "def", "get_build_artefacts", "(", "config", ")", ":", "def", "aux", "(", "ctx", ",", "service_name", ",", "service", ")", ":", "compiler", ",", "environment", "=", "get_compiler", "(", "config", ",", "service", ")", "new_service", ",", "service_barts", "=",...
c323f5ce5b8aa663585d23dc0fb94d4b166c6f16
train
KeyedVectors.load_word2vec_format
Load the input-hidden weight matrix from the original C word2vec-tool format. Note that the information stored in the file is incomplete (the binary tree is missing), so while you can query for word similarity etc., you cannot continue training with a model loaded this way. `binary` is a...
synonyms/word2vec.py
def load_word2vec_format( cls, fname, fvocab=None, binary=False, encoding='utf8', unicode_errors='strict', limit=None, datatype=REAL): """ Load the input-hidden weight matrix from the original C word2vec-tool...
def load_word2vec_format( cls, fname, fvocab=None, binary=False, encoding='utf8', unicode_errors='strict', limit=None, datatype=REAL): """ Load the input-hidden weight matrix from the original C word2vec-tool...
[ "Load", "the", "input", "-", "hidden", "weight", "matrix", "from", "the", "original", "C", "word2vec", "-", "tool", "format", ".", "Note", "that", "the", "information", "stored", "in", "the", "file", "is", "incomplete", "(", "the", "binary", "tree", "is", ...
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/word2vec.py#L88-L214
[ "def", "load_word2vec_format", "(", "cls", ",", "fname", ",", "fvocab", "=", "None", ",", "binary", "=", "False", ",", "encoding", "=", "'utf8'", ",", "unicode_errors", "=", "'strict'", ",", "limit", "=", "None", ",", "datatype", "=", "REAL", ")", ":", ...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
KeyedVectors.word_vec
Accept a single word as input. Returns the word's representations in vector space, as a 1D numpy array. If `use_norm` is True, returns the normalized word vector. Example:: >>> trained_model['office'] array([ -1.40128313e-02, ...])
synonyms/word2vec.py
def word_vec(self, word, use_norm=False): """ Accept a single word as input. Returns the word's representations in vector space, as a 1D numpy array. If `use_norm` is True, returns the normalized word vector. Example:: >>> trained_model['office'] array([ -1.40...
def word_vec(self, word, use_norm=False): """ Accept a single word as input. Returns the word's representations in vector space, as a 1D numpy array. If `use_norm` is True, returns the normalized word vector. Example:: >>> trained_model['office'] array([ -1.40...
[ "Accept", "a", "single", "word", "as", "input", ".", "Returns", "the", "word", "s", "representations", "in", "vector", "space", "as", "a", "1D", "numpy", "array", ".", "If", "use_norm", "is", "True", "returns", "the", "normalized", "word", "vector", ".", ...
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/word2vec.py#L216-L234
[ "def", "word_vec", "(", "self", ",", "word", ",", "use_norm", "=", "False", ")", ":", "if", "word", "in", "self", ".", "vocab", ":", "if", "use_norm", ":", "result", "=", "self", ".", "syn0norm", "[", "self", ".", "vocab", "[", "word", "]", ".", ...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
KeyedVectors.neighbours
Get nearest words with KDTree, ranking by cosine distance
synonyms/word2vec.py
def neighbours(self, word, size = 10): """ Get nearest words with KDTree, ranking by cosine distance """ word = word.strip() v = self.word_vec(word) [distances], [points] = self.kdt.query(array([v]), k = size, return_distance = True) assert len(distances) == len(p...
def neighbours(self, word, size = 10): """ Get nearest words with KDTree, ranking by cosine distance """ word = word.strip() v = self.word_vec(word) [distances], [points] = self.kdt.query(array([v]), k = size, return_distance = True) assert len(distances) == len(p...
[ "Get", "nearest", "words", "with", "KDTree", "ranking", "by", "cosine", "distance" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/word2vec.py#L236-L253
[ "def", "neighbours", "(", "self", ",", "word", ",", "size", "=", "10", ")", ":", "word", "=", "word", ".", "strip", "(", ")", "v", "=", "self", ".", "word_vec", "(", "word", ")", "[", "distances", "]", ",", "[", "points", "]", "=", "self", ".",...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
get_random_state
Turn seed into a np.random.RandomState instance. Method originally from maciejkula/glove-python, and written by @joshloyal.
synonyms/utils.py
def get_random_state(seed): """ Turn seed into a np.random.RandomState instance. Method originally from maciejkula/glove-python, and written by @joshloyal. """ if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, (numbers.Integral, np.integer)): ...
def get_random_state(seed): """ Turn seed into a np.random.RandomState instance. Method originally from maciejkula/glove-python, and written by @joshloyal. """ if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, (numbers.Integral, np.integer)): ...
[ "Turn", "seed", "into", "a", "np", ".", "random", ".", "RandomState", "instance", ".", "Method", "originally", "from", "maciejkula", "/", "glove", "-", "python", "and", "written", "by" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L91-L104
[ "def", "get_random_state", "(", "seed", ")", ":", "if", "seed", "is", "None", "or", "seed", "is", "np", ".", "random", ":", "return", "np", ".", "random", ".", "mtrand", ".", "_rand", "if", "isinstance", "(", "seed", ",", "(", "numbers", ".", "Integr...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
file_or_filename
Return a file-like object ready to be read from the beginning. `input` is either a filename (gz/bz2 also supported) or a file-like object supporting seek.
synonyms/utils.py
def file_or_filename(input): """ Return a file-like object ready to be read from the beginning. `input` is either a filename (gz/bz2 also supported) or a file-like object supporting seek. """ if isinstance(input, string_types): # input was a filename: open as file yield smart_open(i...
def file_or_filename(input): """ Return a file-like object ready to be read from the beginning. `input` is either a filename (gz/bz2 also supported) or a file-like object supporting seek. """ if isinstance(input, string_types): # input was a filename: open as file yield smart_open(i...
[ "Return", "a", "file", "-", "like", "object", "ready", "to", "be", "read", "from", "the", "beginning", ".", "input", "is", "either", "a", "filename", "(", "gz", "/", "bz2", "also", "supported", ")", "or", "a", "file", "-", "like", "object", "supporting...
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L125-L137
[ "def", "file_or_filename", "(", "input", ")", ":", "if", "isinstance", "(", "input", ",", "string_types", ")", ":", "# input was a filename: open as file", "yield", "smart_open", "(", "input", ")", "else", ":", "# input already a file-like object; just reset to the beginn...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
deaccent
Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring. Return input string with accents removed, as unicode. >>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek") u'Sef chomutovskych komunistu dostal postou bily prasek'
synonyms/utils.py
def deaccent(text): """ Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring. Return input string with accents removed, as unicode. >>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek") u'Sef chomutovskych komunistu dostal post...
def deaccent(text): """ Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring. Return input string with accents removed, as unicode. >>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek") u'Sef chomutovskych komunistu dostal post...
[ "Remove", "accentuation", "from", "the", "given", "string", ".", "Input", "text", "is", "either", "a", "unicode", "string", "or", "utf8", "encoded", "bytestring", "." ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L140-L155
[ "def", "deaccent", "(", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "unicode", ")", ":", "# assume utf8 for byte strings, use default (strict) error handling", "text", "=", "text", ".", "decode", "(", "'utf8'", ")", "norm", "=", "unicodedata", ...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
copytree_hardlink
Recursively copy a directory ala shutils.copytree, but hardlink files instead of copying. Available on UNIX systems only.
synonyms/utils.py
def copytree_hardlink(source, dest): """ Recursively copy a directory ala shutils.copytree, but hardlink files instead of copying. Available on UNIX systems only. """ copy2 = shutil.copy2 try: shutil.copy2 = os.link shutil.copytree(source, dest) finally: shutil.copy2 ...
def copytree_hardlink(source, dest): """ Recursively copy a directory ala shutils.copytree, but hardlink files instead of copying. Available on UNIX systems only. """ copy2 = shutil.copy2 try: shutil.copy2 = os.link shutil.copytree(source, dest) finally: shutil.copy2 ...
[ "Recursively", "copy", "a", "directory", "ala", "shutils", ".", "copytree", "but", "hardlink", "files", "instead", "of", "copying", ".", "Available", "on", "UNIX", "systems", "only", "." ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L158-L168
[ "def", "copytree_hardlink", "(", "source", ",", "dest", ")", ":", "copy2", "=", "shutil", ".", "copy2", "try", ":", "shutil", ".", "copy2", "=", "os", ".", "link", "shutil", ".", "copytree", "(", "source", ",", "dest", ")", "finally", ":", "shutil", ...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
tokenize
Iteratively yield tokens as unicode strings, removing accent marks and optionally lowercasing the unidoce string by assigning True to one of the parameters, lowercase, to_lower, or lower. Input text may be either unicode or utf8-encoded byte string. The tokens on output are maximal contiguous sequence...
synonyms/utils.py
def tokenize( text, lowercase=False, deacc=False, encoding='utf8', errors="strict", to_lower=False, lower=False): """ Iteratively yield tokens as unicode strings, removing accent marks and optionally lowercasing the unidoce string by assigning True ...
def tokenize( text, lowercase=False, deacc=False, encoding='utf8', errors="strict", to_lower=False, lower=False): """ Iteratively yield tokens as unicode strings, removing accent marks and optionally lowercasing the unidoce string by assigning True ...
[ "Iteratively", "yield", "tokens", "as", "unicode", "strings", "removing", "accent", "marks", "and", "optionally", "lowercasing", "the", "unidoce", "string", "by", "assigning", "True", "to", "one", "of", "the", "parameters", "lowercase", "to_lower", "or", "lower", ...
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L171-L199
[ "def", "tokenize", "(", "text", ",", "lowercase", "=", "False", ",", "deacc", "=", "False", ",", "encoding", "=", "'utf8'", ",", "errors", "=", "\"strict\"", ",", "to_lower", "=", "False", ",", "lower", "=", "False", ")", ":", "lowercase", "=", "lowerc...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
simple_preprocess
Convert a document into a list of tokens. This lowercases, tokenizes, de-accents (optional). -- the output are final tokens = unicode strings, that won't be processed any further.
synonyms/utils.py
def simple_preprocess(doc, deacc=False, min_len=2, max_len=15): """ Convert a document into a list of tokens. This lowercases, tokenizes, de-accents (optional). -- the output are final tokens = unicode strings, that won't be processed any further. """ tokens = [ token for token in toke...
def simple_preprocess(doc, deacc=False, min_len=2, max_len=15): """ Convert a document into a list of tokens. This lowercases, tokenizes, de-accents (optional). -- the output are final tokens = unicode strings, that won't be processed any further. """ tokens = [ token for token in toke...
[ "Convert", "a", "document", "into", "a", "list", "of", "tokens", "." ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L207-L219
[ "def", "simple_preprocess", "(", "doc", ",", "deacc", "=", "False", ",", "min_len", "=", "2", ",", "max_len", "=", "15", ")", ":", "tokens", "=", "[", "token", "for", "token", "in", "tokenize", "(", "doc", ",", "lower", "=", "True", ",", "deacc", "...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
any2utf8
Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8.
synonyms/utils.py
def any2utf8(text, errors='strict', encoding='utf8'): """Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8.""" if isinstance(text, unicode): return text.encode('utf8') # do bytestring -> unicode -> utf8 full circle, to ensure valid utf8 return unicode(text, encoding, ...
def any2utf8(text, errors='strict', encoding='utf8'): """Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8.""" if isinstance(text, unicode): return text.encode('utf8') # do bytestring -> unicode -> utf8 full circle, to ensure valid utf8 return unicode(text, encoding, ...
[ "Convert", "a", "string", "(", "unicode", "or", "bytestring", "in", "encoding", ")", "to", "bytestring", "in", "utf8", "." ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L222-L227
[ "def", "any2utf8", "(", "text", ",", "errors", "=", "'strict'", ",", "encoding", "=", "'utf8'", ")", ":", "if", "isinstance", "(", "text", ",", "unicode", ")", ":", "return", "text", ".", "encode", "(", "'utf8'", ")", "# do bytestring -> unicode -> utf8 full...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
any2unicode
Convert a string (bytestring in `encoding` or unicode), to unicode.
synonyms/utils.py
def any2unicode(text, encoding='utf8', errors='strict'): """Convert a string (bytestring in `encoding` or unicode), to unicode.""" if isinstance(text, unicode): return text return unicode(text, encoding, errors=errors)
def any2unicode(text, encoding='utf8', errors='strict'): """Convert a string (bytestring in `encoding` or unicode), to unicode.""" if isinstance(text, unicode): return text return unicode(text, encoding, errors=errors)
[ "Convert", "a", "string", "(", "bytestring", "in", "encoding", "or", "unicode", ")", "to", "unicode", "." ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L233-L237
[ "def", "any2unicode", "(", "text", ",", "encoding", "=", "'utf8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "text", ",", "unicode", ")", ":", "return", "text", "return", "unicode", "(", "text", ",", "encoding", ",", "errors", ...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
is_digit
Check if an object is Number
synonyms/utils.py
def is_digit(obj): ''' Check if an object is Number ''' return isinstance(obj, (numbers.Integral, numbers.Complex, numbers.Real))
def is_digit(obj): ''' Check if an object is Number ''' return isinstance(obj, (numbers.Integral, numbers.Complex, numbers.Real))
[ "Check", "if", "an", "object", "is", "Number" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L255-L259
[ "def", "is_digit", "(", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "(", "numbers", ".", "Integral", ",", "numbers", ".", "Complex", ",", "numbers", ".", "Real", ")", ")" ]
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
is_zh
return True if ch is Chinese character. full-width puncts/latins are not counted in.
synonyms/utils.py
def is_zh(ch): """return True if ch is Chinese character. full-width puncts/latins are not counted in. """ x = ord(ch) # CJK Radicals Supplement and Kangxi radicals if 0x2e80 <= x <= 0x2fef: return True # CJK Unified Ideographs Extension A elif 0x3400 <= x <= 0x4dbf: retu...
def is_zh(ch): """return True if ch is Chinese character. full-width puncts/latins are not counted in. """ x = ord(ch) # CJK Radicals Supplement and Kangxi radicals if 0x2e80 <= x <= 0x2fef: return True # CJK Unified Ideographs Extension A elif 0x3400 <= x <= 0x4dbf: retu...
[ "return", "True", "if", "ch", "is", "Chinese", "character", ".", "full", "-", "width", "puncts", "/", "latins", "are", "not", "counted", "in", "." ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L270-L291
[ "def", "is_zh", "(", "ch", ")", ":", "x", "=", "ord", "(", "ch", ")", "# CJK Radicals Supplement and Kangxi radicals", "if", "0x2e80", "<=", "x", "<=", "0x2fef", ":", "return", "True", "# CJK Unified Ideographs Extension A", "elif", "0x3400", "<=", "x", "<=", ...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
_load_stopwords
load stop words
synonyms/synonyms.py
def _load_stopwords(file_path): ''' load stop words ''' global _stopwords if sys.version_info[0] < 3: words = open(file_path, 'r') else: words = open(file_path, 'r', encoding='utf-8') stopwords = words.readlines() for w in stopwords: _stopwords.add(any2unicode(w)....
def _load_stopwords(file_path): ''' load stop words ''' global _stopwords if sys.version_info[0] < 3: words = open(file_path, 'r') else: words = open(file_path, 'r', encoding='utf-8') stopwords = words.readlines() for w in stopwords: _stopwords.add(any2unicode(w)....
[ "load", "stop", "words" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L91-L102
[ "def", "_load_stopwords", "(", "file_path", ")", ":", "global", "_stopwords", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "words", "=", "open", "(", "file_path", ",", "'r'", ")", "else", ":", "words", "=", "open", "(", "file_path", ...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
_segment_words
segment words with jieba
synonyms/synonyms.py
def _segment_words(sen): ''' segment words with jieba ''' words, tags = [], [] m = _tokenizer.cut(sen, HMM=True) # HMM更好的识别新词 for x in m: words.append(x.word) tags.append(x.flag) return words, tags
def _segment_words(sen): ''' segment words with jieba ''' words, tags = [], [] m = _tokenizer.cut(sen, HMM=True) # HMM更好的识别新词 for x in m: words.append(x.word) tags.append(x.flag) return words, tags
[ "segment", "words", "with", "jieba" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L107-L116
[ "def", "_segment_words", "(", "sen", ")", ":", "words", ",", "tags", "=", "[", "]", ",", "[", "]", "m", "=", "_tokenizer", ".", "cut", "(", "sen", ",", "HMM", "=", "True", ")", "# HMM更好的识别新词", "for", "x", "in", "m", ":", "words", ".", "append", ...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
_load_w2v
load word2vec model
synonyms/synonyms.py
def _load_w2v(model_file=_f_model, binary=True): ''' load word2vec model ''' if not os.path.exists(model_file): print("os.path : ", os.path) raise Exception("Model file [%s] does not exist." % model_file) return KeyedVectors.load_word2vec_format( model_file, binary=binary, un...
def _load_w2v(model_file=_f_model, binary=True): ''' load word2vec model ''' if not os.path.exists(model_file): print("os.path : ", os.path) raise Exception("Model file [%s] does not exist." % model_file) return KeyedVectors.load_word2vec_format( model_file, binary=binary, un...
[ "load", "word2vec", "model" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L125-L133
[ "def", "_load_w2v", "(", "model_file", "=", "_f_model", ",", "binary", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "model_file", ")", ":", "print", "(", "\"os.path : \"", ",", "os", ".", "path", ")", "raise", "Exception",...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
_get_wv
get word2vec data by sentence sentence is segmented string.
synonyms/synonyms.py
def _get_wv(sentence, ignore=False): ''' get word2vec data by sentence sentence is segmented string. ''' global _vectors vectors = [] for y in sentence: y_ = any2unicode(y).strip() if y_ not in _stopwords: syns = nearby(y_)[0] # print("sentence %s word...
def _get_wv(sentence, ignore=False): ''' get word2vec data by sentence sentence is segmented string. ''' global _vectors vectors = [] for y in sentence: y_ = any2unicode(y).strip() if y_ not in _stopwords: syns = nearby(y_)[0] # print("sentence %s word...
[ "get", "word2vec", "data", "by", "sentence", "sentence", "is", "segmented", "string", "." ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L137-L172
[ "def", "_get_wv", "(", "sentence", ",", "ignore", "=", "False", ")", ":", "global", "_vectors", "vectors", "=", "[", "]", "for", "y", "in", "sentence", ":", "y_", "=", "any2unicode", "(", "y", ")", ".", "strip", "(", ")", "if", "y_", "not", "in", ...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
_levenshtein_distance
Return the Levenshtein distance between two strings. Based on: http://rosettacode.org/wiki/Levenshtein_distance#Python
synonyms/synonyms.py
def _levenshtein_distance(sentence1, sentence2): ''' Return the Levenshtein distance between two strings. Based on: http://rosettacode.org/wiki/Levenshtein_distance#Python ''' first = any2utf8(sentence1).decode('utf-8', 'ignore') second = any2utf8(sentence2).decode('utf-8', 'ignore') ...
def _levenshtein_distance(sentence1, sentence2): ''' Return the Levenshtein distance between two strings. Based on: http://rosettacode.org/wiki/Levenshtein_distance#Python ''' first = any2utf8(sentence1).decode('utf-8', 'ignore') second = any2utf8(sentence2).decode('utf-8', 'ignore') ...
[ "Return", "the", "Levenshtein", "distance", "between", "two", "strings", ".", "Based", "on", ":", "http", ":", "//", "rosettacode", ".", "org", "/", "wiki", "/", "Levenshtein_distance#Python" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L178-L207
[ "def", "_levenshtein_distance", "(", "sentence1", ",", "sentence2", ")", ":", "first", "=", "any2utf8", "(", "sentence1", ")", ".", "decode", "(", "'utf-8'", ",", "'ignore'", ")", "second", "=", "any2utf8", "(", "sentence2", ")", ".", "decode", "(", "'utf-...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
_nearby_levenshtein_distance
使用空间距离近的词汇优化编辑距离计算
synonyms/synonyms.py
def _nearby_levenshtein_distance(s1, s2): ''' 使用空间距离近的词汇优化编辑距离计算 ''' s1_len, s2_len = len(s1), len(s2) maxlen = s1_len if s1_len == s2_len: first, second = sorted([s1, s2]) elif s1_len < s2_len: first = s1 second = s2 maxlen = s2_len else: first = ...
def _nearby_levenshtein_distance(s1, s2): ''' 使用空间距离近的词汇优化编辑距离计算 ''' s1_len, s2_len = len(s1), len(s2) maxlen = s1_len if s1_len == s2_len: first, second = sorted([s1, s2]) elif s1_len < s2_len: first = s1 second = s2 maxlen = s2_len else: first = ...
[ "使用空间距离近的词汇优化编辑距离计算" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L225-L254
[ "def", "_nearby_levenshtein_distance", "(", "s1", ",", "s2", ")", ":", "s1_len", ",", "s2_len", "=", "len", "(", "s1", ")", ",", "len", "(", "s2", ")", "maxlen", "=", "s1_len", "if", "s1_len", "==", "s2_len", ":", "first", ",", "second", "=", "sorted...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
_similarity_distance
compute similarity with distance measurement
synonyms/synonyms.py
def _similarity_distance(s1, s2, ignore): ''' compute similarity with distance measurement ''' g = 0.0 try: g_ = cosine(_flat_sum_array(_get_wv(s1, ignore)), _flat_sum_array(_get_wv(s2, ignore))) if is_digit(g_): g = g_ except: pass u = _nearby_levenshtein_distance(s1, s2) ...
def _similarity_distance(s1, s2, ignore): ''' compute similarity with distance measurement ''' g = 0.0 try: g_ = cosine(_flat_sum_array(_get_wv(s1, ignore)), _flat_sum_array(_get_wv(s2, ignore))) if is_digit(g_): g = g_ except: pass u = _nearby_levenshtein_distance(s1, s2) ...
[ "compute", "similarity", "with", "distance", "measurement" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L256-L283
[ "def", "_similarity_distance", "(", "s1", ",", "s2", ",", "ignore", ")", ":", "g", "=", "0.0", "try", ":", "g_", "=", "cosine", "(", "_flat_sum_array", "(", "_get_wv", "(", "s1", ",", "ignore", ")", ")", ",", "_flat_sum_array", "(", "_get_wv", "(", "...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
nearby
Nearby word
synonyms/synonyms.py
def nearby(word): ''' Nearby word ''' w = any2unicode(word) # read from cache if w in _cache_nearby: return _cache_nearby[w] words, scores = [], [] try: for x in _vectors.neighbours(w): words.append(x[0]) scores.append(x[1]) except: pass # ignore key ...
def nearby(word): ''' Nearby word ''' w = any2unicode(word) # read from cache if w in _cache_nearby: return _cache_nearby[w] words, scores = [], [] try: for x in _vectors.neighbours(w): words.append(x[0]) scores.append(x[1]) except: pass # ignore key ...
[ "Nearby", "word" ]
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L290-L306
[ "def", "nearby", "(", "word", ")", ":", "w", "=", "any2unicode", "(", "word", ")", "# read from cache", "if", "w", "in", "_cache_nearby", ":", "return", "_cache_nearby", "[", "w", "]", "words", ",", "scores", "=", "[", "]", ",", "[", "]", "try", ":",...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
compare
compare similarity s1 : sentence1 s2 : sentence2 seg : True : The original sentences need jieba.cut Flase : The original sentences have been cut. ignore: True: ignore OOV words False: get vector randomly for OOV words
synonyms/synonyms.py
def compare(s1, s2, seg=True, ignore=False, stopwords=False): ''' compare similarity s1 : sentence1 s2 : sentence2 seg : True : The original sentences need jieba.cut Flase : The original sentences have been cut. ignore: True: ignore OOV words False: get vector randomly for ...
def compare(s1, s2, seg=True, ignore=False, stopwords=False): ''' compare similarity s1 : sentence1 s2 : sentence2 seg : True : The original sentences need jieba.cut Flase : The original sentences have been cut. ignore: True: ignore OOV words False: get vector randomly for ...
[ "compare", "similarity", "s1", ":", "sentence1", "s2", ":", "sentence2", "seg", ":", "True", ":", "The", "original", "sentences", "need", "jieba", ".", "cut", "Flase", ":", "The", "original", "sentences", "have", "been", "cut", ".", "ignore", ":", "True", ...
huyingxi/Synonyms
python
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L308-L344
[ "def", "compare", "(", "s1", ",", "s2", ",", "seg", "=", "True", ",", "ignore", "=", "False", ",", "stopwords", "=", "False", ")", ":", "if", "s1", "==", "s2", ":", "return", "1.0", "s1_words", "=", "[", "]", "s2_words", "=", "[", "]", "if", "s...
fe7450d51d9ad825fdba86b9377da9dc76ae26a4
train
Metric.add_sample
Add a sample to the metric. Internal-only, do not use.
prometheus_client/metrics_core.py
def add_sample(self, name, labels, value, timestamp=None, exemplar=None): """Add a sample to the metric. Internal-only, do not use.""" self.samples.append(Sample(name, labels, value, timestamp, exemplar))
def add_sample(self, name, labels, value, timestamp=None, exemplar=None): """Add a sample to the metric. Internal-only, do not use.""" self.samples.append(Sample(name, labels, value, timestamp, exemplar))
[ "Add", "a", "sample", "to", "the", "metric", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics_core.py#L38-L42
[ "def", "add_sample", "(", "self", ",", "name", ",", "labels", ",", "value", ",", "timestamp", "=", "None", ",", "exemplar", "=", "None", ")", ":", "self", ".", "samples", ".", "append", "(", "Sample", "(", "name", ",", "labels", ",", "value", ",", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
CounterMetricFamily.add_metric
Add a metric to the metric family. Args: labels: A list of label values value: The value of the metric created: Optional unix timestamp the child was created at.
prometheus_client/metrics_core.py
def add_metric(self, labels, value, created=None, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: The value of the metric created: Optional unix timestamp the child was created at. """ self.samples.append(S...
def add_metric(self, labels, value, created=None, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: The value of the metric created: Optional unix timestamp the child was created at. """ self.samples.append(S...
[ "Add", "a", "metric", "to", "the", "metric", "family", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics_core.py#L109-L119
[ "def", "add_metric", "(", "self", ",", "labels", ",", "value", ",", "created", "=", "None", ",", "timestamp", "=", "None", ")", ":", "self", ".", "samples", ".", "append", "(", "Sample", "(", "self", ".", "name", "+", "'_total'", ",", "dict", "(", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
SummaryMetricFamily.add_metric
Add a metric to the metric family. Args: labels: A list of label values count_value: The count value of the metric. sum_value: The sum value of the metric.
prometheus_client/metrics_core.py
def add_metric(self, labels, count_value, sum_value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values count_value: The count value of the metric. sum_value: The sum value of the metric. """ self.samples.append(Samp...
def add_metric(self, labels, count_value, sum_value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values count_value: The count value of the metric. sum_value: The sum value of the metric. """ self.samples.append(Samp...
[ "Add", "a", "metric", "to", "the", "metric", "family", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics_core.py#L166-L175
[ "def", "add_metric", "(", "self", ",", "labels", ",", "count_value", ",", "sum_value", ",", "timestamp", "=", "None", ")", ":", "self", ".", "samples", ".", "append", "(", "Sample", "(", "self", ".", "name", "+", "'_count'", ",", "dict", "(", "zip", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
HistogramMetricFamily.add_metric
Add a metric to the metric family. Args: labels: A list of label values buckets: A list of lists. Each inner list can be a pair of bucket name and value, or a triple of bucket name, value, and exemplar. The buckets must be sorted, and +Inf present. ...
prometheus_client/metrics_core.py
def add_metric(self, labels, buckets, sum_value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values buckets: A list of lists. Each inner list can be a pair of bucket name and value, or a triple of bucket name, valu...
def add_metric(self, labels, buckets, sum_value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values buckets: A list of lists. Each inner list can be a pair of bucket name and value, or a triple of bucket name, valu...
[ "Add", "a", "metric", "to", "the", "metric", "family", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics_core.py#L196-L223
[ "def", "add_metric", "(", "self", ",", "labels", ",", "buckets", ",", "sum_value", ",", "timestamp", "=", "None", ")", ":", "for", "b", "in", "buckets", ":", "bucket", ",", "value", "=", "b", "[", ":", "2", "]", "exemplar", "=", "None", "if", "len"...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
GaugeHistogramMetricFamily.add_metric
Add a metric to the metric family. Args: labels: A list of label values buckets: A list of pairs of bucket names and values. The buckets must be sorted, and +Inf present. gsum_value: The sum value of the metric.
prometheus_client/metrics_core.py
def add_metric(self, labels, buckets, gsum_value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values buckets: A list of pairs of bucket names and values. The buckets must be sorted, and +Inf present. gsum_value: The su...
def add_metric(self, labels, buckets, gsum_value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values buckets: A list of pairs of bucket names and values. The buckets must be sorted, and +Inf present. gsum_value: The su...
[ "Add", "a", "metric", "to", "the", "metric", "family", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics_core.py#L242-L260
[ "def", "add_metric", "(", "self", ",", "labels", ",", "buckets", ",", "gsum_value", ",", "timestamp", "=", "None", ")", ":", "for", "bucket", ",", "value", "in", "buckets", ":", "self", ".", "samples", ".", "append", "(", "Sample", "(", "self", ".", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
InfoMetricFamily.add_metric
Add a metric to the metric family. Args: labels: A list of label values value: A dict of labels
prometheus_client/metrics_core.py
def add_metric(self, labels, value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: A dict of labels """ self.samples.append(Sample( self.name + '_info', dict(dict(zip(self._labelnames, labels...
def add_metric(self, labels, value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: A dict of labels """ self.samples.append(Sample( self.name + '_info', dict(dict(zip(self._labelnames, labels...
[ "Add", "a", "metric", "to", "the", "metric", "family", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics_core.py#L279-L291
[ "def", "add_metric", "(", "self", ",", "labels", ",", "value", ",", "timestamp", "=", "None", ")", ":", "self", ".", "samples", ".", "append", "(", "Sample", "(", "self", ".", "name", "+", "'_info'", ",", "dict", "(", "dict", "(", "zip", "(", "self...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
StateSetMetricFamily.add_metric
Add a metric to the metric family. Args: labels: A list of label values value: A dict of string state names to booleans
prometheus_client/metrics_core.py
def add_metric(self, labels, value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: A dict of string state names to booleans """ labels = tuple(labels) for state, enabled in sorted(value.items()): ...
def add_metric(self, labels, value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: A dict of string state names to booleans """ labels = tuple(labels) for state, enabled in sorted(value.items()): ...
[ "Add", "a", "metric", "to", "the", "metric", "family", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics_core.py#L310-L325
[ "def", "add_metric", "(", "self", ",", "labels", ",", "value", ",", "timestamp", "=", "None", ")", ":", "labels", "=", "tuple", "(", "labels", ")", "for", "state", ",", "enabled", "in", "sorted", "(", "value", ".", "items", "(", ")", ")", ":", "v",...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
make_wsgi_app
Create a WSGI app which serves the metrics from a registry.
prometheus_client/exposition.py
def make_wsgi_app(registry=REGISTRY): """Create a WSGI app which serves the metrics from a registry.""" def prometheus_app(environ, start_response): params = parse_qs(environ.get('QUERY_STRING', '')) r = registry encoder, content_type = choose_encoder(environ.get('HTTP_ACCEPT')) ...
def make_wsgi_app(registry=REGISTRY): """Create a WSGI app which serves the metrics from a registry.""" def prometheus_app(environ, start_response): params = parse_qs(environ.get('QUERY_STRING', '')) r = registry encoder, content_type = choose_encoder(environ.get('HTTP_ACCEPT')) ...
[ "Create", "a", "WSGI", "app", "which", "serves", "the", "metrics", "from", "a", "registry", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L36-L52
[ "def", "make_wsgi_app", "(", "registry", "=", "REGISTRY", ")", ":", "def", "prometheus_app", "(", "environ", ",", "start_response", ")", ":", "params", "=", "parse_qs", "(", "environ", ".", "get", "(", "'QUERY_STRING'", ",", "''", ")", ")", "r", "=", "re...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
start_wsgi_server
Starts a WSGI server for prometheus metrics as a daemon thread.
prometheus_client/exposition.py
def start_wsgi_server(port, addr='', registry=REGISTRY): """Starts a WSGI server for prometheus metrics as a daemon thread.""" app = make_wsgi_app(registry) httpd = make_server(addr, port, app, handler_class=_SilentHandler) t = threading.Thread(target=httpd.serve_forever) t.daemon = True t.start...
def start_wsgi_server(port, addr='', registry=REGISTRY): """Starts a WSGI server for prometheus metrics as a daemon thread.""" app = make_wsgi_app(registry) httpd = make_server(addr, port, app, handler_class=_SilentHandler) t = threading.Thread(target=httpd.serve_forever) t.daemon = True t.start...
[ "Starts", "a", "WSGI", "server", "for", "prometheus", "metrics", "as", "a", "daemon", "thread", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L62-L68
[ "def", "start_wsgi_server", "(", "port", ",", "addr", "=", "''", ",", "registry", "=", "REGISTRY", ")", ":", "app", "=", "make_wsgi_app", "(", "registry", ")", "httpd", "=", "make_server", "(", "addr", ",", "port", ",", "app", ",", "handler_class", "=", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
start_http_server
Starts an HTTP server for prometheus metrics as a daemon thread
prometheus_client/exposition.py
def start_http_server(port, addr='', registry=REGISTRY): """Starts an HTTP server for prometheus metrics as a daemon thread""" CustomMetricsHandler = MetricsHandler.factory(registry) httpd = _ThreadingSimpleServer((addr, port), CustomMetricsHandler) t = threading.Thread(target=httpd.serve_forever) t...
def start_http_server(port, addr='', registry=REGISTRY): """Starts an HTTP server for prometheus metrics as a daemon thread""" CustomMetricsHandler = MetricsHandler.factory(registry) httpd = _ThreadingSimpleServer((addr, port), CustomMetricsHandler) t = threading.Thread(target=httpd.serve_forever) t...
[ "Starts", "an", "HTTP", "server", "for", "prometheus", "metrics", "as", "a", "daemon", "thread" ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L190-L196
[ "def", "start_http_server", "(", "port", ",", "addr", "=", "''", ",", "registry", "=", "REGISTRY", ")", ":", "CustomMetricsHandler", "=", "MetricsHandler", ".", "factory", "(", "registry", ")", "httpd", "=", "_ThreadingSimpleServer", "(", "(", "addr", ",", "...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
write_to_textfile
Write metrics to the given path. This is intended for use with the Node exporter textfile collector. The path must end in .prom for the textfile collector to process it.
prometheus_client/exposition.py
def write_to_textfile(path, registry): """Write metrics to the given path. This is intended for use with the Node exporter textfile collector. The path must end in .prom for the textfile collector to process it.""" tmppath = '%s.%s.%s' % (path, os.getpid(), threading.current_thread().ident) with op...
def write_to_textfile(path, registry): """Write metrics to the given path. This is intended for use with the Node exporter textfile collector. The path must end in .prom for the textfile collector to process it.""" tmppath = '%s.%s.%s' % (path, os.getpid(), threading.current_thread().ident) with op...
[ "Write", "metrics", "to", "the", "given", "path", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L199-L208
[ "def", "write_to_textfile", "(", "path", ",", "registry", ")", ":", "tmppath", "=", "'%s.%s.%s'", "%", "(", "path", ",", "os", ".", "getpid", "(", ")", ",", "threading", ".", "current_thread", "(", ")", ".", "ident", ")", "with", "open", "(", "tmppath"...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
default_handler
Default handler that implements HTTP/HTTPS connections. Used by the push_to_gateway functions. Can be re-used by other handlers.
prometheus_client/exposition.py
def default_handler(url, method, timeout, headers, data): """Default handler that implements HTTP/HTTPS connections. Used by the push_to_gateway functions. Can be re-used by other handlers.""" def handle(): request = Request(url, data=data) request.get_method = lambda: method for k...
def default_handler(url, method, timeout, headers, data): """Default handler that implements HTTP/HTTPS connections. Used by the push_to_gateway functions. Can be re-used by other handlers.""" def handle(): request = Request(url, data=data) request.get_method = lambda: method for k...
[ "Default", "handler", "that", "implements", "HTTP", "/", "HTTPS", "connections", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L211-L226
[ "def", "default_handler", "(", "url", ",", "method", ",", "timeout", ",", "headers", ",", "data", ")", ":", "def", "handle", "(", ")", ":", "request", "=", "Request", "(", "url", ",", "data", "=", "data", ")", "request", ".", "get_method", "=", "lamb...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
basic_auth_handler
Handler that implements HTTP/HTTPS connections with Basic Auth. Sets auth headers using supplied 'username' and 'password', if set. Used by the push_to_gateway functions. Can be re-used by other handlers.
prometheus_client/exposition.py
def basic_auth_handler(url, method, timeout, headers, data, username=None, password=None): """Handler that implements HTTP/HTTPS connections with Basic Auth. Sets auth headers using supplied 'username' and 'password', if set. Used by the push_to_gateway functions. Can be re-used by other handlers.""" ...
def basic_auth_handler(url, method, timeout, headers, data, username=None, password=None): """Handler that implements HTTP/HTTPS connections with Basic Auth. Sets auth headers using supplied 'username' and 'password', if set. Used by the push_to_gateway functions. Can be re-used by other handlers.""" ...
[ "Handler", "that", "implements", "HTTP", "/", "HTTPS", "connections", "with", "Basic", "Auth", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L229-L245
[ "def", "basic_auth_handler", "(", "url", ",", "method", ",", "timeout", ",", "headers", ",", "data", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "def", "handle", "(", ")", ":", "\"\"\"Handler that implements HTTP Basic Auth.\n \"...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
push_to_gateway
Push metrics to the given pushgateway. `gateway` the url for your push gateway. Either of the form 'http://pushgateway.local', or 'pushgateway.local'. Scheme defaults to 'http' if none is provided `job` is the job label to be attached to all pushed metrics `registry` is an insta...
prometheus_client/exposition.py
def push_to_gateway( gateway, job, registry, grouping_key=None, timeout=30, handler=default_handler): """Push metrics to the given pushgateway. `gateway` the url for your push gateway. Either of the form 'http://pushgateway.local', or 'pushgateway.local'. Scheme defa...
def push_to_gateway( gateway, job, registry, grouping_key=None, timeout=30, handler=default_handler): """Push metrics to the given pushgateway. `gateway` the url for your push gateway. Either of the form 'http://pushgateway.local', or 'pushgateway.local'. Scheme defa...
[ "Push", "metrics", "to", "the", "given", "pushgateway", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L248-L289
[ "def", "push_to_gateway", "(", "gateway", ",", "job", ",", "registry", ",", "grouping_key", "=", "None", ",", "timeout", "=", "30", ",", "handler", "=", "default_handler", ")", ":", "_use_gateway", "(", "'PUT'", ",", "gateway", ",", "job", ",", "registry",...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
delete_from_gateway
Delete metrics from the given pushgateway. `gateway` the url for your push gateway. Either of the form 'http://pushgateway.local', or 'pushgateway.local'. Scheme defaults to 'http' if none is provided `job` is the job label to be attached to all pushed metrics `grouping_key` ple...
prometheus_client/exposition.py
def delete_from_gateway( gateway, job, grouping_key=None, timeout=30, handler=default_handler): """Delete metrics from the given pushgateway. `gateway` the url for your push gateway. Either of the form 'http://pushgateway.local', or 'pushgateway.local'. Scheme defaults to 'h...
def delete_from_gateway( gateway, job, grouping_key=None, timeout=30, handler=default_handler): """Delete metrics from the given pushgateway. `gateway` the url for your push gateway. Either of the form 'http://pushgateway.local', or 'pushgateway.local'. Scheme defaults to 'h...
[ "Delete", "metrics", "from", "the", "given", "pushgateway", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L318-L339
[ "def", "delete_from_gateway", "(", "gateway", ",", "job", ",", "grouping_key", "=", "None", ",", "timeout", "=", "30", ",", "handler", "=", "default_handler", ")", ":", "_use_gateway", "(", "'DELETE'", ",", "gateway", ",", "job", ",", "None", ",", "groupin...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
instance_ip_grouping_key
Grouping key with instance set to the IP Address of this host.
prometheus_client/exposition.py
def instance_ip_grouping_key(): """Grouping key with instance set to the IP Address of this host.""" with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s: s.connect(('localhost', 0)) return {'instance': s.getsockname()[0]}
def instance_ip_grouping_key(): """Grouping key with instance set to the IP Address of this host.""" with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s: s.connect(('localhost', 0)) return {'instance': s.getsockname()[0]}
[ "Grouping", "key", "with", "instance", "set", "to", "the", "IP", "Address", "of", "this", "host", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L364-L368
[ "def", "instance_ip_grouping_key", "(", ")", ":", "with", "closing", "(", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", ")", "as", "s", ":", "s", ".", "connect", "(", "(", "'localhost'", ",", "0", ")", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
MetricsHandler.factory
Returns a dynamic MetricsHandler class tied to the passed registry.
prometheus_client/exposition.py
def factory(cls, registry): """Returns a dynamic MetricsHandler class tied to the passed registry. """ # This implementation relies on MetricsHandler.registry # (defined above and defaulted to REGISTRY). # As we have unicode_literals, we need to create a str() ...
def factory(cls, registry): """Returns a dynamic MetricsHandler class tied to the passed registry. """ # This implementation relies on MetricsHandler.registry # (defined above and defaulted to REGISTRY). # As we have unicode_literals, we need to create a str() ...
[ "Returns", "a", "dynamic", "MetricsHandler", "class", "tied", "to", "the", "passed", "registry", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L165-L177
[ "def", "factory", "(", "cls", ",", "registry", ")", ":", "# This implementation relies on MetricsHandler.registry", "# (defined above and defaulted to REGISTRY).", "# As we have unicode_literals, we need to create a str()", "# object for type().", "cls_name", "=", "str", "(", "cls"...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
text_fd_to_metric_families
Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's.
prometheus_client/openmetrics/parser.py
def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's. """ name = None allowed_names = [] eof = F...
def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's. """ name = None allowed_names = [] eof = F...
[ "Parse", "Prometheus", "text", "format", "from", "a", "file", "descriptor", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/openmetrics/parser.py#L292-L455
[ "def", "text_fd_to_metric_families", "(", "fd", ")", ":", "name", "=", "None", "allowed_names", "=", "[", "]", "eof", "=", "False", "seen_metrics", "=", "set", "(", ")", "def", "build_metric", "(", "name", ",", "documentation", ",", "typ", ",", "unit", "...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
CollectorRegistry.register
Add a collector to the registry.
prometheus_client/registry.py
def register(self, collector): """Add a collector to the registry.""" with self._lock: names = self._get_names(collector) duplicates = set(self._names_to_collectors).intersection(names) if duplicates: raise ValueError( 'Duplicated t...
def register(self, collector): """Add a collector to the registry.""" with self._lock: names = self._get_names(collector) duplicates = set(self._names_to_collectors).intersection(names) if duplicates: raise ValueError( 'Duplicated t...
[ "Add", "a", "collector", "to", "the", "registry", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/registry.py#L21-L32
[ "def", "register", "(", "self", ",", "collector", ")", ":", "with", "self", ".", "_lock", ":", "names", "=", "self", ".", "_get_names", "(", "collector", ")", "duplicates", "=", "set", "(", "self", ".", "_names_to_collectors", ")", ".", "intersection", "...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
CollectorRegistry.unregister
Remove a collector from the registry.
prometheus_client/registry.py
def unregister(self, collector): """Remove a collector from the registry.""" with self._lock: for name in self._collector_to_names[collector]: del self._names_to_collectors[name] del self._collector_to_names[collector]
def unregister(self, collector): """Remove a collector from the registry.""" with self._lock: for name in self._collector_to_names[collector]: del self._names_to_collectors[name] del self._collector_to_names[collector]
[ "Remove", "a", "collector", "from", "the", "registry", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/registry.py#L34-L39
[ "def", "unregister", "(", "self", ",", "collector", ")", ":", "with", "self", ".", "_lock", ":", "for", "name", "in", "self", ".", "_collector_to_names", "[", "collector", "]", ":", "del", "self", ".", "_names_to_collectors", "[", "name", "]", "del", "se...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
CollectorRegistry._get_names
Get names of timeseries the collector produces.
prometheus_client/registry.py
def _get_names(self, collector): """Get names of timeseries the collector produces.""" desc_func = None # If there's a describe function, use it. try: desc_func = collector.describe except AttributeError: pass # Otherwise, if auto describe is enabl...
def _get_names(self, collector): """Get names of timeseries the collector produces.""" desc_func = None # If there's a describe function, use it. try: desc_func = collector.describe except AttributeError: pass # Otherwise, if auto describe is enabl...
[ "Get", "names", "of", "timeseries", "the", "collector", "produces", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/registry.py#L41-L67
[ "def", "_get_names", "(", "self", ",", "collector", ")", ":", "desc_func", "=", "None", "# If there's a describe function, use it.", "try", ":", "desc_func", "=", "collector", ".", "describe", "except", "AttributeError", ":", "pass", "# Otherwise, if auto describe is en...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
CollectorRegistry.collect
Yields metrics from the collectors in the registry.
prometheus_client/registry.py
def collect(self): """Yields metrics from the collectors in the registry.""" collectors = None with self._lock: collectors = copy.copy(self._collector_to_names) for collector in collectors: for metric in collector.collect(): yield metric
def collect(self): """Yields metrics from the collectors in the registry.""" collectors = None with self._lock: collectors = copy.copy(self._collector_to_names) for collector in collectors: for metric in collector.collect(): yield metric
[ "Yields", "metrics", "from", "the", "collectors", "in", "the", "registry", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/registry.py#L69-L76
[ "def", "collect", "(", "self", ")", ":", "collectors", "=", "None", "with", "self", ".", "_lock", ":", "collectors", "=", "copy", ".", "copy", "(", "self", ".", "_collector_to_names", ")", "for", "collector", "in", "collectors", ":", "for", "metric", "in...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
CollectorRegistry.restricted_registry
Returns object that only collects some metrics. Returns an object which upon collect() will return only samples with the given names. Intended usage is: generate_latest(REGISTRY.restricted_registry(['a_timeseries'])) Experimental.
prometheus_client/registry.py
def restricted_registry(self, names): """Returns object that only collects some metrics. Returns an object which upon collect() will return only samples with the given names. Intended usage is: generate_latest(REGISTRY.restricted_registry(['a_timeseries'])) Experim...
def restricted_registry(self, names): """Returns object that only collects some metrics. Returns an object which upon collect() will return only samples with the given names. Intended usage is: generate_latest(REGISTRY.restricted_registry(['a_timeseries'])) Experim...
[ "Returns", "object", "that", "only", "collects", "some", "metrics", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/registry.py#L78-L107
[ "def", "restricted_registry", "(", "self", ",", "names", ")", ":", "names", "=", "set", "(", "names", ")", "collectors", "=", "set", "(", ")", "with", "self", ".", "_lock", ":", "for", "name", "in", "names", ":", "if", "name", "in", "self", ".", "_...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
CollectorRegistry.get_sample_value
Returns the sample value, or None if not found. This is inefficient, and intended only for use in unittests.
prometheus_client/registry.py
def get_sample_value(self, name, labels=None): """Returns the sample value, or None if not found. This is inefficient, and intended only for use in unittests. """ if labels is None: labels = {} for metric in self.collect(): for s in metric.samples: ...
def get_sample_value(self, name, labels=None): """Returns the sample value, or None if not found. This is inefficient, and intended only for use in unittests. """ if labels is None: labels = {} for metric in self.collect(): for s in metric.samples: ...
[ "Returns", "the", "sample", "value", "or", "None", "if", "not", "found", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/registry.py#L109-L120
[ "def", "get_sample_value", "(", "self", ",", "name", ",", "labels", "=", "None", ")", ":", "if", "labels", "is", "None", ":", "labels", "=", "{", "}", "for", "metric", "in", "self", ".", "collect", "(", ")", ":", "for", "s", "in", "metric", ".", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
mark_process_dead
Do bookkeeping for when one process dies in a multi-process setup.
prometheus_client/multiprocess.py
def mark_process_dead(pid, path=None): """Do bookkeeping for when one process dies in a multi-process setup.""" if path is None: path = os.environ.get('prometheus_multiproc_dir') for f in glob.glob(os.path.join(path, 'gauge_livesum_{0}.db'.format(pid))): os.remove(f) for f in glob.glob(o...
def mark_process_dead(pid, path=None): """Do bookkeeping for when one process dies in a multi-process setup.""" if path is None: path = os.environ.get('prometheus_multiproc_dir') for f in glob.glob(os.path.join(path, 'gauge_livesum_{0}.db'.format(pid))): os.remove(f) for f in glob.glob(o...
[ "Do", "bookkeeping", "for", "when", "one", "process", "dies", "in", "a", "multi", "-", "process", "setup", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/multiprocess.py#L121-L128
[ "def", "mark_process_dead", "(", "pid", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "os", ".", "environ", ".", "get", "(", "'prometheus_multiproc_dir'", ")", "for", "f", "in", "glob", ".", "glob", "(", "os", ".",...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
MultiProcessCollector.merge
Merge metrics from given mmap files. By default, histograms are accumulated, as per prometheus wire format. But if writing the merged data back to mmap files, use accumulate=False to avoid compound accumulation.
prometheus_client/multiprocess.py
def merge(files, accumulate=True): """Merge metrics from given mmap files. By default, histograms are accumulated, as per prometheus wire format. But if writing the merged data back to mmap files, use accumulate=False to avoid compound accumulation. """ metrics = {} ...
def merge(files, accumulate=True): """Merge metrics from given mmap files. By default, histograms are accumulated, as per prometheus wire format. But if writing the merged data back to mmap files, use accumulate=False to avoid compound accumulation. """ metrics = {} ...
[ "Merge", "metrics", "from", "given", "mmap", "files", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/multiprocess.py#L29-L114
[ "def", "merge", "(", "files", ",", "accumulate", "=", "True", ")", ":", "metrics", "=", "{", "}", "for", "f", "in", "files", ":", "parts", "=", "os", ".", "path", ".", "basename", "(", "f", ")", ".", "split", "(", "'_'", ")", "typ", "=", "parts...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
getargspec
A replacement for inspect.getargspec
prometheus_client/decorator.py
def getargspec(f): """A replacement for inspect.getargspec""" spec = getfullargspec(f) return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
def getargspec(f): """A replacement for inspect.getargspec""" spec = getfullargspec(f) return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
[ "A", "replacement", "for", "inspect", ".", "getargspec" ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/decorator.py#L78-L81
[ "def", "getargspec", "(", "f", ")", ":", "spec", "=", "getfullargspec", "(", "f", ")", "return", "ArgSpec", "(", "spec", ".", "args", ",", "spec", ".", "varargs", ",", "spec", ".", "varkw", ",", "spec", ".", "defaults", ")" ]
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
decorate
decorate(func, caller) decorates a function using a caller.
prometheus_client/decorator.py
def decorate(func, caller): """ decorate(func, caller) decorates a function using a caller. """ evaldict = dict(_call_=caller, _func_=func) fun = FunctionMaker.create( func, "return _call_(_func_, %(shortsignature)s)", evaldict, __wrapped__=func) if hasattr(func, '__qualname__'):...
def decorate(func, caller): """ decorate(func, caller) decorates a function using a caller. """ evaldict = dict(_call_=caller, _func_=func) fun = FunctionMaker.create( func, "return _call_(_func_, %(shortsignature)s)", evaldict, __wrapped__=func) if hasattr(func, '__qualname__'):...
[ "decorate", "(", "func", "caller", ")", "decorates", "a", "function", "using", "a", "caller", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/decorator.py#L229-L239
[ "def", "decorate", "(", "func", ",", "caller", ")", ":", "evaldict", "=", "dict", "(", "_call_", "=", "caller", ",", "_func_", "=", "func", ")", "fun", "=", "FunctionMaker", ".", "create", "(", "func", ",", "\"return _call_(_func_, %(shortsignature)s)\"", ",...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
decorator
decorator(caller) converts a caller function into a decorator
prometheus_client/decorator.py
def decorator(caller, _func=None): """decorator(caller) converts a caller function into a decorator""" if _func is not None: # return a decorated function # this is obsolete behavior; you should use decorate instead return decorate(_func, caller) # else return a decorator function if in...
def decorator(caller, _func=None): """decorator(caller) converts a caller function into a decorator""" if _func is not None: # return a decorated function # this is obsolete behavior; you should use decorate instead return decorate(_func, caller) # else return a decorator function if in...
[ "decorator", "(", "caller", ")", "converts", "a", "caller", "function", "into", "a", "decorator" ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/decorator.py#L242-L265
[ "def", "decorator", "(", "caller", ",", "_func", "=", "None", ")", ":", "if", "_func", "is", "not", "None", ":", "# return a decorated function", "# this is obsolete behavior; you should use decorate instead", "return", "decorate", "(", "_func", ",", "caller", ")", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
append
Append ``a`` to the list of the virtual ancestors, unless it is already included.
prometheus_client/decorator.py
def append(a, vancestors): """ Append ``a`` to the list of the virtual ancestors, unless it is already included. """ add = True for j, va in enumerate(vancestors): if issubclass(va, a): add = False break if issubclass(a, va): vancestors[j] = a ...
def append(a, vancestors): """ Append ``a`` to the list of the virtual ancestors, unless it is already included. """ add = True for j, va in enumerate(vancestors): if issubclass(va, a): add = False break if issubclass(a, va): vancestors[j] = a ...
[ "Append", "a", "to", "the", "list", "of", "the", "virtual", "ancestors", "unless", "it", "is", "already", "included", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/decorator.py#L306-L320
[ "def", "append", "(", "a", ",", "vancestors", ")", ":", "add", "=", "True", "for", "j", ",", "va", "in", "enumerate", "(", "vancestors", ")", ":", "if", "issubclass", "(", "va", ",", "a", ")", ":", "add", "=", "False", "break", "if", "issubclass", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
text_fd_to_metric_families
Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's.
prometheus_client/parser.py
def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's. """ name = '' documentation = '' typ = 'un...
def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's. """ name = '' documentation = '' typ = 'un...
[ "Parse", "Prometheus", "text", "format", "from", "a", "file", "descriptor", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/parser.py#L144-L232
[ "def", "text_fd_to_metric_families", "(", "fd", ")", ":", "name", "=", "''", "documentation", "=", "''", "typ", "=", "'untyped'", "samples", "=", "[", "]", "allowed_names", "=", "[", "]", "def", "build_metric", "(", "name", ",", "documentation", ",", "typ"...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
mmap_key
Format a key for use in the mmap file.
prometheus_client/mmap_dict.py
def mmap_key(metric_name, name, labelnames, labelvalues): """Format a key for use in the mmap file.""" # ensure labels are in consistent order for identity labels = dict(zip(labelnames, labelvalues)) return json.dumps([metric_name, name, labels], sort_keys=True)
def mmap_key(metric_name, name, labelnames, labelvalues): """Format a key for use in the mmap file.""" # ensure labels are in consistent order for identity labels = dict(zip(labelnames, labelvalues)) return json.dumps([metric_name, name, labels], sort_keys=True)
[ "Format", "a", "key", "for", "use", "in", "the", "mmap", "file", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/mmap_dict.py#L125-L129
[ "def", "mmap_key", "(", "metric_name", ",", "name", ",", "labelnames", ",", "labelvalues", ")", ":", "# ensure labels are in consistent order for identity", "labels", "=", "dict", "(", "zip", "(", "labelnames", ",", "labelvalues", ")", ")", "return", "json", ".", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
MmapedDict._init_value
Initialize a value. Lock must be held by caller.
prometheus_client/mmap_dict.py
def _init_value(self, key): """Initialize a value. Lock must be held by caller.""" encoded = key.encode('utf-8') # Pad to be 8-byte aligned. padded = encoded + (b' ' * (8 - (len(encoded) + 4) % 8)) value = struct.pack('i{0}sd'.format(len(padded)).encode(), len(encoded), padded, 0...
def _init_value(self, key): """Initialize a value. Lock must be held by caller.""" encoded = key.encode('utf-8') # Pad to be 8-byte aligned. padded = encoded + (b' ' * (8 - (len(encoded) + 4) % 8)) value = struct.pack('i{0}sd'.format(len(padded)).encode(), len(encoded), padded, 0...
[ "Initialize", "a", "value", ".", "Lock", "must", "be", "held", "by", "caller", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/mmap_dict.py#L56-L71
[ "def", "_init_value", "(", "self", ",", "key", ")", ":", "encoded", "=", "key", ".", "encode", "(", "'utf-8'", ")", "# Pad to be 8-byte aligned.", "padded", "=", "encoded", "+", "(", "b' '", "*", "(", "8", "-", "(", "len", "(", "encoded", ")", "+", "...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
MmapedDict._read_all_values
Yield (key, value, pos). No locking is performed.
prometheus_client/mmap_dict.py
def _read_all_values(self): """Yield (key, value, pos). No locking is performed.""" pos = 8 # cache variables to local ones and prevent attributes lookup # on every loop iteration used = self._used data = self._m unpack_from = struct.unpack_from while p...
def _read_all_values(self): """Yield (key, value, pos). No locking is performed.""" pos = 8 # cache variables to local ones and prevent attributes lookup # on every loop iteration used = self._used data = self._m unpack_from = struct.unpack_from while p...
[ "Yield", "(", "key", "value", "pos", ")", ".", "No", "locking", "is", "performed", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/mmap_dict.py#L73-L96
[ "def", "_read_all_values", "(", "self", ")", ":", "pos", "=", "8", "# cache variables to local ones and prevent attributes lookup", "# on every loop iteration", "used", "=", "self", ".", "_used", "data", "=", "self", ".", "_m", "unpack_from", "=", "struct", ".", "un...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
MetricWrapperBase.labels
Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels(...
prometheus_client/metrics.py
def labels(self, *labelvalues, **labelkwargs): """Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTT...
def labels(self, *labelvalues, **labelkwargs): """Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTT...
[ "Return", "the", "child", "for", "the", "given", "labelset", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics.py#L105-L158
[ "def", "labels", "(", "self", ",", "*", "labelvalues", ",", "*", "*", "labelkwargs", ")", ":", "if", "not", "self", ".", "_labelnames", ":", "raise", "ValueError", "(", "'No label names were set when constructing %s'", "%", "self", ")", "if", "self", ".", "_...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
MetricWrapperBase.remove
Remove the given labelset from the metric.
prometheus_client/metrics.py
def remove(self, *labelvalues): if not self._labelnames: raise ValueError('No label names were set when constructing %s' % self) """Remove the given labelset from the metric.""" if len(labelvalues) != len(self._labelnames): raise ValueError('Incorrect label count (expect...
def remove(self, *labelvalues): if not self._labelnames: raise ValueError('No label names were set when constructing %s' % self) """Remove the given labelset from the metric.""" if len(labelvalues) != len(self._labelnames): raise ValueError('Incorrect label count (expect...
[ "Remove", "the", "given", "labelset", "from", "the", "metric", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics.py#L160-L169
[ "def", "remove", "(", "self", ",", "*", "labelvalues", ")", ":", "if", "not", "self", ".", "_labelnames", ":", "raise", "ValueError", "(", "'No label names were set when constructing %s'", "%", "self", ")", "if", "len", "(", "labelvalues", ")", "!=", "len", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
Gauge.set_function
Call the provided function to return the Gauge value. The function must return a float, and may be called from multiple threads. All other methods of the Gauge become NOOPs.
prometheus_client/metrics.py
def set_function(self, f): """Call the provided function to return the Gauge value. The function must return a float, and may be called from multiple threads. All other methods of the Gauge become NOOPs. """ def samples(self): return (('', {}, float(f())),) ...
def set_function(self, f): """Call the provided function to return the Gauge value. The function must return a float, and may be called from multiple threads. All other methods of the Gauge become NOOPs. """ def samples(self): return (('', {}, float(f())),) ...
[ "Call", "the", "provided", "function", "to", "return", "the", "Gauge", "value", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics.py#L362-L372
[ "def", "set_function", "(", "self", ",", "f", ")", ":", "def", "samples", "(", "self", ")", ":", "return", "(", "(", "''", ",", "{", "}", ",", "float", "(", "f", "(", ")", ")", ")", ",", ")", "self", ".", "_child_samples", "=", "types", ".", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
Summary.observe
Observe the given amount.
prometheus_client/metrics.py
def observe(self, amount): """Observe the given amount.""" self._count.inc(1) self._sum.inc(amount)
def observe(self, amount): """Observe the given amount.""" self._count.inc(1) self._sum.inc(amount)
[ "Observe", "the", "given", "amount", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics.py#L417-L420
[ "def", "observe", "(", "self", ",", "amount", ")", ":", "self", ".", "_count", ".", "inc", "(", "1", ")", "self", ".", "_sum", ".", "inc", "(", "amount", ")" ]
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
Histogram.observe
Observe the given amount.
prometheus_client/metrics.py
def observe(self, amount): """Observe the given amount.""" self._sum.inc(amount) for i, bound in enumerate(self._upper_bounds): if amount <= bound: self._buckets[i].inc(1) break
def observe(self, amount): """Observe the given amount.""" self._sum.inc(amount) for i, bound in enumerate(self._upper_bounds): if amount <= bound: self._buckets[i].inc(1) break
[ "Observe", "the", "given", "amount", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics.py#L525-L531
[ "def", "observe", "(", "self", ",", "amount", ")", ":", "self", ".", "_sum", ".", "inc", "(", "amount", ")", "for", "i", ",", "bound", "in", "enumerate", "(", "self", ".", "_upper_bounds", ")", ":", "if", "amount", "<=", "bound", ":", "self", ".", ...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
Info.info
Set info metric.
prometheus_client/metrics.py
def info(self, val): """Set info metric.""" if self._labelname_set.intersection(val.keys()): raise ValueError('Overlapping labels for Info metric, metric: %s child: %s' % ( self._labelnames, val)) with self._lock: self._value = dict(val)
def info(self, val): """Set info metric.""" if self._labelname_set.intersection(val.keys()): raise ValueError('Overlapping labels for Info metric, metric: %s child: %s' % ( self._labelnames, val)) with self._lock: self._value = dict(val)
[ "Set", "info", "metric", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics.py#L575-L581
[ "def", "info", "(", "self", ",", "val", ")", ":", "if", "self", ".", "_labelname_set", ".", "intersection", "(", "val", ".", "keys", "(", ")", ")", ":", "raise", "ValueError", "(", "'Overlapping labels for Info metric, metric: %s child: %s'", "%", "(", "self",...
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
Enum.state
Set enum metric state.
prometheus_client/metrics.py
def state(self, state): """Set enum metric state.""" with self._lock: self._value = self._states.index(state)
def state(self, state): """Set enum metric state.""" with self._lock: self._value = self._states.index(state)
[ "Set", "enum", "metric", "state", "." ]
prometheus/client_python
python
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics.py#L634-L637
[ "def", "state", "(", "self", ",", "state", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_value", "=", "self", ".", "_states", ".", "index", "(", "state", ")" ]
31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb
train
RFPDupeFilter.from_settings
Returns an instance from given settings. This uses by default the key ``dupefilter:<timestamp>``. When using the ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as it needs to pass the spider name in the key. Parameters ---------- settings : scrapy.s...
src/scrapy_redis/dupefilter.py
def from_settings(cls, settings): """Returns an instance from given settings. This uses by default the key ``dupefilter:<timestamp>``. When using the ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as it needs to pass the spider name in the key. Parameters ...
def from_settings(cls, settings): """Returns an instance from given settings. This uses by default the key ``dupefilter:<timestamp>``. When using the ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as it needs to pass the spider name in the key. Parameters ...
[ "Returns", "an", "instance", "from", "given", "settings", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/dupefilter.py#L43-L68
[ "def", "from_settings", "(", "cls", ",", "settings", ")", ":", "server", "=", "get_redis_from_settings", "(", "settings", ")", "# XXX: This creates one-time key. needed to support to use this", "# class as standalone dupefilter with scrapy's default scheduler", "# if scrapy passes sp...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
RFPDupeFilter.request_seen
Returns True if request was already seen. Parameters ---------- request : scrapy.http.Request Returns ------- bool
src/scrapy_redis/dupefilter.py
def request_seen(self, request): """Returns True if request was already seen. Parameters ---------- request : scrapy.http.Request Returns ------- bool """ fp = self.request_fingerprint(request) # This returns the number of values added, ...
def request_seen(self, request): """Returns True if request was already seen. Parameters ---------- request : scrapy.http.Request Returns ------- bool """ fp = self.request_fingerprint(request) # This returns the number of values added, ...
[ "Returns", "True", "if", "request", "was", "already", "seen", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/dupefilter.py#L86-L101
[ "def", "request_seen", "(", "self", ",", "request", ")", ":", "fp", "=", "self", ".", "request_fingerprint", "(", "request", ")", "# This returns the number of values added, zero if already exists.", "added", "=", "self", ".", "server", ".", "sadd", "(", "self", "...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
RFPDupeFilter.log
Logs given request. Parameters ---------- request : scrapy.http.Request spider : scrapy.spiders.Spider
src/scrapy_redis/dupefilter.py
def log(self, request, spider): """Logs given request. Parameters ---------- request : scrapy.http.Request spider : scrapy.spiders.Spider """ if self.debug: msg = "Filtered duplicate request: %(request)s" self.logger.debug(msg, {'request'...
def log(self, request, spider): """Logs given request. Parameters ---------- request : scrapy.http.Request spider : scrapy.spiders.Spider """ if self.debug: msg = "Filtered duplicate request: %(request)s" self.logger.debug(msg, {'request'...
[ "Logs", "given", "request", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/dupefilter.py#L140-L157
[ "def", "log", "(", "self", ",", "request", ",", "spider", ")", ":", "if", "self", ".", "debug", ":", "msg", "=", "\"Filtered duplicate request: %(request)s\"", "self", ".", "logger", ".", "debug", "(", "msg", ",", "{", "'request'", ":", "request", "}", "...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
process_items
Process items from a redis queue. Parameters ---------- r : Redis Redis connection instance. keys : list List of keys to read the items from. timeout: int Read timeout.
example-project/process_items.py
def process_items(r, keys, timeout, limit=0, log_every=1000, wait=.1): """Process items from a redis queue. Parameters ---------- r : Redis Redis connection instance. keys : list List of keys to read the items from. timeout: int Read timeout. """ limit = limit o...
def process_items(r, keys, timeout, limit=0, log_every=1000, wait=.1): """Process items from a redis queue. Parameters ---------- r : Redis Redis connection instance. keys : list List of keys to read the items from. timeout: int Read timeout. """ limit = limit o...
[ "Process", "items", "from", "a", "redis", "queue", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/example-project/process_items.py#L20-L61
[ "def", "process_items", "(", "r", ",", "keys", ",", "timeout", ",", "limit", "=", "0", ",", "log_every", "=", "1000", ",", "wait", "=", ".1", ")", ":", "limit", "=", "limit", "or", "float", "(", "'inf'", ")", "processed", "=", "0", "while", "proces...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
get_redis_from_settings
Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_PARAMS`` setting. Parameters ---------- settin...
src/scrapy_redis/connection.py
def get_redis_from_settings(settings): """Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_PARAMS`` sett...
def get_redis_from_settings(settings): """Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_PARAMS`` sett...
[ "Returns", "a", "redis", "client", "instance", "from", "given", "Scrapy", "settings", "object", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/connection.py#L17-L60
[ "def", "get_redis_from_settings", "(", "settings", ")", ":", "params", "=", "defaults", ".", "REDIS_PARAMS", ".", "copy", "(", ")", "params", ".", "update", "(", "settings", ".", "getdict", "(", "'REDIS_PARAMS'", ")", ")", "# XXX: Deprecate REDIS_* settings.", "...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
get_redis
Returns a redis client instance. Parameters ---------- redis_cls : class, optional Defaults to ``redis.StrictRedis``. url : str, optional If given, ``redis_cls.from_url`` is used to instantiate the class. **kwargs Extra parameters to be passed to the ``redis_cls`` class. ...
src/scrapy_redis/connection.py
def get_redis(**kwargs): """Returns a redis client instance. Parameters ---------- redis_cls : class, optional Defaults to ``redis.StrictRedis``. url : str, optional If given, ``redis_cls.from_url`` is used to instantiate the class. **kwargs Extra parameters to be passed...
def get_redis(**kwargs): """Returns a redis client instance. Parameters ---------- redis_cls : class, optional Defaults to ``redis.StrictRedis``. url : str, optional If given, ``redis_cls.from_url`` is used to instantiate the class. **kwargs Extra parameters to be passed...
[ "Returns", "a", "redis", "client", "instance", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/connection.py#L67-L90
[ "def", "get_redis", "(", "*", "*", "kwargs", ")", ":", "redis_cls", "=", "kwargs", ".", "pop", "(", "'redis_cls'", ",", "defaults", ".", "REDIS_CLS", ")", "url", "=", "kwargs", ".", "pop", "(", "'url'", ",", "None", ")", "if", "url", ":", "return", ...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
bytes_to_str
Returns a str if a bytes object is given.
src/scrapy_redis/utils.py
def bytes_to_str(s, encoding='utf-8'): """Returns a str if a bytes object is given.""" if six.PY3 and isinstance(s, bytes): return s.decode(encoding) return s
def bytes_to_str(s, encoding='utf-8'): """Returns a str if a bytes object is given.""" if six.PY3 and isinstance(s, bytes): return s.decode(encoding) return s
[ "Returns", "a", "str", "if", "a", "bytes", "object", "is", "given", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/utils.py#L4-L8
[ "def", "bytes_to_str", "(", "s", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "six", ".", "PY3", "and", "isinstance", "(", "s", ",", "bytes", ")", ":", "return", "s", ".", "decode", "(", "encoding", ")", "return", "s" ]
31c022dd145654cb4ea1429f09852a82afa0a01c
train
RedisMixin.setup_redis
Setup redis connection and idle signal. This should be called after the spider has set its crawler object.
src/scrapy_redis/spiders.py
def setup_redis(self, crawler=None): """Setup redis connection and idle signal. This should be called after the spider has set its crawler object. """ if self.server is not None: return if crawler is None: # We allow optional crawler argument to keep bac...
def setup_redis(self, crawler=None): """Setup redis connection and idle signal. This should be called after the spider has set its crawler object. """ if self.server is not None: return if crawler is None: # We allow optional crawler argument to keep bac...
[ "Setup", "redis", "connection", "and", "idle", "signal", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/spiders.py#L22-L73
[ "def", "setup_redis", "(", "self", ",", "crawler", "=", "None", ")", ":", "if", "self", ".", "server", "is", "not", "None", ":", "return", "if", "crawler", "is", "None", ":", "# We allow optional crawler argument to keep backwards", "# compatibility.", "# XXX: Rai...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
RedisMixin.next_requests
Returns a request to be scheduled or none.
src/scrapy_redis/spiders.py
def next_requests(self): """Returns a request to be scheduled or none.""" use_set = self.settings.getbool('REDIS_START_URLS_AS_SET', defaults.START_URLS_AS_SET) fetch_one = self.server.spop if use_set else self.server.lpop # XXX: Do we need to use a timeout here? found = 0 ...
def next_requests(self): """Returns a request to be scheduled or none.""" use_set = self.settings.getbool('REDIS_START_URLS_AS_SET', defaults.START_URLS_AS_SET) fetch_one = self.server.spop if use_set else self.server.lpop # XXX: Do we need to use a timeout here? found = 0 ...
[ "Returns", "a", "request", "to", "be", "scheduled", "or", "none", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/spiders.py#L75-L95
[ "def", "next_requests", "(", "self", ")", ":", "use_set", "=", "self", ".", "settings", ".", "getbool", "(", "'REDIS_START_URLS_AS_SET'", ",", "defaults", ".", "START_URLS_AS_SET", ")", "fetch_one", "=", "self", ".", "server", ".", "spop", "if", "use_set", "...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
RedisMixin.make_request_from_data
Returns a Request instance from data coming from Redis. By default, ``data`` is an encoded URL. You can override this method to provide your own message decoding. Parameters ---------- data : bytes Message from redis.
src/scrapy_redis/spiders.py
def make_request_from_data(self, data): """Returns a Request instance from data coming from Redis. By default, ``data`` is an encoded URL. You can override this method to provide your own message decoding. Parameters ---------- data : bytes Message from redi...
def make_request_from_data(self, data): """Returns a Request instance from data coming from Redis. By default, ``data`` is an encoded URL. You can override this method to provide your own message decoding. Parameters ---------- data : bytes Message from redi...
[ "Returns", "a", "Request", "instance", "from", "data", "coming", "from", "Redis", "." ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/spiders.py#L97-L110
[ "def", "make_request_from_data", "(", "self", ",", "data", ")", ":", "url", "=", "bytes_to_str", "(", "data", ",", "self", ".", "redis_encoding", ")", "return", "self", ".", "make_requests_from_url", "(", "url", ")" ]
31c022dd145654cb4ea1429f09852a82afa0a01c
train
RedisMixin.schedule_next_requests
Schedules a request if available
src/scrapy_redis/spiders.py
def schedule_next_requests(self): """Schedules a request if available""" # TODO: While there is capacity, schedule a batch of redis requests. for req in self.next_requests(): self.crawler.engine.crawl(req, spider=self)
def schedule_next_requests(self): """Schedules a request if available""" # TODO: While there is capacity, schedule a batch of redis requests. for req in self.next_requests(): self.crawler.engine.crawl(req, spider=self)
[ "Schedules", "a", "request", "if", "available" ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/spiders.py#L112-L116
[ "def", "schedule_next_requests", "(", "self", ")", ":", "# TODO: While there is capacity, schedule a batch of redis requests.", "for", "req", "in", "self", ".", "next_requests", "(", ")", ":", "self", ".", "crawler", ".", "engine", ".", "crawl", "(", "req", ",", "...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
Base._encode_request
Encode a request object
src/scrapy_redis/queue.py
def _encode_request(self, request): """Encode a request object""" obj = request_to_dict(request, self.spider) return self.serializer.dumps(obj)
def _encode_request(self, request): """Encode a request object""" obj = request_to_dict(request, self.spider) return self.serializer.dumps(obj)
[ "Encode", "a", "request", "object" ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L40-L43
[ "def", "_encode_request", "(", "self", ",", "request", ")", ":", "obj", "=", "request_to_dict", "(", "request", ",", "self", ".", "spider", ")", "return", "self", ".", "serializer", ".", "dumps", "(", "obj", ")" ]
31c022dd145654cb4ea1429f09852a82afa0a01c
train
Base._decode_request
Decode an request previously encoded
src/scrapy_redis/queue.py
def _decode_request(self, encoded_request): """Decode an request previously encoded""" obj = self.serializer.loads(encoded_request) return request_from_dict(obj, self.spider)
def _decode_request(self, encoded_request): """Decode an request previously encoded""" obj = self.serializer.loads(encoded_request) return request_from_dict(obj, self.spider)
[ "Decode", "an", "request", "previously", "encoded" ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L45-L48
[ "def", "_decode_request", "(", "self", ",", "encoded_request", ")", ":", "obj", "=", "self", ".", "serializer", ".", "loads", "(", "encoded_request", ")", "return", "request_from_dict", "(", "obj", ",", "self", ".", "spider", ")" ]
31c022dd145654cb4ea1429f09852a82afa0a01c
train
FifoQueue.push
Push a request
src/scrapy_redis/queue.py
def push(self, request): """Push a request""" self.server.lpush(self.key, self._encode_request(request))
def push(self, request): """Push a request""" self.server.lpush(self.key, self._encode_request(request))
[ "Push", "a", "request" ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L74-L76
[ "def", "push", "(", "self", ",", "request", ")", ":", "self", ".", "server", ".", "lpush", "(", "self", ".", "key", ",", "self", ".", "_encode_request", "(", "request", ")", ")" ]
31c022dd145654cb4ea1429f09852a82afa0a01c
train
PriorityQueue.push
Push a request
src/scrapy_redis/queue.py
def push(self, request): """Push a request""" data = self._encode_request(request) score = -request.priority # We don't use zadd method as the order of arguments change depending on # whether the class is Redis or StrictRedis, and the option of using # kwargs only accepts...
def push(self, request): """Push a request""" data = self._encode_request(request) score = -request.priority # We don't use zadd method as the order of arguments change depending on # whether the class is Redis or StrictRedis, and the option of using # kwargs only accepts...
[ "Push", "a", "request" ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L97-L104
[ "def", "push", "(", "self", ",", "request", ")", ":", "data", "=", "self", ".", "_encode_request", "(", "request", ")", "score", "=", "-", "request", ".", "priority", "# We don't use zadd method as the order of arguments change depending on", "# whether the class is Red...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
PriorityQueue.pop
Pop a request timeout not support in this queue class
src/scrapy_redis/queue.py
def pop(self, timeout=0): """ Pop a request timeout not support in this queue class """ # use atomic range/remove using multi/exec pipe = self.server.pipeline() pipe.multi() pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0) results, count...
def pop(self, timeout=0): """ Pop a request timeout not support in this queue class """ # use atomic range/remove using multi/exec pipe = self.server.pipeline() pipe.multi() pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0) results, count...
[ "Pop", "a", "request", "timeout", "not", "support", "in", "this", "queue", "class" ]
rmax/scrapy-redis
python
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L106-L117
[ "def", "pop", "(", "self", ",", "timeout", "=", "0", ")", ":", "# use atomic range/remove using multi/exec", "pipe", "=", "self", ".", "server", ".", "pipeline", "(", ")", "pipe", ".", "multi", "(", ")", "pipe", ".", "zrange", "(", "self", ".", "key", ...
31c022dd145654cb4ea1429f09852a82afa0a01c
train
rgb2short
Find the closest xterm-256 approximation to the given RGB value. @param r,g,b: each is a number between 0-255 for the Red, Green, and Blue values @returns: integer between 0 and 255, compatible with xterm. >>> rgb2short(18, 52, 86) 23 >>> rgb2short(255, 255, 255) 231 >>> rgb2short(13, 173, 2...
powerline_shell/colortrans.py
def rgb2short(r, g, b): """ Find the closest xterm-256 approximation to the given RGB value. @param r,g,b: each is a number between 0-255 for the Red, Green, and Blue values @returns: integer between 0 and 255, compatible with xterm. >>> rgb2short(18, 52, 86) 23 >>> rgb2short(255, 255, 255) ...
def rgb2short(r, g, b): """ Find the closest xterm-256 approximation to the given RGB value. @param r,g,b: each is a number between 0-255 for the Red, Green, and Blue values @returns: integer between 0 and 255, compatible with xterm. >>> rgb2short(18, 52, 86) 23 >>> rgb2short(255, 255, 255) ...
[ "Find", "the", "closest", "xterm", "-", "256", "approximation", "to", "the", "given", "RGB", "value", "." ]
b-ryan/powerline-shell
python
https://github.com/b-ryan/powerline-shell/blob/a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc/powerline_shell/colortrans.py#L284-L312
[ "def", "rgb2short", "(", "r", ",", "g", ",", "b", ")", ":", "incs", "=", "(", "0x00", ",", "0x5f", ",", "0x87", ",", "0xaf", ",", "0xd7", ",", "0xff", ")", "# Break 6-char RGB code into 3 integer vals.", "parts", "=", "[", "r", ",", "g", ",", "b", ...
a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc
train
RepoStats.n_or_empty
Given a string name of one of the properties of this class, returns the value of the property as a string when the value is greater than 1. When it is not greater than one, returns an empty string. As an example, if you want to show an icon for new files, but you only want a number to a...
powerline_shell/utils.py
def n_or_empty(self, _key): """Given a string name of one of the properties of this class, returns the value of the property as a string when the value is greater than 1. When it is not greater than one, returns an empty string. As an example, if you want to show an icon for new files, ...
def n_or_empty(self, _key): """Given a string name of one of the properties of this class, returns the value of the property as a string when the value is greater than 1. When it is not greater than one, returns an empty string. As an example, if you want to show an icon for new files, ...
[ "Given", "a", "string", "name", "of", "one", "of", "the", "properties", "of", "this", "class", "returns", "the", "value", "of", "the", "property", "as", "a", "string", "when", "the", "value", "is", "greater", "than", "1", ".", "When", "it", "is", "not"...
b-ryan/powerline-shell
python
https://github.com/b-ryan/powerline-shell/blob/a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc/powerline_shell/utils.py#L65-L76
[ "def", "n_or_empty", "(", "self", ",", "_key", ")", ":", "return", "unicode_", "(", "self", "[", "_key", "]", ")", "if", "int", "(", "self", "[", "_key", "]", ")", ">", "1", "else", "u''" ]
a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc
train
maybe_shorten_name
If the user has asked for each directory name to be shortened, will return the name up to their specified length. Otherwise returns the full name.
powerline_shell/segments/cwd.py
def maybe_shorten_name(powerline, name): """If the user has asked for each directory name to be shortened, will return the name up to their specified length. Otherwise returns the full name.""" max_size = powerline.segment_conf("cwd", "max_dir_size") if max_size: return name[:max_size] r...
def maybe_shorten_name(powerline, name): """If the user has asked for each directory name to be shortened, will return the name up to their specified length. Otherwise returns the full name.""" max_size = powerline.segment_conf("cwd", "max_dir_size") if max_size: return name[:max_size] r...
[ "If", "the", "user", "has", "asked", "for", "each", "directory", "name", "to", "be", "shortened", "will", "return", "the", "name", "up", "to", "their", "specified", "length", ".", "Otherwise", "returns", "the", "full", "name", "." ]
b-ryan/powerline-shell
python
https://github.com/b-ryan/powerline-shell/blob/a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc/powerline_shell/segments/cwd.py#L33-L40
[ "def", "maybe_shorten_name", "(", "powerline", ",", "name", ")", ":", "max_size", "=", "powerline", ".", "segment_conf", "(", "\"cwd\"", ",", "\"max_dir_size\"", ")", "if", "max_size", ":", "return", "name", "[", ":", "max_size", "]", "return", "name" ]
a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc
train
get_fg_bg
Returns the foreground and background color to use for the given name.
powerline_shell/segments/cwd.py
def get_fg_bg(powerline, name, is_last_dir): """Returns the foreground and background color to use for the given name. """ if requires_special_home_display(powerline, name): return (powerline.theme.HOME_FG, powerline.theme.HOME_BG,) if is_last_dir: return (powerline.theme.CWD_FG, powerl...
def get_fg_bg(powerline, name, is_last_dir): """Returns the foreground and background color to use for the given name. """ if requires_special_home_display(powerline, name): return (powerline.theme.HOME_FG, powerline.theme.HOME_BG,) if is_last_dir: return (powerline.theme.CWD_FG, powerl...
[ "Returns", "the", "foreground", "and", "background", "color", "to", "use", "for", "the", "given", "name", "." ]
b-ryan/powerline-shell
python
https://github.com/b-ryan/powerline-shell/blob/a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc/powerline_shell/segments/cwd.py#L43-L52
[ "def", "get_fg_bg", "(", "powerline", ",", "name", ",", "is_last_dir", ")", ":", "if", "requires_special_home_display", "(", "powerline", ",", "name", ")", ":", "return", "(", "powerline", ".", "theme", ".", "HOME_FG", ",", "powerline", ".", "theme", ".", ...
a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc
train
get_valid_cwd
Determine and check the current working directory for validity. Typically, an directory arises when you checkout a different branch on git that doesn't have this directory. When an invalid directory is found, a warning is printed to the screen, but the directory is still returned as-is, since this is w...
powerline_shell/__init__.py
def get_valid_cwd(): """Determine and check the current working directory for validity. Typically, an directory arises when you checkout a different branch on git that doesn't have this directory. When an invalid directory is found, a warning is printed to the screen, but the directory is still returne...
def get_valid_cwd(): """Determine and check the current working directory for validity. Typically, an directory arises when you checkout a different branch on git that doesn't have this directory. When an invalid directory is found, a warning is printed to the screen, but the directory is still returne...
[ "Determine", "and", "check", "the", "current", "working", "directory", "for", "validity", "." ]
b-ryan/powerline-shell
python
https://github.com/b-ryan/powerline-shell/blob/a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc/powerline_shell/__init__.py#L30-L54
[ "def", "get_valid_cwd", "(", ")", ":", "try", ":", "cwd", "=", "_current_dir", "(", ")", "except", ":", "warn", "(", "\"Your current directory is invalid. If you open a ticket at \"", "+", "\"https://github.com/milkbikis/powerline-shell/issues/new \"", "+", "\"we would love t...
a9b8c9bb39dbfb7ec3c639e497b5a76fa6dcb8cc
train
validate_email
Brutally simple email address validation. Note unlike most email address validation * raw ip address (literal) domain parts are not allowed. * "John Doe <local_part@domain.com>" style "pretty" email addresses are processed * the local part check is extremely basic. This raises the possibility of unicode spo...
pydantic/utils.py
def validate_email(value: str) -> Tuple[str, str]: """ Brutally simple email address validation. Note unlike most email address validation * raw ip address (literal) domain parts are not allowed. * "John Doe <local_part@domain.com>" style "pretty" email addresses are processed * the local part check...
def validate_email(value: str) -> Tuple[str, str]: """ Brutally simple email address validation. Note unlike most email address validation * raw ip address (literal) domain parts are not allowed. * "John Doe <local_part@domain.com>" style "pretty" email addresses are processed * the local part check...
[ "Brutally", "simple", "email", "address", "validation", ".", "Note", "unlike", "most", "email", "address", "validation", "*", "raw", "ip", "address", "(", "literal", ")", "domain", "parts", "are", "not", "allowed", ".", "*", "John", "Doe", "<local_part@domain"...
samuelcolvin/pydantic
python
https://github.com/samuelcolvin/pydantic/blob/bff8a1789dfde2c38928cced6640887b53615aa3/pydantic/utils.py#L49-L75
[ "def", "validate_email", "(", "value", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "if", "email_validator", "is", "None", ":", "raise", "ImportError", "(", "'email-validator is not installed, run `pip install pydantic[email]`'", ")", "m", "="...
bff8a1789dfde2c38928cced6640887b53615aa3
train
make_dsn
Create a DSN from from connection settings. Stolen approximately from sqlalchemy/engine/url.py:URL.
pydantic/utils.py
def make_dsn( *, driver: str, user: str = None, password: str = None, host: str = None, port: str = None, name: str = None, query: Dict[str, Any] = None, ) -> str: """ Create a DSN from from connection settings. Stolen approximately from sqlalchemy/engine/url.py:URL. """...
def make_dsn( *, driver: str, user: str = None, password: str = None, host: str = None, port: str = None, name: str = None, query: Dict[str, Any] = None, ) -> str: """ Create a DSN from from connection settings. Stolen approximately from sqlalchemy/engine/url.py:URL. """...
[ "Create", "a", "DSN", "from", "from", "connection", "settings", "." ]
samuelcolvin/pydantic
python
https://github.com/samuelcolvin/pydantic/blob/bff8a1789dfde2c38928cced6640887b53615aa3/pydantic/utils.py#L82-L117
[ "def", "make_dsn", "(", "*", ",", "driver", ":", "str", ",", "user", ":", "str", "=", "None", ",", "password", ":", "str", "=", "None", ",", "host", ":", "str", "=", "None", ",", "port", ":", "str", "=", "None", ",", "name", ":", "str", "=", ...
bff8a1789dfde2c38928cced6640887b53615aa3