text
stringlengths
81
112k
Compile digest auth response If the qop directive's value is "auth" or "auth-int" , then compute the response as follows: RESPONSE = MD5(HA1:nonce:nonceCount:clienNonce:qop:HA2) Else if the qop directive is unspecified, then compute the response as follows: RESPONSE = MD5(HA1:nonce:HA2) Argu...
Check user authentication using HTTP Digest auth def check_digest_auth(user, passwd): """Check user authentication using HTTP Digest auth""" if request.headers.get('Authorization'): credentials = parse_authorization_header(request.headers.get('Authorization')) if not credentials: r...
Return a tuple describing the byte range requested in a GET request If the range is open ended on the left or right side, then a value of None will be set. RFC7233: http://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7233.html#header.range Examples: Range : bytes=1024- Range : bytes=10-20 ...
Break apart an HTTP header string that is potentially a quoted, comma separated list as used in entity headers in RFC2616. def parse_multi_value_header(header_str): """Break apart an HTTP header string that is potentially a quoted, comma separated list as used in entity headers in RFC2616.""" parsed_parts = []...
302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/html responses: 302: description: A redirection. def redirect_n_times(n): """302 Redirects n times. --- tags: - Redirects para...
302/3XX Redirects to the given URL. --- tags: - Redirects produces: - text/html get: parameters: - in: query name: url type: string required: true - in: query name: status_code type: int post: consumes: ...
Relatively 302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/html responses: 302: description: A redirection. def relative_redirect_n_times(n): """Relatively 302 Redirects n times. --- t...
Absolutely 302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/html responses: 302: description: A redirection. def absolute_redirect_n_times(n): """Absolutely 302 Redirects n times. --- t...
Stream n JSON responses --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/json responses: 200: description: Streamed JSON responses. def stream_n_messages(n): """Stream n JSON responses --- tags: ...
Return status code or random status code if more than one are given --- tags: - Status codes parameters: - in: path name: codes produces: - text/plain responses: 100: description: Informational responses 200: description: Success 300: ...
Returns a set of response headers from the query string. --- tags: - Response inspection parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: type: string styl...
Returns cookie data. --- tags: - Cookies produces: - application/json responses: 200: description: Set cookies. def view_cookies(hide_env=True): """Returns cookie data. --- tags: - Cookies produces: - application/json responses: 200: ...
Sets a cookie and redirects to cookie list. --- tags: - Cookies parameters: - in: path name: name type: string - in: path name: value type: string produces: - text/plain responses: 200: description: Set cookies and redirects to co...
Sets cookie(s) as provided by the query string and redirects to cookie list. --- tags: - Cookies parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: type: string ...
Deletes cookie(s) as provided by the query string and redirects to cookie list. --- tags: - Cookies parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: type: string ...
Prompts the user for authorization using HTTP Basic Auth. --- tags: - Auth parameters: - in: path name: user type: string - in: path name: passwd type: string produces: - application/json responses: 200: description: Sucessful aut...
Prompts the user for authorization using HTTP Basic Auth. --- tags: - Auth parameters: - in: path name: user type: string - in: path name: passwd type: string produces: - application/json responses: 200: description: Sucessful aut...
Prompts the user for authorization using bearer authentication. --- tags: - Auth parameters: - in: header name: Authorization schema: type: string produces: - application/json responses: 200: description: Sucessful authentication. 401: ...
Prompts the user for authorization using Digest Auth + Algorithm. --- tags: - Auth parameters: - in: path name: qop type: string description: auth or auth-int - in: path name: user type: string - in: path name: passwd type: stri...
Prompts the user for authorization using Digest Auth + Algorithm. allow settings the stale_after argument. --- tags: - Auth parameters: - in: path name: qop type: string description: auth or auth-int - in: path name: user type: string - in:...
Returns a delayed response (max of 10 seconds). --- tags: - Dynamic data parameters: - in: path name: delay type: int produces: - application/json responses: 200: description: A delayed response. def delay_response(delay): """Returns a delayed res...
Drips data over a duration after an optional initial delay. --- tags: - Dynamic data parameters: - in: query name: duration type: number description: The amount of time (in seconds) over which to drip each byte default: 2 required: false - in: query ...
Returns a 304 if an If-Modified-Since header or If-None-Match is present. Returns the same as a GET otherwise. --- tags: - Response inspection parameters: - in: header name: If-Modified-Since - in: header name: If-None-Match produces: - application/json respon...
Assumes the resource has the given etag and responds to If-None-Match and If-Match headers appropriately. --- tags: - Response inspection parameters: - in: header name: If-None-Match - in: header name: If-Match produces: - application/json responses: 200...
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. def random_bytes(n): """Returns n random bytes generated wi...
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. 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: numbytes type: int produces: - application/octet-stream responses: 200: description: Bytes. def range_request(numby...
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...
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. def image(): """Returns a simple image of the type s...
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)]) def weighted_choice(choices): """Returns a value from choices chosen by weighted random selection choices should be a li...
X-Runtime Flask Response Decorator. 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
GZip Flask Response Decorator. 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', c...
Deflate Flask Response Decorator. 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...
Brotli Flask Response Decorator 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): ...
Parses the version out of libjsonnet.h 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_JSO...
Get fractal coordinates from query string, call mandelbrot to generate image. Returns: The image, wrapped in an HTML response. def handle_fractal(): """Get fractal coordinates from query string, call mandelbrot to generate image. Returns: The image, wrapped in an HTML response. """ ...
Return a copy of the config with ${-} handled. 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] ...
Create all required build artefacts, modify config to refer to them. 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...
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...
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, ...]) def word_vec(self, word, use_norm=False): ...
Get nearest words with KDTree, ranking by cosine distance 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, ret...
Turn seed into a np.random.RandomState instance. Method originally from maciejkula/glove-python, and written by @joshloyal. 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 ...
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. 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)...
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' def deaccent(te...
Recursively copy a directory ala shutils.copytree, but hardlink files instead of copying. Available on UNIX systems only. def copytree_hardlink(source, dest): """ Recursively copy a directory ala shutils.copytree, but hardlink files instead of copying. Available on UNIX systems only. """ copy2 ...
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...
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. def simple_preprocess(doc, deacc=False, min_len=2, max_len=15): """ Convert a document into a list of tokens. This lo...
Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8. 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 -> unico...
Convert a string (bytestring in `encoding` or unicode), to unicode. 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)
Check if an object is Number def is_digit(obj): ''' Check if an object is Number ''' return isinstance(obj, (numbers.Integral, numbers.Complex, numbers.Real))
return True if ch is Chinese character. full-width puncts/latins are not counted in. 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 ...
load stop words 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.ad...
segment words with jieba 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
load word2vec model 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_fi...
get word2vec data by sentence sentence is segmented string. 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: ...
Return the Levenshtein distance between two strings. Based on: http://rosettacode.org/wiki/Levenshtein_distance#Python def _levenshtein_distance(sentence1, sentence2): ''' Return the Levenshtein distance between two strings. Based on: http://rosettacode.org/wiki/Levenshtein_distance#Pyt...
使用空间距离近的词汇优化编辑距离计算 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 el...
compute similarity with distance measurement 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 ...
Nearby word 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 ...
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 def compare(s1, s2, seg=True, ignore=False, stopwords=False): ...
Add a sample to the metric. Internal-only, do not use. 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 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. def add_metric(self, labels, value, created=None, timestamp=None): """Add a metric to the metric family. ...
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. def add_metric(self, labels, count_value, sum_value, timestamp=None): """Add a metric to the metric family. ...
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. ...
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. def add_metric(self, labels, buckets, gsum_value, time...
Add a metric to the metric family. Args: labels: A list of label values value: A dict of 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 ...
Add a metric to the metric family. Args: labels: A list of label values value: A dict of string state names to booleans def add_metric(self, labels, value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value...
Create a WSGI app which serves the metrics from a registry. 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, cont...
Starts a WSGI server for prometheus metrics as a daemon thread. 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.T...
Starts an HTTP server for prometheus metrics as a daemon thread 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), CustomMetricsHa...
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. def write_to_textfile(path, registry): """Write metrics to the given path. This is intended for use with the Node exporter textfile...
Default handler that implements HTTP/HTTPS connections. Used by the push_to_gateway functions. Can be re-used by other handlers. 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 ot...
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...
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...
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...
Grouping key with instance set to the IP Address of this host. 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(...
Returns a dynamic MetricsHandler class tied to the passed registry. 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 REG...
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. def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. ...
Add a collector to the registry. 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(...
Remove a collector from the registry. 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]
Get names of timeseries the collector produces. 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: pa...
Yields metrics from the collectors in the registry. 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 collect...
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. def restricted_registry(self, names): ...
Returns the sample value, or None if not found. This is inefficient, and intended only for use in unittests. 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 la...
Do bookkeeping for when one process dies in a multi-process setup. 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_...
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. def merge(files, accumulate=True): """Merge metrics from given mmap files....
A replacement for inspect.getargspec def getargspec(f): """A replacement for inspect.getargspec""" spec = getfullargspec(f) return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
decorate(func, caller) decorates a function using a caller. 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)", eval...
decorator(caller) converts a caller function into a decorator 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(...
Append ``a`` to the list of the virtual ancestors, unless it is already included. 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...
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. def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. ...
Format a key for use in the mmap file. 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)
Initialize a value. Lock must be held by caller. 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'.for...
Yield (key, value, pos). No locking is performed. 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 ...
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(...
Remove the given labelset from the metric. 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): rai...
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 set_function(self, f): """Call the provided function to return the Gauge value. The function must return a ...
Observe the given amount. def observe(self, amount): """Observe the given amount.""" self._count.inc(1) self._sum.inc(amount)
Observe the given amount. 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
Set info metric. 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)