code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
attributes = [] # type: List[str] for attr in kw.keys(): attributes.append("%s=%s" % (attr, kw[attr])) return bool( ctypes.windll.ODBCCP32.SQLConfigDataSource(0, ODBC_ADD_DSN, driver, nul.join(attributes)) )
def create_user_dsn(driver: str, **kw) -> bool
(Windows only.) Create a user ODBC data source name (DSN). Args: driver: ODBC driver name kw: Driver attributes Returns: bool: was the DSN created?
7.593671
7.114895
1.067292
directory = os.path.dirname(fullfilename) return create_sys_dsn( access_driver, SERVER="", DESCRIPTION=description, DSN=dsn, DBQ=fullfilename, DefaultDir=directory )
def register_access_db(fullfilename: str, dsn: str, description: str) -> bool
(Windows only.) Registers a Microsoft Access database with ODBC. Args: fullfilename: filename of the existing database dsn: ODBC data source name to create description: description of the database Returns: bool: was the DSN created?
13.097178
10.79067
1.21375
fullfilename = os.path.abspath(filename) create_string = fullfilename + " General" # ... filename, space, sort order ("General" for English) return (create_user_dsn(access_driver, CREATE_DB3=create_string) and register_access_db(filename, dsn, description))
def create_and_register_access97_db(filename: str, dsn: str, description: str) -> bool
(Windows only.) Creates a Microsoft Access 97 database and registers it with ODBC. Args: filename: filename of the database to create dsn: ODBC data source name to create description: description of the database Returns: bool: was the DSN created?
22.106184
20.934725
1.055958
fullfilename = os.path.abspath(filename) create_string = fullfilename + " General" # ... filename, space, sort order ("General" for English) return (create_user_dsn(access_driver, CREATE_DB4=create_string) and register_access_db(filename, dsn, description))
def create_and_register_access2000_db(filename: str, dsn: str, description: str) -> bool
(Windows only.) Creates a Microsoft Access 2000 database and registers it with ODBC. Args: filename: filename of the database to create dsn: ODBC data source name to create description: description of the database Returns: bool: was the DSN created?
23.703257
22.337788
1.061128
fullfilename = os.path.abspath(filename) create_string = fullfilename + " General" # ... filename, space, sort order ("General" for English) return (create_user_dsn(access_driver, CREATE_DB=create_string) and register_access_db(filename, dsn, description))
def create_and_register_access_db(filename: str, dsn: str, description: str) -> bool
(Windows only.) Creates a Microsoft Access database and registers it with ODBC. Args: filename: filename of the database to create dsn: ODBC data source name to create description: description of the database Returns: bool: was the DSN created?
20.42498
19.174337
1.065225
return \ len(self._finalized_dependencies) >= self.dependency_count \ and len(self._enqueued_dependencies) >= self.dependency_count
def _finalized(self)
Return true if all dependencies have informed this node that they'll be sending no more data (by calling _finalize()), and that they have sent at least one batch of data (by calling enqueue())
7.165349
4.789055
1.496192
try: f = self.func.__call__.__code__ except AttributeError: f = self.func.__code__ h = md5() h.update(f.co_code) h.update(str(f.co_names).encode()) try: closure = self.func.__closure__ except AttributeError: ...
def version(self)
Compute the version identifier for this functional node using the func code and local names. Optionally, also allow closed-over variable values to affect the version number when closure_fingerprint is specified
2.873348
2.48265
1.157372
table = ormclass.__table__ # type: Table log.info("Creating table {} on engine {}{}", table.name, get_safe_url_from_engine(engine), " (omitting constraints)" if without_constraints else "") # https://stackoverflow.com/questions/19175311/how-to-create-only-one-tab...
def create_table_from_orm_class(engine: Engine, ormclass: DeclarativeMeta, without_constraints: bool = False) -> None
From an SQLAlchemy ORM class, creates the database table via the specified engine, using a ``CREATE TABLE`` SQL (DDL) statement. Args: engine: SQLAlchemy :class:`Engine` object ormclass: SQLAlchemy ORM class without_constraints: don't add foreign key constraints
3.777117
3.867324
0.976675
self.counties = CachedCountyLookup(precision=GEOHASH_PRECISION) self.extractor = WordExtractor()
def mapper_init(self)
Download counties geojson from S3 and build spatial index and cache
35.004108
21.284161
1.644608
logging.info("Starting GeoJSON MongoDB loading process.") mongo = dict(uri=self.mongo, db=self.db, collection=self.collection) self.load(self.source, **mongo) logging.info("Finished loading {0} into MongoDB".format(self.source))
def run(self)
Top level runner to load State and County GeoJSON files into Mongo DB
6.357102
5.231713
1.215109
logging.info("Mongo URI: {0}".format(uri)) logging.info("Mongo DB: {0}".format(db)) logging.info("Mongo Collection: {0}".format(collection)) logging.info("Geojson File to be loaded: {0}".format(geojson)) mongo = MongoGeo(db=db, collection=collection, uri=uri) Geo...
def load(self, geojson, uri=None, db=None, collection=None)
Load geojson file into mongodb instance
3.065371
2.911925
1.052696
if all([VERSION, UPDATED, any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]), ]): return FORMAT_STRING.format(**{"version": VERSION, "updated": UPDATED, }) elif VERSION: return VERSION elif UPDATED: return localize(UPDATED) if any([isinstance(UPDATED, date), i...
def get_version()
Return formatted version string. Returns: str: string with project version or empty string.
5.881941
5.917529
0.993986
# log.critical("process_file: start") try: reader = CorruptedOpenXmlReader(filename, show_zip_output=show_zip_output) if reader.file_type in filetypes: log.info("Found {}: {}", reader.description, filename) if move_to: ...
def process_file(filename: str, filetypes: List[str], move_to: str, delete_if_not_specified_file_type: bool, show_zip_output: bool) -> None
Deals with an OpenXML, including if it is potentially corrupted. Args: filename: filename to process filetypes: list of filetypes that we care about, e.g. ``['docx', 'pptx', 'xlsx']``. move_to: move matching files to this directory delete_if_not_specified_file_type: if `...
4.05932
3.835689
1.058303
if not self.src_filename: return if alter_if_clash: counter = 0 while os.path.exists(destination_filename): root, ext = os.path.splitext(destination_filename) destination_filename = "{r}_{c}{e}".format( r=ro...
def move_to(self, destination_filename: str, alter_if_clash: bool = True) -> None
Move the file to which this class refers to a new location. The function will not overwrite existing files (but offers the option to rename files slightly to avoid a clash). Args: destination_filename: filename to move to alter_if_clash: if ``True`` (the default), append...
2.450261
2.47096
0.991623
if meta.get('layout', self.default_template) in self.inc_layout: if self.prev_mtime.get(fpath, 0) == os.path.getmtime(fpath): return False else: return True return True
def should_build(self, fpath, meta)
Checks if the file should be built or not Only skips layouts which are tagged as INCREMENTAL Rebuilds only those files with mtime changed since previous build
4.66012
3.38769
1.375604
servers = yield self.getClusterServers() queues = {} for sname in servers: qs = yield self.get('rhumba.server.%s.queues' % sname) uuid = yield self.get('rhumba.server.%s.uuid' % sname) qs = json.loads(qs) for q in qs: ...
def clusterQueues(self)
Return a dict of queues in cluster and servers running them
3.57836
3.348568
1.068624
servers = yield self.getClusterServers() d = { 'workers': {}, 'crons': {}, 'queues': {} } now = time.time() reverse_map = {} for sname in servers: last = yield self.get('rhumba.server.%s.heartbeat' % sname) ...
def clusterStatus(self)
Returns a dict of cluster nodes and their status information
2.887964
2.900625
0.995635
if fields: query_params[EsConst.FIELDS] = fields path = self._es_parser.make_path(index, doc_type, id) result = yield self._perform_request(HttpMethod.GET, path, params=query_params) returnValue(result)
def get(self, index, id, fields=None, doc_type=EsConst.ALL_VALUES, **query_params)
Retrieve specific record by id `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name to query :param id: the id of the record :param fields: the fields you what to fetch from the record (str separated by comma's) :param doc...
4.235397
5.29837
0.799377
self._es_parser.is_not_empty_params(index, doc_type, id) path = self._es_parser.make_path(index, doc_type, id) result = yield self._perform_request(HttpMethod.HEAD, path, params=query_params) ...
def exists(self, index, doc_type, id, **query_params)
Check if the doc exist in the elastic search `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name :param doc_type: the document type :param id: the id of the doc type :arg parent: The ID of the parent document :arg...
4.84973
5.744685
0.844212
self._es_parser.is_not_empty_params(index, doc_type, id) path = self._es_parser.make_path(index, doc_type, id, EsMethods.SOURCE) result = yield self._perform_request(HttpMethod.GET, path, params=qu...
def get_source(self, index, doc_type, id, **query_params)
Get the _source of the document `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name :param doc_type: the document type :param id: the id of the doc type :arg _source: True or false to return the _source field or not, or a...
5.664724
6.501778
0.871258
self._es_parser.is_not_empty_params(body) path = self._es_parser.make_path(index, doc_type, EsMethods.MULTIPLE_GET) result = yield self._perform_request(HttpMethod.GET, ...
def mget(self, body, index=None, doc_type=None, **query_params)
Get multiple document from the same index and doc_type (optionally) by ids `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html>` :param body: list of docs with or without the index and type parameters or list of ids :param index: the name of the index ...
5.937329
8.082048
0.734632
self._es_parser.is_not_empty_params(index, doc_type, id) path = self._es_parser.make_path(index, doc_type, id, EsMethods.UPDATE) result = yield self._perform_request(HttpMethod.POST, path, body=body, params=query_params) returnValue(result)
def update(self, index, doc_type, id, body=None, **query_params)
Update a document with the body param or list of ids `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html>`_ :param index: the name of the index :param doc_type: the document type :param id: the id of the doc type :param body: the data to update in t...
4.832465
5.846865
0.826505
path = self._es_parser.make_path(index, doc_type, EsMethods.SEARCH) result = yield self._perform_request(HttpMethod.POST, path, body=body, params=query_params) returnValue(result)
def search(self, index=None, doc_type=None, body=None, **query_params)
Make a search query on the elastic search `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html>`_ :param index: the index name to query :param doc_type: he doc type to search in :param body: the query :param query_params: params :arg _sourc...
5.836515
7.761941
0.75194
self._es_parser.is_not_empty_params(index, doc_type, id) path = self._es_parser.make_path(index, doc_type, id, EsMethods.EXPLAIN) result = yield self._perform_req...
def explain(self, index, doc_type, id, body=None, **query_params)
The explain api computes a score explanation for a query and a specific document. This can give useful feedback whether a document matches or didn't match a specific query. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html>`_ :param index: The name of t...
5.302802
7.306365
0.725778
path = self._es_parser.make_path(index, doc_type, id) result = yield self._perform_request(HttpMethod.DELETE, path, params=query_params) returnValue(result)
def delete(self, index, doc_type, id, **query_params)
Delete specific record by id `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html>`_ :param index: the index name to delete from :param doc_type: the doc type to delete from :param id: the id of the record :param query_params: params :return:
5.34296
5.936491
0.90002
self._es_parser.is_not_empty_params(index, doc_type, body) method = HttpMethod.POST if id in NULL_VALUES else HttpMethod.PUT path = self._es_parser.make_path(index, doc_type, id) result = yield self._perform_request(method, path, body, params=query_params) returnValue(r...
def index(self, index, doc_type, body, id=None, **query_params)
Adds or updates a typed JSON document in a specific index, making it searchable. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html>`_ :param index: The name of the index :param doc_type: The type of the document :param body: The document :param id...
4.948554
5.806317
0.852271
query_params['op_type'] = 'create' result = yield self.index(index, doc_type, body, id=id, params=query_params) returnValue(result)
def create(self, index, doc_type, body, id=None, **query_params)
Adds a typed JSON document in a specific index, making it searchable. Behind the scenes this method calls index(..., op_type='create') `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html>`_ :param index: The name of the index :param doc_type: The type of the...
3.382466
5.589678
0.605127
if scroll_id in NULL_VALUES and body in NULL_VALUES: raise ValueError("You need to supply scroll_id or body.") elif scroll_id and not body: body = scroll_id elif scroll_id: query_params[EsConst.SCROLL_ID] = scroll_id path = self._es_parser.ma...
def clear_scroll(self, scroll_id=None, body=None, **query_params)
Clear the scroll request created by specifying the scroll parameter to search. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_ :param scroll_id: A comma-separated list of scroll IDs to clear :param body: A comma-separated list of scroll IDs ...
4.725693
5.36546
0.880762
if not preserve_order: kwargs['search_type'] = 'scan' # initial search results = yield self.search(index=index, doc_type=doc_type, body=query, size=size, ...
def scan(self, index, doc_type, query=None, scroll='5m', preserve_order=False, size=10, **kwargs)
Simple abstraction on top of the :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that yields all hits as returned by underlining scroll requests. By default scan does not return results in any pre-determined order. To have a standard order in the returned documents (...
3.912634
4.730445
0.827118
if doc_type and not index: index = EsConst.ALL_VALUES path = self._es_parser.make_path(index, doc_type, EsMethods.COUNT) result = yield self._perform_request(HttpMethod.GET, path, body, params=query_params) returnValue(result)
def count(self, index=None, doc_type=None, body=None, **query_params)
Execute a query and get the number of matches for that query. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html>`_ :param index: A comma-separated list of indices to restrict the results :param doc_type: A comma-separated list of types to restrict the results ...
6.484197
12.675113
0.511569
self._es_parser.is_not_empty_params(body) path = self._es_parser.make_path(index, doc_type, EsMethods.BULK) result = yield self._perform_request(HttpMethod.POST, path, self._bulk_body(body), ...
def bulk(self, body, index=None, doc_type=None, **query_params)
Perform many index/delete operations in a single API call. See the :func:`~elasticsearch.helpers.bulk` helper function for a more friendly API. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html>`_ :param body: The operation definition and data (action-data p...
5.654485
7.200471
0.785294
self._es_parser.is_not_empty_params(body) path = self._es_parser.make_path(index, doc_type, EsMethods.MULTIPLE_SEARCH) result = yield self._perform_request(HttpMethod.GET, ...
def msearch(self, body, index=None, doc_type=None, **query_params)
Execute several search requests within the same API. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html>`_ :arg body: The request definitions (metadata-search request definition pairs), separated by newlines :arg index: A comma-separated list of...
6.645375
7.597407
0.87469
def validate_client(client): host, port = client.addr parsed_url = urlparse(self._hostname) return host == parsed_url.hostname and port == parsed_url.port # read https://github.com/twisted/treq/issues/86 # to understand the following......
def close(self)
close all http connections. returns a deferred that fires once they're all closed.
6.401383
5.610517
1.140961
l1 = len(coords) coords = coords[~N.isnan(coords).any(axis=1)] # remove NaN values l2 = len(coords) if not silent: msg = "{0} coordinates".format(l2) if l2 < l1: msg += " ({0} removed as invalid)".format(l1-l2) print(msg) return coords
def clean_coordinates(coords, silent=False)
Removes invalid coordinates (this is generally caused by importing coordinates outside of the DEM)
3.029585
2.895627
1.046262
def axis_data(axis): x = mask.sum(axis) trimmed_front = N.trim_zeros(x,"f") offset = len(x)-len(trimmed_front) size = len(N.trim_zeros(trimmed_front,"b")) return offset,size xo,xs = axis_data(0) yo,ys = axis_data(1) array = mask[yo:yo+ys,xo:xo+xs] ...
def offset_mask(mask)
Returns a mask shrunk to the 'minimum bounding rectangle' of the nonzero portion of the previous mask, and its offset from the original. Useful to find the smallest rectangular section of the image that can be extracted to include the entire geometry. Conforms to the y-first expectations...
5.338655
5.055807
1.055945
kwargs.setdefault('masked', True) coords_in = coords_array(geom) # Transform geometry into pixels f = lambda *x: ~dem.transform * x px = transform(f,geom) # Subdivide geometry segments if option is given interval = kwargs.pop('subdivide', 1) if interval is not None: px = ...
def extract_line(geom, dem, **kwargs)
Extract a linear feature from a `rasterio` geospatial dataset.
4.77767
4.824907
0.99021
d = defer.Deferred() p = ProcessProtocol(d, timeout) reactor.spawnProcess(p, executable, (executable,)+tuple(args), env, path) return d
def fork(executable, args=(), env={}, path=None, timeout=3600)
fork Provides a deferred wrapper function with a timeout function :param executable: Executable :type executable: str. :param args: Tupple of arguments :type args: tupple. :param env: Environment dictionary :type env: dict. :param timeout: Kill the child process if timeout is exceeded ...
3.306845
3.753181
0.881078
if dialect == SqlaDialectName.MYSQL: return mysql_grammar elif dialect == SqlaDialectName.MSSQL: return mssql_grammar else: raise AssertionError("Invalid SQL dialect: {}".format(repr(dialect)))
def make_grammar(dialect: str) -> SqlGrammar
Factory to make an :class:`.SqlGrammar` from the name of an SQL dialect, where the name is one of the members of :class:`.SqlaDialectName`.
4.299055
3.433901
1.251945
if number is None: return default if number == float("inf"): return u"∞" if number == float("-inf"): s = u"-∞" else: s = u"{:.{precision}f}".format(number, precision=dp) if en_dash_for_minus: s = s.replace("-", u"–") # hyphen becomes en dash for minus si...
def number_to_dp(number: Optional[float], dp: int, default: Optional[str] = "", en_dash_for_minus: bool = True) -> str
Format number to ``dp`` decimal places, optionally using a UTF-8 en dash for minus signs.
2.665888
2.334676
1.141867
for k in form.keys(): text = "{0} = {1}".format(k, form.getvalue(k)) if to_stderr: sys.stderr.write(text) if to_logger: log.info(text)
def debug_form_contents(form: cgi.FieldStorage, to_stderr: bool = True, to_logger: bool = False) -> None
Writes the keys and values of a CGI form to ``stderr``.
2.975297
2.576378
1.154837
method = environ.get("REQUEST_METHOD", None) if not method: return False return method.upper() == "POST"
def cgi_method_is_post(environ: Dict[str, str]) -> bool
Determines if the CGI method was ``POST``, given the CGI environment.
3.166931
2.44348
1.296074
paramlist = form.getlist(key) if len(paramlist) == 0: return default return paramlist[0]
def get_cgi_parameter_str(form: cgi.FieldStorage, key: str, default: str = None) -> str
Extracts a string parameter from a CGI form. Note: ``key`` is CASE-SENSITIVE.
3.535543
2.912755
1.213814
s = get_cgi_parameter_str(form, key) if s is None or len(s) == 0: return None return s
def get_cgi_parameter_str_or_none(form: cgi.FieldStorage, key: str) -> Optional[str]
Extracts a string parameter from a CGI form, or ``None`` if the key doesn't exist or the string is zero-length.
2.598111
2.551215
1.018382
return form.getlist(key)
def get_cgi_parameter_list(form: cgi.FieldStorage, key: str) -> List[str]
Extracts a list of values, all with the same key, from a CGI form.
10.451824
7.330677
1.425765
return is_1(get_cgi_parameter_str(form, key))
def get_cgi_parameter_bool(form: cgi.FieldStorage, key: str) -> bool
Extracts a boolean parameter from a CGI form, on the assumption that ``"1"`` is ``True`` and everything else is ``False``.
10.682711
8.172881
1.307092
s = get_cgi_parameter_str(form, key) if s is None or len(s) == 0: return default return is_1(s)
def get_cgi_parameter_bool_or_default(form: cgi.FieldStorage, key: str, default: bool = None) -> Optional[bool]
Extracts a boolean parameter from a CGI form (``"1"`` = ``True``, other string = ``False``, absent/zero-length string = default value).
3.497701
3.628061
0.964069
return get_cgi_parameter_bool_or_default(form, key, default=None)
def get_cgi_parameter_bool_or_none(form: cgi.FieldStorage, key: str) -> Optional[bool]
Extracts a boolean parameter from a CGI form (``"1"`` = ``True``, other string = False, absent/zero-length string = ``None``).
3.86259
5.960202
0.648064
return get_int_or_none(get_cgi_parameter_str(form, key))
def get_cgi_parameter_int(form: cgi.FieldStorage, key: str) -> Optional[int]
Extracts an integer parameter from a CGI form, or ``None`` if the key is absent or the string value is not convertible to ``int``.
4.209484
5.666375
0.742888
return get_float_or_none(get_cgi_parameter_str(form, key))
def get_cgi_parameter_float(form: cgi.FieldStorage, key: str) -> Optional[float]
Extracts a float parameter from a CGI form, or None if the key is absent or the string value is not convertible to ``float``.
4.73452
7.824806
0.605066
try: s = get_cgi_parameter_str(form, key) if not s: # if you dateutil.parser.parse() an empty string, # you get today's date return None d = dateutil.parser.parse(s) if d.tzinfo is None: # as it will be d = d.replace(tzinfo=dateut...
def get_cgi_parameter_datetime(form: cgi.FieldStorage, key: str) -> Optional[datetime.datetime]
Extracts a date/time parameter from a CGI form. Applies the LOCAL timezone if none specified.
3.570333
3.784345
0.943448
(filename, filecontents) = get_cgi_parameter_filename_and_file(form, key) return filecontents
def get_cgi_parameter_file(form: cgi.FieldStorage, key: str) -> Optional[bytes]
Extracts a file's contents from a "file" input in a CGI form, or None if no such file was uploaded.
6.396476
5.635315
1.13507
if not (key in form): log.warning('get_cgi_parameter_file: form has no key {}', key) return None, None fileitem = form[key] # a nested FieldStorage instance; see # http://docs.python.org/2/library/cgi.html#using-the-cgi-module if isinstance(fileitem, cgi.MiniFieldStorage): ...
def get_cgi_parameter_filename_and_file(form: cgi.FieldStorage, key: str) \ -> Tuple[Optional[str], Optional[bytes]]
Extracts a file's name and contents from a "file" input in a CGI form. Returns ``(name, contents)``, or ``(None, None)`` if no such file was uploaded.
3.647424
3.697824
0.98637
s = get_cgi_parameter_str(form, key) return s is not None
def cgi_parameter_exists(form: cgi.FieldStorage, key: str) -> bool
Does a CGI form contain the key?
8.658915
5.718078
1.514305
value = os.getenv(key, default) # noinspection PyDeprecation return cgi.escape(value) if value is not None else None
def getenv_escaped(key: str, default: str = None) -> Optional[str]
Returns an environment variable's value, CGI-escaped, or ``None``.
4.820142
3.806449
1.266309
value = config.get(section, key) # noinspection PyDeprecation return cgi.escape(value) if value is not None else None
def getconfigvar_escaped(config: configparser.ConfigParser, section: str, key: str) -> Optional[str]
Returns a CGI-escaped version of the value read from an INI file using :class:`ConfigParser`, or ``None``.
4.706513
4.509237
1.043749
# http://stackoverflow.com/questions/530526/accessing-post-data-from-wsgi post_env = env.copy() if not include_query_string: post_env['QUERY_STRING'] = '' form = cgi.FieldStorage( fp=env['wsgi.input'], environ=post_env, keep_blank_values=True ) return form
def get_cgi_fieldstorage_from_wsgi_env( env: Dict[str, str], include_query_string: bool = True) -> cgi.FieldStorage
Returns a :class:`cgi.FieldStorage` object from the WSGI environment.
2.938291
2.627175
1.118422
return BASE64_PNG_URL_PREFIX + base64.b64encode(blob).decode('ascii')
def get_png_data_url(blob: Optional[bytes]) -> str
Converts a PNG blob into a local URL encapsulating the PNG.
5.054177
3.332811
1.516491
return .format( 'class="{}" '.format(extra_html_class) if extra_html_class else "", get_png_data_url(blob) )
def get_png_img_html(blob: Union[bytes, memoryview], extra_html_class: str = None) -> str
Converts a PNG blob to an HTML IMG tag with embedded data.
5.974344
4.355623
1.37164
extraheaders = extraheaders or [] if filename: extraheaders.append( ('content-disposition', 'inline; filename="{}"'.format(filename)) ) contenttype = 'application/pdf' if filename: contenttype += '; filename="{}"'.format(filename) # log.debug("type(pdf_binary...
def pdf_result(pdf_binary: bytes, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None, filename: str = None) -> WSGI_TUPLE_TYPE
Returns ``(contenttype, extraheaders, data)`` tuple for a PDF.
3.025836
2.708341
1.117229
extraheaders = extraheaders or [] if filename: extraheaders.append( ('content-disposition', 'inline; filename="{}"'.format(filename)) ) contenttype = 'application/zip' if filename: contenttype += '; filename="{}"'.format(filename) return contenttype, extrahea...
def zip_result(zip_binary: bytes, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None, filename: str = None) -> WSGI_TUPLE_TYPE
Returns ``(contenttype, extraheaders, data)`` tuple for a ZIP.
2.769696
2.445364
1.132631
extraheaders = extraheaders or [] return 'text/html; charset=utf-8', extraheaders, html.encode("utf-8")
def html_result(html: str, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None) \ -> WSGI_TUPLE_TYPE
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 HTML.
4.696755
4.107112
1.143566
extraheaders = extraheaders or [] return 'text/xml; charset=utf-8', extraheaders, xml.encode("utf-8")
def xml_result(xml: str, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None) \ -> WSGI_TUPLE_TYPE
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 XML.
4.884847
4.429291
1.102851
extraheaders = extraheaders or [] if filename: extraheaders.append( ('content-disposition', 'inline; filename="{}"'.format(filename)) ) contenttype = 'text/plain; charset=utf-8' if filename: contenttype += '; filename="{}"'.format(filename) return contenttype...
def text_result(text: str, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None, filename: str = None) -> WSGI_TUPLE_TYPE
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 text.
2.548193
2.306478
1.104798
contenttype, headers, content = contenttype_headers_content print_result_for_plain_cgi_script(contenttype, headers, content, status)
def print_result_for_plain_cgi_script_from_tuple( contenttype_headers_content: WSGI_TUPLE_TYPE, status: str = '200 OK') -> None
Writes HTTP result to stdout. Args: contenttype_headers_content: the tuple ``(contenttype, extraheaders, data)`` status: HTTP status message (default ``"200 OK``)
2.986449
3.675904
0.812439
headers = [ ("Status", status), ("Content-Type", contenttype), ("Content-Length", str(len(content))), ] + headers sys.stdout.write("\n".join([h[0] + ": " + h[1] for h in headers]) + "\n\n") sys.stdout.write(content)
def print_result_for_plain_cgi_script(contenttype: str, headers: TYPE_WSGI_RESPONSE_HEADERS, content: bytes, status: str = '200 OK') -> None
Writes HTTP request result to stdout.
2.257789
2.081676
1.084601
extraheaders = extraheaders or [] (contenttype, extraheaders2, output) = handler(result) response_headers = [('Content-Type', contenttype), ('Content-Length', str(len(output)))] response_headers.extend(extraheaders) if extraheaders2 is not None: response_headers....
def wsgi_simple_responder( result: Union[str, bytes], handler: Callable[[Union[str, bytes]], WSGI_TUPLE_TYPE], start_response: TYPE_WSGI_START_RESPONSE, status: str = '200 OK', extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None) \ -> TYPE_WSGI_APP_RESULT
Simple WSGI app. Args: result: the data to be processed by ``handler`` handler: a function returning a ``(contenttype, extraheaders, data)`` tuple, e.g. ``text_result``, ``html_result`` start_response: standard WSGI ``start_response`` function status: status code (defaul...
2.575842
2.729566
0.943682
nl = "<br>" if preserve_newlines else " " if v is None: return "" if not isinstance(v, str): v = str(v) # noinspection PyDeprecation return cgi.escape(v).replace("\n", nl).replace("\\n", nl)
def webify(v: Any, preserve_newlines: bool = True) -> str
Converts a value into an HTML-safe ``str`` (formerly, in Python 2: ``unicode``). Converts value ``v`` to a string; escapes it to be safe in HTML format (escaping ampersands, replacing newlines with ``<br>``, etc.). Returns ``""`` for blank input.
3.621975
3.266845
1.108707
if x is None: return u"{}".format(x) return u"<b>{}</b>".format(x)
def bold_if_not_blank(x: Optional[str]) -> str
HTML-emboldens content, unless blank.
4.590204
3.0835
1.488634
find_url = r''' (?x)( # verbose identify URLs within text (http|ftp|gopher) # make sure we find a resource type :// # ...needs to be followed by colon-slash-slash (\w+[:.]?){2,} # at least two domain groups, e.g. (gnosis.)(cx) (/?| ...
def make_urls_hyperlinks(text: str) -> str
Adds hyperlinks to text that appears to contain URLs. See - http://stackoverflow.com/questions/1071191 - ... except that double-replaces everything; e.g. try with ``text = "me@somewhere.com me@somewhere.com"`` - http://stackp.online.fr/?p=19
8.116819
8.202215
0.989589
html = u"<table>\n" # Header row html += u"<tr>" for x in descriptions: if x is None: x = u"" html += u"<th>{}</th>".format(webify(x)) html += u"</tr>\n" # Data rows for row in rows: html += u"<tr>" for x in row: if x is None: ...
def html_table_from_query(rows: Iterable[Iterable[Optional[str]]], descriptions: Iterable[Optional[str]]) -> str
Converts rows from an SQL query result to an HTML table. Suitable for processing output from the defunct function ``rnc_db.fetchall_with_fieldnames(sql)``.
2.054007
1.974319
1.040362
assert "\n" not in heading assert len(underline_char) == 1 return heading + "\n" + (underline_char * len(heading))
def rst_underline(heading: str, underline_char: str) -> str
Underlines a heading for RST files. Args: heading: text to underline underline_char: character to use Returns: underlined heading, over two lines (without a final terminating newline)
3.840256
3.778007
1.016477
# Check we're allowed if not overwrite and exists(filename): fail("File exists, not overwriting: {!r}".format(filename)) # Make the directory, if necessary directory = dirname(filename) if not mock: mkdir_p(directory) # Write the file log.info("Writing to {!r}", filena...
def write_if_allowed(filename: str, content: str, overwrite: bool = False, mock: bool = False) -> None
Writes the contents to a file, if permitted. Args: filename: filename to write content: contents to write overwrite: permit overwrites? mock: pretend to write, but don't Raises: RuntimeError: if file exists but overwriting not permitted
3.7957
3.74398
1.013814
index_dir = dirname(abspath(expanduser(index_filename))) return relpath(self.target_rst_filename, start=index_dir)
def rst_filename_rel_autodoc_index(self, index_filename: str) -> str
Returns the filename of the target RST file, relative to a specified index file. Used to make the index refer to the RST.
6.414522
4.224816
1.518296
if not self.is_python: return "" filepath = self.source_filename_rel_python_root dirs_and_base = splitext(filepath)[0] dir_and_file_parts = dirs_and_base.split(sep) return ".".join(dir_and_file_parts)
def python_module_name(self) -> str
Returns the name of the Python module that this instance refers to, in dotted Python module notation, or a blank string if it doesn't.
6.164684
5.498399
1.121178
extension = splitext(self.source_filename)[1] if extension in self.pygments_language_override: return self.pygments_language_override[extension] try: lexer = get_lexer_for_filename(self.source_filename) # type: Lexer return lexer.name except ...
def pygments_language(self) -> str
Returns the code type annotation for Pygments; e.g. ``python`` for Python, ``cpp`` for C++, etc.
4.130415
3.769535
1.095736
spacer = " " # Choose our final method if method is None: method = self.method is_python = self.is_python if method == AutodocMethod.BEST: if is_python: method = AutodocMethod.AUTOMODULE else: method ...
def rst_content(self, prefix: str = "", suffix: str = "", heading_underline_char: str = "=", method: AutodocMethod = None) -> str
Returns the text contents of an RST file that will automatically document our source file. Args: prefix: prefix, e.g. RST copyright comment suffix: suffix, after the part we're creating heading_underline_char: RST character to use to underline the hea...
4.296732
4.222467
1.017588
content = self.rst_content( prefix=prefix, suffix=suffix, heading_underline_char=heading_underline_char, method=method ) write_if_allowed(self.target_rst_filename, content, overwrite=overwrite, mock=mock)
def write_rst(self, prefix: str = "", suffix: str = "", heading_underline_char: str = "=", method: AutodocMethod = None, overwrite: bool = False, mock: bool = False) -> None
Writes the RST file to our destination RST filename, making any necessary directories. Args: prefix: as for :func:`rst_content` suffix: as for :func:`rst_content` heading_underline_char: as for :func:`rst_content` method: as for :func:`rst_content` ...
3.516391
3.675265
0.956772
if not source_filenames_or_globs: return if method is None: # Use the default method = self.method if recursive is None: recursive = self.recursive if source_rst_title_style_python is None: source_rst_title_style_pytho...
def add_source_files( self, source_filenames_or_globs: Union[str, List[str]], method: AutodocMethod = None, recursive: bool = None, source_rst_title_style_python: bool = None, pygments_language_override: Dict[str, str] = None) -> None
Adds source files to the index. Args: source_filenames_or_globs: string containing a filename or a glob, describing the file(s) to be added, or a list of such strings method: optional method to override ``self.method`` recursive: use :func:`gl...
2.127774
2.103246
1.011662
if isinstance(source_filenames_or_globs, str): source_filenames_or_globs = [source_filenames_or_globs] final_filenames = [] # type: List[str] for sfg in source_filenames_or_globs: sfg_expanded = expanduser(sfg) log.debug("Looking for: {!r}", sfg_expa...
def get_sorted_source_files( self, source_filenames_or_globs: Union[str, List[str]], recursive: bool = True) -> List[str]
Returns a sorted list of filenames to process, from a filename, a glob string, or a list of filenames/globs. Args: source_filenames_or_globs: filename/glob, or list of them recursive: use :func:`glob.glob` in recursive mode? Returns: sorted list of files to ...
2.16813
2.362106
0.91788
# Quick check on basename-only matching if fnmatch(filename, globtext): log.debug("{!r} matches {!r}", filename, globtext) return True bname = basename(filename) if fnmatch(bname, globtext): log.debug("{!r} matches {!r}", bname, globtext) ...
def filename_matches_glob(filename: str, globtext: str) -> bool
The ``glob.glob`` function doesn't do exclusion very well. We don't want to have to specify root directories for exclusion patterns. We don't want to have to trawl a massive set of files to find exclusion files. So let's implement a glob match. Args: filename: filename ...
5.06116
5.650172
0.895753
for skip_glob in self.skip_globs: if self.filename_matches_glob(filename, skip_glob): return True return False
def should_exclude(self, filename) -> bool
Should we exclude this file from consideration?
4.225585
3.112968
1.357413
highest_code_to_target = relative_filename_within_dir( source_filename, self.highest_code_dir) bname = basename(source_filename) result = join(self.autodoc_rst_root_dir, dirname(highest_code_to_target), bname + EXT_RST) log...
def specific_file_rst_filename(self, source_filename: str) -> str
Gets the RST filename corresponding to a source filename. See the help for the constructor for more details. Args: source_filename: source filename within current project Returns: RST filename Note in particular: the way we structure the directories means that ...
6.462955
5.997196
1.077663
for f in self.files_to_index: if isinstance(f, FileToAutodocument): f.write_rst( prefix=self.rst_prefix, suffix=self.rst_suffix, heading_underline_char=self.source_rst_heading_underline_char, # noqa ...
def write_index_and_rst_files(self, overwrite: bool = False, mock: bool = False) -> None
Writes both the individual RST files and the index. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't
3.882739
3.860357
1.005798
return relpath(self.index_filename, start=dirname(other))
def index_filename_rel_other_index(self, other: str) -> str
Returns the filename of this index, relative to the director of another index. (For inserting a reference to this index into ``other``.) Args: other: the other index Returns: relative filename of our index
12.139791
15.836255
0.766582
# Build the toctree command index_filename = self.index_filename spacer = " " toctree_lines = [ ".. toctree::", spacer + ":maxdepth: {}".format(self.toctree_maxdepth), "" ] for f in self.files_to_index: if isins...
def index_content(self) -> str
Returns the contents of the index RST file.
4.640337
4.416213
1.05075
write_if_allowed(self.index_filename, self.index_content(), overwrite=overwrite, mock=mock)
def write_index(self, overwrite: bool = False, mock: bool = False) -> None
Writes the index file, if permitted. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't
8.772441
11.017752
0.79621
hosts = EsParser._normalize_hosts(hosts) host = hosts[0] host_name = host[HostParsing.HOST] host_port = host[HostParsing.PORT] auth = None if HostParsing.HTTP_AUTH in host: http_auth = host[HostParsing.HTTP_AUTH] user_pass = http_auth.sp...
def parse_host(hosts)
Parsing the hosts parameter, * currently support only one host :param hosts: the hosts json to parse :return: the full host and the authentication if exists
2.733449
2.723817
1.003536
if host[HostParsing.HOST] \ and EsParser._is_secure_connection_type(host): host[HostParsing.PORT] = EsParser.SSL_DEFAULT_PORT host[HostParsing.USE_SSL] = True parsed_url = urlparse(EsParser._fix_host_prefix(host[HostParsing.HOST])) host[Ho...
def _update_ssl_params(host)
Update the host ssl params (port or scheme) if needed. :param host: :return:
4.32493
4.52753
0.955251
host_str = EsParser._fix_host_prefix(host_str) parsed_url = urlparse(host_str) host = {HostParsing.HOST: parsed_url.hostname} if parsed_url.port: host[HostParsing.PORT] = parsed_url.port if parsed_url.scheme == HostParsing.HTTPS: host[HostParsing....
def _parse_string_host(host_str)
Parse host string into a dictionary host :param host_str: :return:
2.163249
2.221829
0.973634
queued_params = [quote(c.encode('utf-8'), '') for c in sub_paths if c not in NULL_VALUES] queued_params.insert(0, '') return '/'.join(queued_params)
def make_path(*sub_paths)
Create a path from a list of sub paths. :param sub_paths: a list of sub paths :return:
7.119799
7.351003
0.968548
url = hostname + path if params: url = url + '?' + urlencode(params) if not url.startswith(('http:', 'https:')): url = "http://" + url return url.encode('utf-8')
def prepare_url(hostname, path, params=None)
Prepare Elasticsearch request url. :param hostname: host name :param path: request path :param params: optional url params :return:
3.010411
3.644023
0.826123
fig = plt.figure() ax = plt.axes(xlim=(0, 10), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) x = np.linspace(0, 10, 1000) def init(): line.set_data([], []) return line, def animate(i): y = np.cos(i * 0.02 * np.pi) * np.sin(x - i * 0.02 * np.pi) line.set_data...
def basic_animation(frames=100, interval=30)
Plot a basic sine wave with oscillating amplitude
1.702535
1.640471
1.037833
from scipy import integrate from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import cnames def lorentz_deriv(coords, t0, sigma=10., beta=8./3, rho=28.0): x, y, z = coords return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z] # Choose random start...
def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30)
Plot a 3D visualization of the dynamics of the Lorenz system
2.208469
2.176923
1.014491
return INCLUDED_FRAMES.format(Nframes=len(frame_list), frame_dir=os.path.dirname(frame_list[0]), frame_format=frame_format)
def _included_frames(frame_list, frame_format)
frame_list should be a list of filenames
4.227489
4.002048
1.056331
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n' embedded = "\n" for i, frame_data in enumerate(frame_list): embedded += template.format(i, frame_format, frame_data.replace('\n', '\\\n')) return embedded
def _embedded_frames(frame_list, frame_format)
frame_list should be a list of base64-encoded png files
3.827554
3.36173
1.138567
data, mjd = magnitude, time data_len = len(mjd) error_mean = np.mean(error) error_tolerance = error_limit * (error_mean or 1) data_mean = np.mean(data) data_std = np.std(data) mjd_out, data_out, error_out = [], [], [] for i in range(data_len): is_not_noise = ( ...
def remove_noise(time, magnitude, error, error_limit=3, std_limit=5)
Points within 'std_limit' standard deviations from the mean and with errors greater than 'error_limit' times the error mean are considered as noise and thus are eliminated.
2.065395
2.017805
1.023585
error = np.zeros(time.shape) if error is None else error error2 = np.zeros(time2.shape) if error2 is None else error2 # this asume that the first series is the short one sserie = pd.DataFrame({"mag": magnitude, "error": error}, index=time) lserie = pd.DataFrame({"mag": magnitude2, "error": er...
def align(time, time2, magnitude, magnitude2, error, error2)
Synchronizes the light-curves in the two different bands. Returns ------- aligned_time aligned_magnitude aligned_magnitude2 aligned_error aligned_error2
2.533731
2.59343
0.976981
with bz2.BZ2File(CATALOG_PATH) as bz2fp, warnings.catch_warnings(): warnings.simplefilter("ignore") df = pd.read_table(bz2fp, skiprows=6) df.rename(columns={"# ID": "ID"}, inplace=True) return df
def load_OGLE3_catalog()
Return the full list of variables stars of OGLE-3 as a DataFrame
3.548986
3.521173
1.007899
sorted_ext, features_from_sorted = [], set() pending = [(e, 0) for e in exts] retry = len(exts) * 100 if retry is None else retry while pending: ext, cnt = pending.pop(0) if not isinstance(ext, Extractor) and not issubclass(ext, Extractor): msg = "Only Extractor instanc...
def sort_by_dependencies(exts, retry=None)
Calculate the Feature Extractor Resolution Order.
3.392977
3.19069
1.063399
expy = exp(-wk2) effm = 2.0*(nout)/ofac sig = effm*expy ind = (sig > 0.01).nonzero() sig[ind] = 1.0-(1.0-expy[ind])**effm return sig
def getSignificance(wk1, wk2, nout, ofac)
returns the peak false alarm probabilities Hence the lower is the probability and the more significant is the peak
6.508381
6.509693
0.999798