code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
"generate a single random sample"
Z = _unwhiten_cf(self._S_cf, self._genA())
return Z.dot(Z.T) | def _rand1(self) | generate a single random sample | 21.310167 | 20.952974 | 1.017047 |
'''Accepts a :key:, :value:, and :index: parameter and inserts
a new key, value member at the desired index.
Note: Inserting with a negative index will have the following behavior:
>>> l = [1, 2, 3, 4]
>>> l.insert(-1, 5)
>>> l
[1, 2, 3, 5, 4]
'''
... | def insert(self, key, value, index) | Accepts a :key:, :value:, and :index: parameter and inserts
a new key, value member at the desired index.
Note: Inserting with a negative index will have the following behavior:
>>> l = [1, 2, 3, 4]
>>> l.insert(-1, 5)
>>> l
[1, 2, 3, 5, 4] | 3.716151 | 1.597451 | 2.326301 |
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if len(keys) != len(self._keys):
raise ValueError('The supplied number of keys does not match.')
if set(keys) != set(self._d.keys()):
... | def reorder_keys(self, keys) | Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys. | 5.275452 | 2.650952 | 1.990022 |
self.file_path = filepath
_, self.file_type = os.path.splitext(filepath)
_, self.file_name = os.path.split(filepath)
with open(filepath) as ffile:
self.file_content = ffile.readlines()
return (self._load_funcs[self.file_type]()) | def load_file(self, filepath) | This function opens any type of a readable file and decompose
the file object into a list, for each line, of lists containing
splitted line strings using space as a spacer.
Parameters
----------
filepath : :class:`str`
The full path or a relative path to any type of ... | 3.341439 | 3.894161 | 0.858064 |
self.system = {
'elements': np.empty(
mol.GetNumAtoms(), dtype=str),
'coordinates': np.empty((mol.GetNumAtoms(), 3))
}
for atom in mol.GetAtoms():
atom_id = atom.GetIdx()
atom_sym = atom.GetSymbol()
x, y, z = mo... | def load_rdkit_mol(self, mol) | Return molecular data from :class:`rdkit.Chem.rdchem.Mol` object.
Parameters
----------
mol : :class:`rdkit.Chem.rdchem.Mol`
A molecule object from RDKit.
Returns
-------
:class:`dict`
A dictionary with ``elements`` and ``coordinates`` as keys
... | 2.163164 | 2.112353 | 1.024054 |
self.system = dict()
if self.file_content[2] != '\n':
self.system['remarks'] = self.file_content[2]
file_body = [i.split() for i in self.file_content]
elements = []
coordinates = []
atom_data = False
for line in file_body:
if len(l... | def _read_mol(self) | -V3000 | 2.516888 | 2.445155 | 1.029337 |
# We make sure that the object passed by the user is a dictionary.
if isinstance(obj, dict):
pass
else:
raise _NotADictionary(
"This function only accepts dictionaries as input")
# We check if the filepath has a json extenstion, if not we ... | def dump2json(self, obj, filepath, override=False, **kwargs) | Dump a dictionary into a JSON dictionary.
Uses the json.dump() function.
Parameters
----------
obj : :class:`dict`
A dictionary to be dumpped as JSON file.
filepath : :class:`str`
The filepath for the dumped file.
override : :class:`bool`
... | 3.202123 | 3.369762 | 0.950252 |
# First we check if the file already exists. If yes and the override
# keyword is False (default), we will raise an exception. Otherwise
# the file will be overwritten.
if override is False:
if os.path.isfile(filepath):
raise _FileAlreadyExists(
... | def dump2file(self, obj, filepath, override=False, **kwargs) | Dump a dictionary into a file. (Extensions: XYZ or PDB)
Parameters
----------
obj : :class:`dict`
A dictionary containing molecular information.
filepath : :class:`str`
The filepath for the dumped file.
override : :class:`bool`
If True, any fi... | 3.847765 | 3.725036 | 1.032947 |
'''Accepts a :value: and :index: parameter and inserts
a new key, value member at the desired index.
Note: Inserting with a negative index will have the following behavior:
>>> l = [1, 2, 3, 4]
>>> l.insert(-1, 5)
>>> l
[1, 2, 3, 5, 4]
'''
if val... | def insert(self, value, index) | Accepts a :value: and :index: parameter and inserts
a new key, value member at the desired index.
Note: Inserting with a negative index will have the following behavior:
>>> l = [1, 2, 3, 4]
>>> l.insert(-1, 5)
>>> l
[1, 2, 3, 5, 4] | 3.917241 | 1.64227 | 2.38526 |
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if len(keys) != len(self._set):
raise ValueError('The supplied number of keys does not match.')
if set(keys) != self._set:
... | def reorder_keys(self, keys) | Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys. | 5.462163 | 2.695956 | 2.026058 |
data = unjson(data)
if update is True:
obj = get_obj_by_request_data(self.session, self.table, data)
else:
obj = None
return self._add(obj, data, **kwargs) | def create(self, data, update=False, **kwargs) | Creates a new object pretreated input data.
.. code-block:: python
DBSession.sacrud(Users).create({'name': 'Vasya', 'sex': 1})
Support JSON:
.. code-block:: python
DBSession.sacrud(Users).create('{"name": "Vasya", "sex": 1}')
For adding multiple data for m2m... | 5.81399 | 7.154763 | 0.812604 |
pk = [unjson(obj) for obj in pk]
if len(pk) == 1: # like ([1,2,3,4,5], )
return get_obj(self.session, self.table, pk[0])
elif len(pk) > 1: # like (1, 2, 3, 4, 5)
return get_obj(self.session, self.table, pk)
return self.session.query(self.table) | def read(self, *pk) | Return a list of entries in the table or single
entry if there is an pk.
.. code-block:: python
# All users
DBSession.sacrud(Users).read()
# Composite primary_key
DBSession.sacrud(User2Groups).read({'user_id': 4, 'group_id': 2})
# Multiple ... | 3.299401 | 3.901341 | 0.845709 |
pk = unjson(pk)
data = unjson(data)
obj = get_obj(self.session, self.table, pk)
return self._add(obj, data, **kwargs) | def update(self, pk, data, **kwargs) | Updates the object by primary_key:
.. code-block:: python
DBSession.sacrud(Users).update(1, {'name': 'Petya'})
DBSession.sacrud(Users).update('1', {'name': 'Petya'})
DBSession.sacrud(User2Groups).update({'user_id': 4, 'group_id': 2},
... | 5.615116 | 6.847451 | 0.82003 |
pk = unjson(pk)
obj = get_obj(self.session, self.table, pk)
if self._delete(obj, **kwargs):
return {'pk': pk, 'name': obj.__repr__()} | def delete(self, pk, **kwargs) | Delete the object by primary_key:
.. code-block:: python
DBSession.sacrud(Users).delete(1)
DBSession.sacrud(Users).delete('1')
DBSession.sacrud(User2Groups).delete({'user_id': 4, 'group_id': 2})
JSON support:
.. code-block:: python
DBSession.s... | 7.001333 | 9.809457 | 0.713733 |
if isinstance(obj, sqlalchemy.orm.query.Query):
obj = obj.one()
obj = self.preprocessing(obj=obj or self.table)\
.add(self.session, data, self.table)
self.session.add(obj)
if kwargs.get('commit', self.commit) is True:
try:
self... | def _add(self, obj, data, **kwargs) | Update the object directly.
.. code-block:: python
DBSession.sacrud(Users)._add(UserObj, {'name': 'Gennady'}) | 5.014269 | 5.330666 | 0.940646 |
if isinstance(obj, sqlalchemy.orm.query.Query):
obj = obj.one()
obj = self.preprocessing(obj=obj).delete()
self.session.delete(obj)
if kwargs.get('commit', self.commit) is True:
try:
self.session.commit()
except AssertionError:... | def _delete(self, obj, **kwargs) | Delete the object directly.
.. code-block:: python
DBSession.sacrud(Users)._delete(UserObj)
If you no needed commit session
.. code-block:: python
DBSession.sacrud(Users, commit=False)._delete(UserObj) | 4.595776 | 5.226079 | 0.879393 |
log.info("Trying to authenticate user: '%s'", username)
if simplepam.authenticate(username, password):
expire = datetime.now() + timedelta(seconds=self.token_lifetime)
log.info("Token will be valid to %s", expire.strftime('%c'))
refresh_expire = -1
... | def authenticate(self, username, password, **token_context) | Performs authentication using simplepam
This function calls simplepam's authenticate function and returns
status of authentication using PAM and token object (of type
self.token_type)
:param username: username in Linux
:param password: password for username
:p... | 2.570487 | 2.469067 | 1.041076 |
log.info("Trying to refresh token...")
refresh = self.refresh_token_storage.get(token)
if refresh:
expire = datetime.now() + timedelta(seconds=self.token_lifetime)
refresh.context['refresh_salt'] = urandom(120).encode('base-64')
new_token = self.toke... | def refresh(self, token) | Refresh token | 4.048242 | 4.031579 | 1.004133 |
token = self.token_storage.get(user_token)
if token and token.validate(user_token, **validation_context):
return True
return False | def authenticated(self, user_token, **validation_context) | Checks if user is authenticated using token passed in argument
:param user_token: string representing token
:param validation_context: Token.validate optional keyword arguments | 3.933362 | 4.139985 | 0.950091 |
if self.authenticated(user_token):
token = self.token_storage.get(user_token)
groups = self.get_groups(token.username)
if group in groups:
return True
return False | def group_authenticated(self, user_token, group) | Checks if user represented by token is in group.
:param user_token: string representing token
:param group: group's name | 3.710332 | 4.206214 | 0.882107 |
groups = []
for group in grp.getgrall():
if username in group.gr_mem:
groups.append(group.gr_name)
return groups | def get_groups(self, username) | Returns list of groups in which user is.
:param username: name of Linux user | 2.522097 | 3.010518 | 0.837762 |
@functools.wraps(view)
def decorated(*args, **kwargs):
log.info("Trying to get access to protected resource: '%s'", view.__name__)
if request.method == 'POST':
token = request.form['token']
if self.development or self.authenticated(token)... | def auth_required(self, view) | Decorator which checks if user is authenticated
Decorator for Flask's view which blocks not authenticated requests
:param view: Flask's view function | 3.798235 | 3.604174 | 1.053843 |
def decorator(view):
@functools.wraps(view)
def decorated(*args, **kwargs):
log.info("Trying to get access to resource: %s protected by group: %s", view.__name__, group)
if request.method == 'POST':
token = request.form['token... | def group_required(self, group) | Decorator which checks if user is in group
Decorator for Flask's view which blocks requests from not
authenticated users or if user is not member of specified group
:param group: group's name | 3.832843 | 3.585896 | 1.068866 |
if re.match(".*py[co]$", filename):
if PYTHON3:
return re.sub(r'(.*)__pycache__/(.+)\.cpython-%s.py[co]$' % PYVER,
'\\1\\2.py',
filename)
else:
return filename[:-1]
return filename | def pyc2py(filename) | Find corresponding .py name given a .pyc or .pyo | 6.407098 | 5.553622 | 1.153679 |
global file_cache, file2file_remap, file2file_remap_lines
if filename is not None:
if filename in file_cache:
del file_cache[filename]
pass
else:
file_cache = {}
file2file_remap = {}
file2file_remap_lines = {}
pass
return | def clear_file_cache(filename=None) | Clear the file cache. If no filename is given clear it entirely.
if a filename is given, clear just that filename. | 3.297822 | 3.254135 | 1.013425 |
for fname, cache_info in file_cache.items():
for format, lines in cache_info.lines.items():
if 'plain' == format: continue
file_cache[fname].lines[format] = None
pass
pass
pass | def clear_file_format_cache() | Remove syntax-formatted lines in the cache. Use this
when you change the Pygments syntax or Token formatting
and want to redo how files may have previously been
syntax marked. | 6.084445 | 6.203959 | 0.980736 |
if isinstance(opts, dict):
use_linecache_lines = opts['use_linecache_lines']
else:
use_linecache_lines = opts
pass
if not filename:
filenames = list(file_cache.keys())
elif filename in file_cache:
filenames = [filename]
else:
return None
re... | def checkcache(filename=None, opts=False) | Discard cache entries that are out of date. If *filename* is *None*
all entries in the file cache *file_cache* are checked. If we do not
have stat information about a file it will be kept. Return a list of
invalidated filenames. None is returned if a filename was given but
not found cached. | 2.662606 | 2.462249 | 1.081372 |
global script_cache
if script not in script_cache:
update_script_cache(script, text, opts)
pass
return script | def cache_script(script, text, opts={}) | Cache script if it is not already cached. | 4.230582 | 4.007005 | 1.055797 |
filename = pyc2py(filename)
if filename in file_cache:
if reload_on_change: checkcache(filename)
pass
else:
opts['use_linecache_lines'] = True
update_cache(filename, opts)
pass
if filename in file_cache:
return file_cache[filename].path
else: retu... | def cache_file(filename, reload_on_change=False, opts=default_opts) | Cache filename if it is not already cached.
Return the expanded filename for it in the cache
or nil if we can not find the file. | 5.87249 | 6.587163 | 0.891505 |
if isinstance(file_or_script, str):
return unmap_file(file_or_script) in file_cache
else:
return is_cached_script(file_or_script)
return | def is_cached(file_or_script) | Return True if file_or_script is cached | 4.277308 | 4.087738 | 1.046375 |
filename = unmap_file(file_or_script)
filename, line_number = unmap_file_line(filename, line_number)
lines = getlines(filename, opts)
if lines and line_number >=1 and line_number <= maxline(filename):
line = lines[line_number-1]
if get_option('strip_nl', opts):
return li... | def getline(file_or_script, line_number, opts=default_opts) | Get line *line_number* from file named *file_or_script*. Return None if
there was a problem or it is not found.
Example:
lines = pyficache.getline("/tmp/myfile.py") | 3.794845 | 4.558892 | 0.832405 |
if get_option('reload_on_change', opts): checkcache(filename)
fmt = get_option('output', opts)
highlight_opts = {'bg': fmt}
cs = opts.get('style')
# Colorstyle of Terminal255Formatter takes precidence over
# light/dark colorthemes of TerminalFormatter
if cs:
highlight_opts['sty... | def getlines(filename, opts=default_opts) | Read lines of *filename* and cache the results. However, if
*filename* was previously cached use the results from the
cache. Return *None* if we can not get lines | 8.37059 | 8.765151 | 0.954985 |
filename = unmap_file(filename)
if filename not in file_cache:
return None
return file_cache[filename].path | def path(filename) | Return full filename path for filename | 7.648804 | 7.553278 | 1.012647 |
from_path = pyc2py(from_path)
cache_file(to_path)
remap_entry = file2file_remap_lines.get(to_path)
if remap_entry:
new_list = list(remap_entry.from_to_pairs) + list(line_map_list)
else:
new_list = line_map_list
# FIXME: look for duplicates ?
file2file_remap_lines[to_path... | def remap_file_lines(from_path, to_path, line_map_list) | Adds line_map list to the list of association of from_file to
to to_file | 4.755587 | 4.881359 | 0.974234 |
global file2file_remap
if filename in file2file_remap:
retval = file2file_remap[filename]
del file2file_remap[filename]
return retval
return None | def remove_remap_file(filename) | Remove any mapping for *filename* and return that if it exists | 3.20563 | 2.994938 | 1.070349 |
filename = unmap_file(filename)
if filename not in file_cache:
cache_file(filename)
if filename not in file_cache:
return None
pass
if file_cache[filename].sha1:
return file_cache[filename].sha1.hexdigest()
sha1 = hashlib.sha1()
for line in file_cache... | def sha1(filename) | Return SHA1 of filename. | 2.91291 | 2.855866 | 1.019974 |
filename = unmap_file(filename)
if filename not in file_cache:
if not use_cache_only: cache_file(filename)
if filename not in file_cache:
return None
pass
return len(file_cache[filename].lines['plain']) | def size(filename, use_cache_only=False) | Return the number of lines in filename. If `use_cache_only' is False,
we'll try to fetch the file if it is not cached. | 5.073739 | 5.140259 | 0.987059 |
if filename not in file2file_remap_lines:
return size(filename, use_cache_only)
max_lineno = -1
remap_line_entry = file2file_remap_lines.get(filename)
if not remap_line_entry:
return size(filename, use_cache_only)
for t in remap_line_entry.from_to_pairs:
max_lineno = max... | def maxline(filename, use_cache_only=False) | Return the maximum line number filename after taking into account
line remapping. If no remapping then this is the same as size | 3.155663 | 2.875433 | 1.097457 |
filename = pyc2py(filename)
if filename not in file_cache:
if not use_cache_only: cache_file(filename)
if filename not in file_cache:
return None
pass
return file_cache[filename].stat | def stat(filename, use_cache_only=False) | Return stat() info for *filename*. If *use_cache_only* is *False*,
we will try to fetch the file if it is not cached. | 4.641794 | 5.168293 | 0.898129 |
fullname = cache_file(filename, reload_on_change)
if not fullname: return None
e = file_cache[filename]
if not e.line_numbers:
if hasattr(coverage.coverage, 'analyze_morf'):
e.line_numbers = coverage.the_coverage.analyze_morf(fullname)[1]
else:
cov = coverage... | def trace_line_numbers(filename, reload_on_change=False) | Return an Array of breakpoints in filename.
The list will contain an entry for each distinct line event call
so it is possible (and possibly useful) for a line number appear more
than once. | 4.766808 | 4.95557 | 0.961909 |
if not filename: return None
orig_filename = filename
filename = pyc2py(filename)
if filename in file_cache: del file_cache[filename]
path = os.path.abspath(filename)
stat = None
if get_option('use_linecache_lines', opts):
fname_list = [filename]
mapped_path = file2fil... | def update_cache(filename, opts=default_opts, module_globals=None) | Update a cache entry. If something is wrong, return
*None*. Return *True* if the cache was updated and *False* if not. If
*use_linecache_lines* is *True*, use an existing cache entry as source
for the lines of the file. | 2.913131 | 2.836985 | 1.02684 |
session = await get_session(request)
session[self.cookie_name] = ticket | async def remember_ticket(self, request, ticket) | Called to store the ticket data for a request.
Ticket data is stored in the aiohttp_session object
Args:
request: aiohttp Request object.
ticket: String like object representing the ticket to be stored. | 6.039616 | 6.685553 | 0.903383 |
session = await get_session(request)
session.pop(self.cookie_name, '') | async def forget_ticket(self, request) | Called to forget the ticket data a request
Args:
request: aiohttp Request object. | 8.688219 | 11.416508 | 0.761022 |
session = await get_session(request)
return session.get(self.cookie_name) | async def get_ticket(self, request) | Called to return the ticket for a request.
Args:
request: aiohttp Request object.
Returns:
A ticket (string like) object, or None if no ticket is available
for the passed request. | 7.223108 | 11.131736 | 0.648875 |
assert isinstance(policy, AbstractAuthentication)
async def _auth_middleware_factory(app, handler):
async def _middleware_handler(request):
# Save the policy in the request
request[POLICY_KEY] = policy
# Call the next handler in the chain
response ... | def auth_middleware(policy) | Returns a aiohttp_auth middleware factory for use by the aiohttp
application object.
Args:
policy: A authentication policy with a base class of
AbstractAuthentication. | 3.137362 | 3.079136 | 1.01891 |
auth_val = request.get(AUTH_KEY)
if auth_val:
return auth_val
auth_policy = request.get(POLICY_KEY)
if auth_policy is None:
raise RuntimeError('auth_middleware not installed')
request[AUTH_KEY] = await auth_policy.get(request)
return request[AUTH_KEY] | async def get_auth(request) | Returns the user_id associated with a particular request.
Args:
request: aiohttp Request object.
Returns:
The user_id associated with the request, or None if no user is
associated with the request.
Raises:
RuntimeError: Middleware is not installed | 3.979934 | 3.473504 | 1.145798 |
auth_policy = request.get(POLICY_KEY)
if auth_policy is None:
raise RuntimeError('auth_middleware not installed')
return await auth_policy.remember(request, user_id) | async def remember(request, user_id) | Called to store and remember the userid for a request
Args:
request: aiohttp Request object.
user_id: String representing the user_id to remember
Raises:
RuntimeError: Middleware is not installed | 6.405286 | 4.610823 | 1.389185 |
auth_policy = request.get(POLICY_KEY)
if auth_policy is None:
raise RuntimeError('auth_middleware not installed')
return await auth_policy.forget(request) | async def forget(request) | Called to forget the userid for a request
Args:
request: aiohttp Request object
Raises:
RuntimeError: Middleware is not installed | 6.865164 | 5.220777 | 1.31497 |
def decorator(fn):
def debounced(*args, **kwargs):
def call_it():
fn(*args, **kwargs)
try:
debounced.t.cancel()
except(AttributeError):
pass
debounced.t = threading.Timer(wait, call_it)
debounced... | def debounce(wait) | Decorator that will postpone a functions
execution until after wait seconds
have elapsed since the last time it was invoked. | 1.655872 | 1.766154 | 0.937558 |
await super().process_response(request, response)
if COOKIE_AUTH_KEY in request:
if response.started:
raise RuntimeError("Cannot save cookie into started response")
cookie = request[COOKIE_AUTH_KEY]
if cookie == '':
response.d... | async def process_response(self, request, response) | Called to perform any processing of the response required.
This function stores any cookie data in the COOKIE_AUTH_KEY as a
cookie in the response object. If the value is a empty string, the
associated cookie is deleted instead.
This function requires the response to be a aiohttp Respo... | 4.33935 | 3.248942 | 1.335619 |
res = self.get(uri)
ysmm = re.findall(r'var ysmm =.*\;?', res.text)
if len(ysmm) == 0:
raise UnshortenFailed('No ysmm variable found.')
# Decode the ysmm variable and extract the actual link
ysmm = re.sub(r'var ysmm \= \'|\'\;', '', ysmm[0])
left ... | def unshorten(self, uri: str) -> str | http://j.gs/AXr9 | 3.659658 | 3.547836 | 1.031518 |
'''
Definition decorator for all function requiring an active session
Credit: http://stackoverflow.com/a/7590709
'''
def _wrapper(self, *args, **kwargs):
'''
Function to be applied on top of all decorated methods
'''
if self._token_age:
timediff = self._to... | def login_required(f) | Definition decorator for all function requiring an active session
Credit: http://stackoverflow.com/a/7590709 | 5.055872 | 3.416746 | 1.479733 |
'''
Parse CLI args
'''
parser = argparse.ArgumentParser(description='Process args')
parser.Add_argument(
'-H', '--host',
required=True,
action='store',
help='Remote host to connect to'
)
parser.add_argument(
'-P', '--port',
type=int,
de... | def get_args() | Parse CLI args | 1.892151 | 1.838895 | 1.028961 |
'''
Main function
'''
# We should only steal the root logger if we're the application, not the module
logging.basicConfig(level=logging.DEBUG)
args = get_args()
if args.password:
password = args.password
else:
password = getpass(
prompt='Enter password for {... | def main() | Main function | 3.771468 | 3.662328 | 1.029801 |
'''
Get information about the API
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#api_version_information
'''
return self.__auth_req_get(self.rest_url, verbose=verbose) | def api_version(self, verbose=False) | Get information about the API
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#api_version_information | 11.382827 | 3.009688 | 3.782062 |
'''
Get information about the current opsview instance
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#opsview_information
'''
url = '{}/{}'.format(self.rest_url, 'info')
return self.__auth_req_get(url, verbose=verbose) | def opsview_info(self, verbose=False) | Get information about the current opsview instance
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#opsview_information | 5.783463 | 2.499704 | 2.313659 |
'''
Authenticate with Opsview
:param verbose: Verbose output mode
:type verbose: bool
:return: The authentification token
:rtype: str or unicode
'''
url = '{}/{}'.format(self.rest_url, 'login')
logger.debug('POST: {}'.format(url))
r = reque... | def login(self, verbose=False) | Authenticate with Opsview
:param verbose: Verbose output mode
:type verbose: bool
:return: The authentification token
:rtype: str or unicode | 3.185812 | 2.486986 | 1.280993 |
'''
Delete the current session
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#logout
'''
url = '{}/{}'.format(self.rest_url, 'logout')
response = self.__auth_req_post(url, verbose=verbose)
self.headers['X-Opsview-Token'] = None
return response | def logout(self, verbose=False) | Delete the current session
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#logout | 5.951703 | 2.767719 | 2.1504 |
'''
Get information about the currently authenticated user
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information
'''
url = '{}/{}'.format(self.rest_url, 'user')
return self.__auth_req_get(url, verbose=verbose) | def user_info(self, verbose=False) | Get information about the currently authenticated user
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information | 7.015356 | 2.526263 | 2.776969 |
'''
Get information about the Opsview monitoring servers
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#server_information
'''
url = '{}/{}'.format(self.rest_url, 'serverinfo')
return self.__auth_req_get(url, verbose=verbose) | def server_info(self, verbose=False) | Get information about the Opsview monitoring servers
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#server_information | 7.841685 | 2.568783 | 3.052685 |
'''
Initiate a config reload. This may take a while on large installations.
'''
# If we're using an API version older than 4.5.0, don't use async
api_version = float(self.api_version()['api_version'])
if api_version < 4.5:
async = False
url = '{}/{}{}'... | def reload_config(self, async=True, verbose=False) | Initiate a config reload. This may take a while on large installations. | 5.521138 | 4.509133 | 1.224435 |
ticket = self._new_ticket(request, user_id)
await self.remember_ticket(request, ticket) | async def remember(self, request, user_id) | Called to store the userid for a request.
This function creates a ticket from the request and user_id, and calls
the abstract function remember_ticket() to store the ticket.
Args:
request: aiohttp Request object.
user_id: String representing the user_id to remember | 6.177782 | 6.704297 | 0.921466 |
ticket = await self.get_ticket(request)
if ticket is None:
return None
try:
# Returns a tuple of (user_id, token, userdata, validuntil)
now = time.time()
fields = self._ticket.validate(ticket, self._get_ip(request), now)
# Ch... | async def get(self, request) | Gets the user_id for the request.
Gets the ticket for the request using the get_ticket() function, and
authenticates the ticket.
Args:
request: aiohttp Request object.
Returns:
The userid for the request, or None if the ticket is not
authenticated. | 5.057703 | 4.552756 | 1.11091 |
if _REISSUE_KEY in request:
if (response.started or
not isinstance(response, web.Response) or
response.status < 200 or response.status > 299):
return
await self.remember_ticket(request, request[_REISSUE_KEY]) | async def process_response(self, request, response) | If a reissue was requested, only reiisue if the response was a
valid 2xx response | 6.50971 | 5.021436 | 1.296384 |
'''Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it.
'''
try:
iteritem... | def elements(self) | Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it. | 4.423368 | 2.226346 | 1.986829 |
'''Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d) # add elements from another counter
>... | def update(self, iterable=None, **kwds) | Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d) # add elements from another counter
>>> c[... | 2.75054 | 1.698532 | 1.619363 |
def decorator(func):
@wraps(func)
async def wrapper(*args):
request = args[-1]
if callable(context):
context = context()
if await get_permitted(request, permission, context):
return await func(*args)
raise web.... | def acl_required(permission, context) | Returns a decorator that checks if a user has the requested permission
from the passed acl context.
This function constructs a decorator that can be used to check a aiohttp's
view for authorization before calling it. It uses the get_permission()
function to check the request against the passed permissi... | 3.526246 | 3.589874 | 0.982276 |
if float(dataset.get('version')) >= 2.0 \
if dataset.get('version') else False:
return True
else:
return False | def check_version_2(dataset) | Checks if json-stat version attribute exists and is equal or greater \
than 2.0 for a given dataset.
Args:
dataset (OrderedDict): data in JSON-stat format, previously \
deserialized to a python object by \
json.load() or json.... | 5.433487 | 4.864978 | 1.116858 |
for item in collection['link']['item']:
if item['class'] == 'dataset':
df_list.append(Dataset.read(item['href']).write('dataframe'))
elif item['class'] == 'collection':
nested_collection = request(item['href'])
unnest_collection(nested_collection, df_list) | def unnest_collection(collection, df_list) | Unnest collection structure extracting all its datasets and converting \
them to Pandas Dataframes.
Args:
collection (OrderedDict): data in JSON-stat format, previously \
deserialized to a python object by \
json.l... | 4.047854 | 4.127741 | 0.980646 |
dimensions = []
dim_names = []
if check_version_2(js_dict):
dimension_dict = js_dict
else:
dimension_dict = js_dict['dimension']
for dim in dimension_dict['id']:
dim_name = js_dict['dimension'][dim]['label']
if not dim_name:
dim_name = dim
if... | def get_dimensions(js_dict, naming) | Get dimensions from input data.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
naming (string, optional): dimension naming. Possible values: 'label' \
or 'id'.
Returns:
dimensions (list): list of pandas data frames with dimension \
... | 2.382704 | 2.278452 | 1.045756 |
if input == 'dataset':
input = js_dict['dimension'][dim]
label_col = 'label'
elif input == 'dimension':
label_col = js_dict['label']
input = js_dict
else:
raise ValueError
try:
dim_label = input['category']['label']
except KeyError:
dim... | def get_dim_label(js_dict, dim, input="dataset") | Get label from a given dimension.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
dim (string): dimension name obtained from JSON file.
Returns:
dim_label(pandas.DataFrame): DataFrame with label-based dimension data. | 2.332548 | 2.279496 | 1.023273 |
try:
dim_index = js_dict['dimension'][dim]['category']['index']
except KeyError:
dim_label = get_dim_label(js_dict, dim)
dim_index = pd.DataFrame(list(zip([dim_label['id'][0]], [0])),
index=[0],
columns=['id', 'index... | def get_dim_index(js_dict, dim) | Get index from a given dimension.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
dim (string): dimension name obtained from JSON file.
Returns:
dim_index (pandas.DataFrame): DataFrame with index-based dimension data. | 2.383987 | 2.236252 | 1.066063 |
values = js_dict[value]
if type(values) is list:
if type(values[0]) is not dict or tuple:
return values
# being not a list of dicts or tuples leaves us with a dict...
values = {int(key): value for (key, value) in values.items()}
if js_dict.get('size'):
max_val = np... | def get_values(js_dict, value='value') | Get values from input data.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
value (string, optional): name of the value column. Defaults to 'value'.
Returns:
values (list): list of dataset values. | 4.046771 | 4.146604 | 0.975924 |
check_input(naming)
if i == 0 or record is None:
record = []
for dimension in dimensions[i][naming]:
record.append(dimension)
if len(record) == len(dimensions):
yield record
if i + 1 < len(dimensions):
for row in get_df_row(dimensions, naming, i... | def get_df_row(dimensions, naming='label', i=0, record=None) | Generate row dimension values for a pandas dataframe.
Args:
dimensions (list): list of pandas dataframes with dimension labels \
generated by get_dim_label or get_dim_index methods.
naming (string, optional): dimension naming. Possible values: 'label' \
... | 3.269383 | 3.231019 | 1.011874 |
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)] | def uniquify(seq) | Return unique values in a list in the original order. See: \
http://www.peterbe.com/plog/uniqifiers-benchmark
Args:
seq (list): original list.
Returns:
list: list without duplicates preserving original order. | 2.158146 | 2.178067 | 0.990854 |
values = []
dimensions, dim_names = get_dimensions(js_dict, naming)
values = get_values(js_dict, value=value)
output = pd.DataFrame([category + [values[i]]
for i, category in
enumerate(get_df_row(dimensions, naming))])
output.columns = dim_... | def generate_df(js_dict, naming, value="value") | Decode JSON-stat dict into pandas.DataFrame object. Helper method \
that should be called inside from_json_stat().
Args:
js_dict(OrderedDict): OrderedDict with data in JSON-stat format, \
previously deserialized into a python object by \
json.loa... | 4.494382 | 4.472424 | 1.00491 |
warnings.warn(
"Shouldn't use this function anymore! Now use read() methods of"
"Dataset, Collection or Dimension.",
DeprecationWarning
)
check_input(naming)
results = []
if type(datasets) is list:
for idx, element in enumerate(datasets):
for datase... | def from_json_stat(datasets, naming='label', value='value') | Decode JSON-stat formatted data into pandas.DataFrame object.
Args:
datasets(OrderedDict, list): data in JSON-stat format, previously \
deserialized to a python object by \
json.load() or json.loads(), for example.\
... | 4.252952 | 4.060959 | 1.047278 |
warnings.warn(
"Shouldn't use this function anymore! Now use write() methods of"
"Dataset, Collection or Dimension.",
DeprecationWarning
)
data = []
if output == 'list':
result = []
elif output == 'dict':
result = OrderedDict({})
if isinstance(input_... | def to_json_stat(input_df, value='value', output='list', version='1.3') | Encode pandas.DataFrame object into JSON-stat format. The DataFrames
must have exactly one value column.
Args:
df(pandas.DataFrame): pandas data frame (or list of data frames) to
encode.
value (string, optional): name of the value column. Defaults to 'value'.
output(string): accepts ... | 2.928452 | 2.928768 | 0.999892 |
headers = {'Accept': 'application/json'}
try:
requested_object = requests.get(path, headers=headers)
requested_object.raise_for_status()
except requests.exceptions.HTTPError as exception:
LOGGER.error((inspect.stack()[0][3]) + ': HTTPError = ' +
str(exceptio... | def request(path) | Send a request to a given URL accepting JSON format and return a \
deserialized Python object.
Args:
path (str): The URI to be requested.
Returns:
response: Deserialized JSON Python object.
Raises:
HTTPError: the HTTP error returned by the requested server.
InvalidURL: an i... | 2.538144 | 2.480185 | 1.023369 |
if isinstance(data, pd.DataFrame):
return cls((json.loads(
to_json_stat(data, output='dict', version='2.0'),
object_pairs_hook=OrderedDict)))
elif isinstance(data, OrderedDict):
return cls(data)
elif (isinstance(data, basestring)
... | def read(cls, data) | Reads data from URL, Dataframe, JSON string, JSON file or
OrderedDict.
Args:
data: can be a Pandas Dataframe, a JSON file, a JSON string,
an OrderedDict or a URL pointing to a JSONstat file.
Returns:
An object of class Dataset populated with data. | 2.829333 | 2.521957 | 1.12188 |
if 'index' not in self.get('dimension', {}). \
get(name, {}).get('category', {}):
return 0
ndx = self['dimension'][name]['category']['index']
if isinstance(ndx, list):
return ndx.index(value)
else:
return ndx[value] | def get_dimension_index(self, name, value) | Converts a dimension ID string and a categody ID string into the \
numeric index of that category in that dimension
Args:
name(string): ID string of the dimension.
value(string): ID string of the category.
Returns:
ndx[value](int): index of the category in th... | 4.043203 | 3.661927 | 1.104119 |
ids = self['id'] if self.get('id') else self['dimension']['id']
indices = []
for idx, id in enumerate(ids):
indices.append(self.get_dimension_index(id,
[d.get(id) for d in query
... | def get_dimension_indices(self, query) | Converts a dimension/category list of dicts into a list of \
dimensions’ indices.
Args:
query(list): dimension/category list of dicts.
Returns:
indices(list): list of dimensions' indices. | 5.568642 | 5.216211 | 1.067564 |
size = self['size'] if self.get('size') else self['dimension']['size']
ndims = len(size)
mult = 1
num = 0
for idx, dim in enumerate(size):
mult *= size[ndims - idx] if (idx > 0) else 1
num += mult * indices[ndims - idx - 1]
return num | def get_value_index(self, indices) | Converts a list of dimensions’ indices into a numeric value index.
Args:
indices(list): list of dimension's indices.
Returns:
num(int): numeric value index. | 4.331518 | 3.85372 | 1.123983 |
indices = self.get_dimension_indices(query)
index = self.get_value_index(indices)
value = self.get_value_by_index(index)
return value | def get_value(self, query) | Converts a dimension/category list of dicts into a data value \
in three steps.
Args:
query(list): list of dicts with the desired query.
Returns:
value(float): numeric data value. | 3.715306 | 4.245019 | 0.875215 |
if isinstance(data, pd.DataFrame):
output = OrderedDict({})
output['version'] = '2.0'
output['class'] = 'dimension'
[label] = [x for x in list(data.columns.values) if
x not in ['id', 'index']]
output['label'] = label
... | def read(cls, data) | Reads data from URL, Dataframe, JSON string, JSON file
or OrderedDict.
Args:
data: can be a Pandas Dataframe, a JSON string, a JSON file,
an OrderedDict or a URL pointing to a JSONstat file.
Returns:
An object of class Dimension populated with data. | 2.637968 | 2.45959 | 1.072523 |
if output == 'jsonstat':
return json.dumps(OrderedDict(self), cls=NumpyEncoder)
elif output == 'dataframe':
return get_dim_label(self, self['label'], 'dimension')
else:
raise ValueError("Allowed arguments are 'jsonstat' or 'dataframe'") | def write(self, output='jsonstat') | Writes data from a Dataset object to JSONstat or Pandas Dataframe.
Args:
output(string): can accept 'jsonstat' or 'dataframe'
Returns:
Serialized JSONstat or a Pandas Dataframe,depending on the \
'output' parameter. | 5.359404 | 5.55032 | 0.965603 |
if isinstance(data, OrderedDict):
return cls(data)
elif isinstance(data, basestring)\
and data.startswith(("http://", "https://", "ftp://", "ftps://")):
return cls(request(data))
elif isinstance(data, basestring):
try:
jso... | def read(cls, data) | Reads data from URL or OrderedDict.
Args:
data: can be a URL pointing to a JSONstat file, a JSON string
or an OrderedDict.
Returns:
An object of class Collection populated with data. | 2.204133 | 2.088802 | 1.055214 |
if output == 'jsonstat':
return json.dumps(self)
elif output == 'dataframe_list':
df_list = []
unnest_collection(self, df_list)
return df_list
else:
raise ValueError(
"Allowed arguments are 'jsonstat' or 'dataf... | def write(self, output='jsonstat') | Writes data from a Collection object to JSONstat or list of \
Pandas Dataframes.
Args:
output(string): can accept 'jsonstat' or 'dataframe_list'
Returns:
Serialized JSONstat or a list of Pandas Dataframes,depending on \
the 'output' parameter. | 4.05443 | 3.020865 | 1.342142 |
if self['link']['item'][element]['class'] == 'dataset':
return Dataset.read(self['link']['item'][element]['href'])
elif self['link']['item'][element]['class'] == 'collection':
return Collection.read(self['link']['item'][element]['href'])
elif self['link']['item'... | def get(self, element) | Gets ith element of a collection in an object of the corresponding \
class.
Args:
output(string): can accept 'jsonstat' or 'dataframe_list'
Returns:
Serialized JSONstat or a list of Pandas Dataframes,depending on \
the 'output' parameter. | 3.159727 | 3.129118 | 1.009782 |
@wraps(func)
async def wrapper(*args):
if (await get_auth(args[-1])) is None:
raise web.HTTPForbidden()
return await func(*args)
return wrapper | def auth_required(func) | Utility decorator that checks if a user has been authenticated for this
request.
Allows views to be decorated like:
@auth_required
def view_func(request):
pass
providing a simple means to ensure that whoever is calling the function has
the correct authentication details.
... | 3.864795 | 5.719121 | 0.675767 |
args = []
kwargs = {}
tokens = token.split_contents()
if len(tokens) < 2:
raise TemplateSyntaxError(
'%r tag requires one or more arguments' %
token.contents.split()[0]
)
tokens.pop(0) # tag name
view_name = tokens.pop(0)
for token in tokens:
... | def render_partial(parser, token) | Inserts the output of a view, using fully qualified view name,
or view name from urls.py.
{% render_partial view_name arg[ arg2] k=v [k2=v2...] %}
IMPORTANT: the calling template must receive a context variable called
'request' containing the original HttpRequest. This means you should be OK
wit... | 2.411224 | 2.411803 | 0.99976 |
# Try to convert node, raise error with code on failure
try:
svgout = WaveDrom().renderWaveForm(0, json.loads(node['code']))
except JSONDecodeError as e:
raise SphinxError("Cannot render the following json code: \n{} \n\nError: {}".format(node['code'], e))
if not os.path.exists(ou... | def render_wavedrom(self, node, outpath, bname, format) | Render a wavedrom image | 3.963349 | 3.926663 | 1.009343 |
format = determine_format(self.builder.supported_image_types)
if format is None:
raise SphinxError(__("Cannot determine a suitable output format"))
# Create random filename
bname = "wavedrom-{}".format(uuid4())
outpath = path.join(self.builder.outdir, self.builder.imagedir)
# Rend... | def visit_wavedrom(self, node) | Visit the wavedrom node | 6.423625 | 6.252379 | 1.027389 |
if (app.config.wavedrom_html_jsinline and
app.builder.name not in ('html', 'dirhtml', 'singlehtml')):
app.config.wavedrom_html_jsinline = False
# Skip for non-html or if javascript is not inlined
if not app.env.config.wavedrom_html_jsinline:
return
if app.config.offline_sk... | def builder_inited(app) | Sets wavedrom_html_jsinline to False for all non-html builders for
convenience (use ifconf etc.)
We instruct sphinx to include some javascript files in the output html.
Depending on the settings provided in the configuration, we take either
the online files from the wavedrom server, or the locally prov... | 2.938588 | 2.539756 | 1.157035 |
# Skip for non-html or if javascript is not inlined
if not app.env.config.wavedrom_html_jsinline:
return
if app.config.offline_skin_js_path is not None:
copy_static_entry(path.join(app.builder.srcdir, app.config.offline_skin_js_path), path.join(app.builder.outdir, '_static'), app.build... | def build_finished(app, exception) | When the build is finished, we copy the javascript files (if specified)
to the build directory (the static folder) | 3.587908 | 3.182858 | 1.12726 |
# Skip for non-html or if javascript is not inlined
if not app.env.config.wavedrom_html_jsinline:
return
text =
doctree.append(nodes.raw(text=text, format='html')) | def doctree_resolved(app, doctree, fromdocname) | When the document, and all the links are fully resolved, we inject one
raw html element for running the command for processing the wavedrom
diagrams at the onload event. | 11.751717 | 9.457705 | 1.242555 |
app.add_config_value('offline_skin_js_path', None, 'html')
app.add_config_value('offline_wavedrom_js_path', None, 'html')
app.add_config_value('wavedrom_html_jsinline', True, 'html')
app.add_directive('wavedrom', WavedromDirective)
app.connect('build-finished', build_finished)
app.connect('... | def setup(app) | Setup the extension | 2.423264 | 2.397407 | 1.010786 |
user_supercell = [[1, supercell[0]], [1, supercell[1]], [1, supercell[1]]]
system = create_supercell(system, matrix, supercell=user_supercell)
return MolecularSystem.load_system(system) | def make_supercell(system, matrix, supercell=[1, 1, 1]) | Return a supercell.
This functions takes the input unitcell and creates a supercell of it that
is returned as a new :class:`pywindow.molecular.MolecularSystem`.
Parameters
----------
system : :attr:`pywindow.molecular.MolecularSystem.system`
The unit cell for creation of the supercell
... | 3.869817 | 4.983791 | 0.776481 |
if override is True:
self.frames = {}
if isinstance(frames, int):
frame = self._get_frame(
self.trajectory_map[frames], frames, **kwargs)
if frames not in self.frames.keys():
self.frames[frames] = frame
return frame... | def get_frames(self, frames='all', override=False, **kwargs) | Extract frames from the trajectory file.
Depending on the passed parameters a frame, a list of particular
frames, a range of frames (from, to), or all frames can be extracted
with this function.
Parameters
----------
frames : :class:`int` or :class:`list` or :class:`tou... | 1.745321 | 1.71226 | 1.019308 |
# We pass a copy of the analysis attribute dictionary.
dict_obj = deepcopy(self.analysis_output)
# If no filepath is provided we create one.
if filepath is None:
filepath = "_".join(
(str(self.system_id), "pywindow_analysis")
)
... | def save_analysis(self, filepath=None, **kwargs) | Dump the content of :attr:`analysis_output` as JSON dictionary.
Parameters
----------
filepath : :class:`str`
The filepath for the JSON file.
Returns
-------
None : :class:`NoneType` | 7.128198 | 7.197412 | 0.990383 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.