code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
import re
import shap
import numpy as np
import pandas as pd
from warnings import warn
from scipy.special import softmax
from sklearn.model_selection import train_test_split
from sklearn.inspection import permutation_importance
from ageas.classifier import reshape_tensor
import ageas.lib as lib
import ageas.tool as tool
class Interpret:
"""
Apply various methods to interpret correct predictions made by models
Then, assign an importance score to every feature
"""
def __init__(self, trainer_data):
super(Interpret, self).__init__()
# make background example based on mean of every sample
# ToDo:
# Background generation may need to be revised
# We may just use grn generated based on universal exp matrix
bases = pd.DataFrame().append(trainer_data.allData.mean(axis = 0),
ignore_index = True)
self.result = self.__interpret_process(trainer_data, bases)
self.result = self.__subtract_feature_score(self.result)
# Calculate importances of each feature
def __interpret_process(self, trainer_data, bases):
shap_explainer = SHAP_Explainer(bases)
feature_score_sum = None
# sumFIs = None
for records in trainer_data.models:
# get model and data to explain
model = records[0]
accuracy = records[-1]
print(' Interpreting:',model.id,' which reached ACC:',accuracy)
test_data = ''
# Get sample index when test result consist with ground truth
for i in range(len(records[-2])):
if trainer_data.allLabel[i] == records[-2][i]:
test_data += str(i) + ';'
test_data = list(map(int, test_data.split(';')[:-1]))
# usefullLabel = trainer_data.allLabel[test_data]
test_data = trainer_data.allData.iloc[test_data,:]
# Handling RFC cases
if model.model_type == 'RFC':
feature_score = shap_explainer.get_tree_explain(
model.clf,
test_data
)
# Handling GNB cases
elif model.model_type == 'GNB':
feature_score = shap_explainer.get_kernel_explain(
model.clf.predict_proba,
test_data
)
# Handling Logistic Regression cases
elif model.model_type == 'Logit':
feature_score = softmax(abs(model.clf.coef_[0]))
# Handling SVM cases
elif model.model_type == 'SVM':
# Handle linear kernel SVC here
if model.param['kernel'] == 'linear':
feature_score = softmax(abs(model.clf.coef_[0]))
# Handle other cases here
else:
feature_score = shap_explainer.get_kernel_explain(
model.clf.predict_proba,
test_data
)
# Hybrid CNN cases and 1D CNN cases
elif re.search(r'CNN', model.model_type):
# Use DeepExplainer when in limited mode
if re.search(r'Limited', model.model_type):
feature_score = shap_explainer.get_deep_explain(
model,
test_data
)
# Use GradientExplainer when in unlimited mode
elif re.search(r'Unlimited', model.model_type):
feature_score = shap_explainer.get_gradient_explain(
model,
test_data
)
else:
raise lib.Error('Unrecogonized CNN model:',model.model_type)
# XGB's GBM cases
elif model.model_type == 'XGB_GBM':
feature_score = softmax(model.clf.feature_importances_)
# RNN_base model cases
elif (model.model_type == 'RNN' or
model.model_type == 'LSTM' or
model.model_type == 'GRU' or
model.model_type == 'Transformer'):
feature_score = shap_explainer.get_gradient_explain(
model,
test_data
)
else:raise lib.Error('Unrecogonized model type: ', model.model_type)
# Update feature_score_sum
if feature_score_sum is None and feature_score is not None:
feature_score_sum = pd.array(
(feature_score * accuracy),
dtype = float
)
elif feature_score is not None:
feature_score_sum += (feature_score * accuracy)
# Make feature importnace matrix
feature_score = pd.DataFrame()
feature_score.index = bases.columns
feature_score['importance'] = feature_score_sum
feature_score = feature_score.sort_values('importance', ascending=False)
return feature_score
# clear out Fake GRPs if there is any
# also subtract DataFrame based on standardized Z score
def __subtract_feature_score(self, df):
df['importance'] = df['importance'] - df['importance'][-1]
remove_list = []
for ele in df.index:
if re.search('FAKE', ele):
if df.loc[ele]['importance'] != 0.0:
raise lib.Error('Fake GRP got attention!: ', ele)
remove_list.append(ele)
df = df.drop(index = remove_list)
df = tool.Z_Score_Standardize(df = df, col = 'importance')
# validation part
return df
# Update feature importance matrix with newer matrix
def add(self, df):
self.result = self.result.add(
df,
axis = 0,
fill_value = 0
).sort_values(
'importance',
ascending = False
)
# divide importance value with stabilizing iteration times
def divide(self, denominator):
self.result['importance'] = self.result['importance'] / denominator
# stratify GRPs based on Z score thread
def stratify(self, z_score_thread, top_grp_amount):
# change top top_grp_amount to int if value less or equal 1.0
if top_grp_amount <= 1.0:
top_grp_amount = int(len(self.result.index) * top_grp_amount)
for thread in range(len(self.result.index)):
value = self.result.iloc[thread]['importance']
if value < z_score_thread or thread == top_grp_amount:
break
if thread < top_grp_amount:
print('Not enough GRP with Z score over thread, extract', thread)
return self.result[:thread]
# Save feature importances to given path
def save(self, path): self.result.to_csv(path, sep = '\t')
class SHAP_Explainer(object):
"""docstring for SHAP_Explainer."""
def __init__(self, basement_data = None):
super(SHAP_Explainer, self).__init__()
self.basement_data = basement_data
# Use LinearExplainer
""" May need to revise """
def get_linear_explain(self, model, data: pd.DataFrame):
explainer = shap.LinearExplainer(model, self.basement_data,)
shap_vals = explainer.shap_values(data)
return softmax(sum(np.abs(shap_vals).mean(0)))
# Use KernelExplainer
def get_kernel_explain(self, model, data: pd.DataFrame):
# print('Kernel Explainer is too slow! Skipping now!')
# return None
explainer = shap.KernelExplainer(model, data = self.basement_data,)
shap_vals = explainer.shap_values(data)
return softmax(sum(np.abs(shap_vals).mean(0)))
# Use GradientExplainer
def get_gradient_explain(self, model, data: pd.DataFrame):
# reshape basement data to tensor type
base = reshape_tensor(self.basement_data.values.tolist())
explainer = shap.GradientExplainer(model, data = base)
# Calculate shapley values
shap_vals = explainer.shap_values(reshape_tensor(data.values.tolist()))
# Get feature importances based on shapley value
return softmax(sum(np.abs(shap_vals).mean(0))[0])
# Use DeepExplainer
def get_deep_explain(self, model, data: pd.DataFrame):
# reshape basement data to tensor type
base = reshape_tensor(self.basement_data.values.tolist())
explainer = shap.DeepExplainer(model, data = base)
# Calculate shapley values
shap_vals = explainer.shap_values(reshape_tensor(data.values.tolist()))
# Get feature importances based on shapley value
return softmax(sum(np.abs(shap_vals).mean(0))[0])
# Use TreeExplainer
def get_tree_explain(self, model, data: pd.DataFrame):
explainer = shap.TreeExplainer(
model,
feature_perturbation = 'interventional',
check_additivity = False,
data = self.basement_data,
)
shap_vals = explainer.shap_values(data)
return softmax(sum(np.abs(shap_vals).mean(0))) | Ageas | /Ageas-0.0.1a6.tar.gz/Ageas-0.0.1a6/ageas/lib/clf_interpreter.py | clf_interpreter.py |
# AgenciBr
> The objective is create a package that help to usa data of **Agencia Nacional de Águas (ANA)**, **Instituto Nacional de Meteorologia (INEMET)**, **Merge**, **Brazilian Daily Weather Gridded Data (BR-DWGD)** and **Instituto de Hidrología, Meteorología y Estudios Ambientales (IDEAM)**. All the data above is from Brazil, minus the **IDEAM** that is from Colombia.
- **ANA** [https://www.gov.br/ana/pt-br] or [https://www.snirh.gov.br/hidroweb/apresentacao]
- **INEMET** [https://portal.inmet.gov.br]
- **MERGE** [http://ftp.cptec.inpe.br/modelos/tempo/MERGE/GPM/DAILY/]
- **BR-DWGD** [https://github.com/AlexandreCandidoXavier/BR-DWGD]
- **IDEAM** [http://www.ideam.gov.co]
**Usage**
> pip install AgenciBr
In python:
**Import Ana**
```python
from AgenciBr import Ana.Ana
data = Ana.Ana('path file')
""" Properties """
data.dataset # return the dataset
data.code #Return the
data.startdate #return the first date from dataset
data.enddate #return the end date from dataset
data.len #return the length from dataset
data.type_data #return the data informations (precipitation, temperature, t_maxmin, wind, ...)
data.type #return if data is original, format1, format2 ...
```
**Import Inemet**
```python
from AgenciBr import Inemet
data = Inemet.Inemet('path file')
```
**Import Merge**
```python
from AgenciBr import Merge
data = Merge.Merge('path file')
```
**Import Alexandre**
```python
from AgenciBr import Alexandre
data = Alexandre.Alexandre('path file')
```
**Import Ideam**
```python
from AgenciBr import Ideam
data = Ideam.Ideam('path file')
```
**Suported functions**
|Agenci| Precipitacion | vazão | Temperature(mean) | Temperature (minimun, maximum)|
|------|---------------|-------|-------------------|-------------------------------|
| Ana | [x] |[ ] | [ ] | [ ] |
|Inemet| [x] | | [x] | |
|Merge | [ ] | [ ] | [ ] | [ ] |
|Alexandre| [ ] | [ ] | [ ] | [ ] |
| Ideam| [ ] | [ ] | [ ] | [ ] |
From internal function we construct function1, functon2
### Internal functions
## Format1
We work with distints data and dataframe models, bacause this, was create the function format1 in each agenci.
This function have three param:
- **Comma_to_dot**: change the comma of all file to dot and to float number
- **grow**: Change the dataframe from de lower to larger
- **years**: is a vector of two numbers (year1, year2) that you wish be the start and end, the year can be the future
**The principal objective of this function is**
1) put date that can be jumped
2) organize the file from to smaler to larger based in time
3) Change the ',' to '.'
4) Remove same values from file
5) Change the name of time variable to time
6) padronize a file to work with Ana, Inemet, Merge and etc
7) have option to select a series of year start and year end. The date that not exist, are created and set NaN
**The outfile have format precipitation**
```python
time pr
1997-07-01 0.1
1997-07-02 0.3
....
...
...
2020-01-01 0.3
2020-01-02 0.0
```
**The outfile have format temperature**
```python
time max min
0 1961-01-01 NaN NaN
1 1961-01-02 NaN NaN
2 1961-01-03 NaN NaN
3 1961-01-04 NaN NaN
4 1961-01-05 NaN NaN
... ... ... ...
22276 2021-12-28 28.7 21.6
22277 2021-12-29 29.3 21.6
22278 2021-12-30 26.9 21.8
22279 2021-12-31 32.3 21.6
22280 2022-01-01 27.6 23.8
[22281 rows x 3 columns]
```
## Format2
We work with datasets, to padronize, we create the function format2 that exists only when you are working with dataset files.
### Climate Indices
| Indices | Ana | Inemet | Xavier | Merge | IDEAM |
| ------- | --- | ------ | ------ | ----- | ----- |
| TXX | | [X] | | | [X] |
| TNX | | [X] | | | [X] |
| TX90P | | [X] | | | [X] |
| TN90P | | [X] | | | [X] |
| CDD | [X] | | | | |
| CWD | [X] | | | | |
| PRCPTOT | [X] | | | | [X] |
| RX5DAY | [X] | | | | [X] |
| TN10P | | | | | |
| FD | | | | | |
| SU | | | | | |
| ETR | | | | | |
| RNNMM | | | | | |
| R99P | | | | | |
| R95P | | | | | |
| R10MM | | | | | |
| R20MM | | | | | |
| R99PTOT | | | | | |
| AgenciBr | /AgenciBr-0.1.8.tar.gz/AgenciBr-0.1.8/README.md | README.md |
from ast import (
Name, Load, Store,
Assign, Attribute, Call, Constant, Expr, FunctionDef, ImportFrom, Module,
alias, fix_missing_locations, parse, unparse,
)
from collections.abc import Sequence
from copy import deepcopy
from pathlib import Path
from pprint import pprint
from typing import Optional
from . import decor
__all__: Sequence[str] = 'exec_and_get_state_seq', 'compare_output'
def exec_and_get_state_seq(
module_obj_or_script_file_path: Module | Path | str) -> list:
"""Execute Module object or script and get State Sequence."""
# pylint: disable=exec-used
if isinstance(module_obj_or_script_file_path, Module):
print('========================')
print('EXECUTING CODE MODULE...')
print('------------------------')
print(code_str := # bugs.python.org/issue44896
unparse(ast_obj=fix_missing_locations(module_obj_or_script_file_path))) # noqa: E501
print('------------------------')
exec(code_str, globals())
else:
assert isinstance(module_obj_or_script_file_path, Path | str)
print('=========')
print(f'EXECUTING {module_obj_or_script_file_path}...')
print('---------')
with open(file=module_obj_or_script_file_path,
mode='rt',
buffering=-1,
encoding='utf-8',
errors='strict',
newline=None,
closefd=True,
opener=None) as file:
# CUSTOMIZATION for Pybricks-based client code files
if 'pybricks' in (code_str := file.read()):
code_str: str = f'import pybricks.abm\n{code_str}'
exec(code_str)
state_seq: list = decor.STATE_SEQ
decor.STATE_SEQ: list = []
print()
pprint(object=state_seq,
stream=None,
indent=1,
width=80,
depth=None,
compact=False,
sort_dicts=False,
underscore_numbers=True)
print()
return state_seq
def _name_or_attr_from_str(s: str, /) -> Name | Attribute:
str_components = s.split(sep='.', maxsplit=1)
if len(str_components) == 1:
return Name(id=str_components[0], ctx=Load())
assert len(str_components) == 2
name, attr_name = str_components
return Attribute(value=Name(id=name, ctx=Load()), attr=attr_name, ctx=Load()) # noqa: E501
def compare_output(script_file_paths: tuple[str, str],
func_name: Optional[str] = None,
context_file_path: Optional[str] = None,
func_args: Optional[dict | list | tuple] = None) -> bool:
# pylint: disable=too-many-locals
"""Compare output of 2 functions or scripts."""
script_file_path_0, script_file_path_1 = script_file_paths
if func_name:
with open(file=script_file_path_0,
mode='rt',
buffering=-1,
encoding='utf-8',
errors='strict',
newline=None,
closefd=True,
opener=None) as file:
module_0: Module = parse(source=file.read(),
filename=script_file_path_0,
mode='exec',
type_comments=False,
feature_version=None)
try:
func_def_0: FunctionDef = next(i for i in module_0.body
if isinstance(i, FunctionDef)
and i.name == func_name) # noqa: E501,W503
except StopIteration as err:
raise ValueError(f'*** {script_file_path_0} HAS NO '
f'`def {func_name}(...)` ***') from err
with open(file=script_file_path_1,
mode='rt',
buffering=-1,
encoding='utf-8',
errors='strict',
newline=None,
closefd=True,
opener=None) as file:
module_1: Module = parse(source=file.read(),
filename=script_file_path_1,
mode='exec',
type_comments=False,
feature_version=None)
try:
func_def_1: FunctionDef = next(i for i in module_1.body
if isinstance(i, FunctionDef)
and i.name == func_name) # noqa: E501,W503
except StopIteration as err:
raise ValueError(f'*** {script_file_path_1} HAS NO '
f'`def {func_name}(...)` ***') from err
assert context_file_path, \
'*** context_file_path IS REQUIRED TO CHECK FUNCTION EQUALITY ***'
with open(file=context_file_path,
mode='rt',
buffering=-1,
encoding='utf-8',
errors='strict',
newline=None,
closefd=True,
opener=None) as file:
context_module: Module = parse(source=file.read(),
filename=context_file_path,
mode='exec',
type_comments=False,
feature_version=None)
if func_args:
func_args: list = [(_name_or_attr_from_str(arg_value[1:-1])
if isinstance(arg_value, str) and
arg_value.startswith('`') and
arg_value.endswith('`')
else Constant(value=arg_value))
for arg_value in (func_args.values()
if isinstance(func_args, dict)
else func_args)]
else:
func_args: list = []
decor_import: ImportFrom = ImportFrom(module='abm.decor',
names=[alias(name=(decor_name :=
'sense'),
asname=None)],
level=0)
func_decor: Assign = Assign(targets=[Name(id=func_name, ctx=Store())],
value=Call(func=Name(id=decor_name,
ctx=Load()),
args=[Name(id=func_name,
ctx=Load())],
keywords=[],
starargs=[],
kwargs=[]),
type_comment=None)
func_call: Expr = Expr(value=Call(func=Name(id=func_name, ctx=Load()),
args=func_args, keywords=[],
starargs=[], kwargs=[]))
module_0: Module = deepcopy(context_module)
module_0.body.extend((func_def_0, decor_import, func_decor, func_call))
module_1: Module = deepcopy(context_module)
module_1.body.extend((func_def_1, decor_import, func_decor, func_call))
result: bool = (
exec_and_get_state_seq(module_obj_or_script_file_path=module_0) ==
exec_and_get_state_seq(module_obj_or_script_file_path=module_1)
)
else:
result: bool = (
exec_and_get_state_seq(
module_obj_or_script_file_path=script_file_path_0) ==
exec_and_get_state_seq(
module_obj_or_script_file_path=script_file_path_1)
)
print(result)
return result | Agent-Behavior-Model | /Agent-Behavior-Model-23.1.25.tar.gz/Agent-Behavior-Model-23.1.25/src/abm/exec.py | exec.py |
from collections.abc import Sequence
from functools import wraps
from inspect import FullArgSpec, getfullargspec
import json
import re
from typing import Any, Callable, Optional, TypeVar
from . import interactive
__all__: Sequence[str] = 'act', 'sense', 'STATE_SEQ'
_OBJECT_MEMORY_PATTERN: str = ' object at 0x([0-9]|[a-f]|[A-F])+'
CallableTypeVar = TypeVar('CallableTypeVar', bound=Callable[..., Any])
_ACT_DECOR_FLAG: str = '__ACT_DECORATED__'
_SENSE_DECOR_FLAG: str = '__SENSE_DECORATED__'
STATE_SEQ: list = []
def args_dict_from_func_and_given_args(func: CallableTypeVar,
*args: Any, **kwargs: Any) -> dict[str, Any]: # noqa: E501
"""Get arguments dict from function and given arguments."""
# extract function's argument specs
arg_spec: FullArgSpec = getfullargspec(func=func)
# kw_only_arg_names: list[str] = arg_spec.kwonlyargs
# kw_only_var_arg_name: Optional[str] = arg_spec.varkw
# get number of matched positional arguments
n_matched_pos_args: int = min(len(pos_arg_names := arg_spec.args),
n_args := len(args))
# initialize args_dict with matched positional arguments and given kwargs
args_dict: dict[str, Any] = dict(zip(pos_arg_names[:n_matched_pos_args],
args[:n_matched_pos_args])) | kwargs
# insert positional argument defaults where applicable
if (pos_arg_defaults_tup := arg_spec.defaults):
# pylint: disable=invalid-name
for k, v in zip(pos_arg_names[-len(pos_arg_defaults_tup):],
pos_arg_defaults_tup):
if k not in args_dict:
args_dict[k] = v
# record positional varargs where applicable
if arg_spec.varargs and ((n_var_args := n_args - n_matched_pos_args) > 0):
args_dict['VARARGS'] = args[-n_var_args:]
# insert keyword-only argument defaults where applicable
if (kw_only_arg_defaults := arg_spec.kwonlydefaults):
# pylint: disable=invalid-name
for k, v in kw_only_arg_defaults.items():
if k not in args_dict:
args_dict[k] = v
return args_dict
def sanitize_object_name(obj: Any) -> Optional[str]:
"""Sanitize object name."""
return (None
if obj is None
else re.sub(_OBJECT_MEMORY_PATTERN, '', str(obj)))
def check_decor_status(func: callable, /) -> Optional[AssertionError]:
"""Ensure function has NOT been `act`- or `sense`-decorated."""
assert not getattr(func, _ACT_DECOR_FLAG, False), \
f'*** {func} ALREADY `act`-DECORATED ***'
assert not getattr(func, _SENSE_DECOR_FLAG, False), \
f'*** {func} ALREADY `sense`-DECORATED ***'
def act(actuating_func: CallableTypeVar, /) -> CallableTypeVar:
"""Actuation decorator."""
# (use same signature for IDE code autocomplete to work)
check_decor_status(actuating_func)
@wraps(actuating_func)
def decor_actuating_func(*args: Any, **kwargs: Any) -> tuple[str, dict[str, Any]]: # noqa: E501
actuating_func(*args, **kwargs)
args_dict: dict[str, Any] = \
args_dict_from_func_and_given_args(actuating_func, *args, **kwargs)
print_args: dict[str, Any] = args_dict.copy()
self_arg: Optional[Any] = print_args.pop('self', None)
input_arg_strs: list[str] = [f'{k}={v}' for k, v in print_args.items()]
self_name: Optional[str] = sanitize_object_name(self_arg)
print((f'ACT: {self_name}.' if self_name else 'ACT: ') +
f"{actuating_func.__name__}({', '.join(input_arg_strs)})")
result: tuple[str, dict] = actuating_func.__qualname__, args_dict
global STATE_SEQ # pylint: disable=global-variable-not-assigned
STATE_SEQ.append(result)
return result
setattr(decor_actuating_func, _ACT_DECOR_FLAG, True)
return decor_actuating_func
def sense(sensing_func: CallableTypeVar, /) -> CallableTypeVar:
"""Sensing decorator."""
# (use same signature for IDE code autocomplete to work)
check_decor_status(sensing_func)
# name of private dict storing current sensing states
sensing_state_dict_name: str = f'_{(sensing_func_name := sensing_func.__name__)}' # noqa: E501
@wraps(sensing_func)
def decor_sensing_func(*args: Any, set: Any = None, **kwargs: Any) -> Any:
# pylint: disable=redefined-builtin,too-many-locals
result: Any = sensing_func(*args, **kwargs)
args_dict: dict[str, Any] = \
args_dict_from_func_and_given_args(sensing_func, *args, **kwargs)
print_args: dict[str, Any] = args_dict.copy()
# get self
if (self := print_args.pop('self', None)):
self_dot_str: str = f'{self}.'
else:
self: callable = sensing_func
self_dot_str: str = ''
# private dict storing current sensing states
if (sensing_state_dict :=
getattr(self, sensing_state_dict_name, None)) is None: # noqa: E129,E501
setattr(self, sensing_state_dict_name, (sensing_state_dict := {}))
# tuple & str forms of input args
input_arg_tuple: tuple[tuple[str, Any], ...] = \
tuple(input_arg_dict_items := print_args.items())
input_arg_strs: list[str] = [f'{k}={v}' for k, v in input_arg_dict_items] # noqa: E501
if set is None:
return_annotation: Optional[type] = \
sensing_func.__annotations__.get('return')
return_annotation_str: str = (f': {return_annotation}'
if return_annotation
else '')
print_str: str = (f'SENSE: {self_dot_str}{sensing_func_name}'
f"({', '.join(input_arg_strs)})"
f'{return_annotation_str} = ')
# if input_arg_tuple is in current sensing states,
# then get and return corresponding value
if input_arg_tuple in sensing_state_dict:
value: Any = sensing_state_dict.get(input_arg_tuple)
if isinstance(value, list):
if not value:
return None
return_value: Any = value[0]
sensing_state_dict[input_arg_tuple] = value[1:]
else:
return_value: Any = value
print(f'{print_str}{return_value}')
elif interactive.ON:
# ask user for direct input
return_value: Any = json.loads(input(f'{print_str}? (in JSON) ')) # noqa: E501
else:
# return the sensing function's result
return_value: Any = result
print(f'{print_str}{return_value}')
global STATE_SEQ # pylint: disable=global-variable-not-assigned
STATE_SEQ.append((sensing_func.__qualname__, args_dict, return_value)) # noqa: E501
return return_value
# else: set the provided value in current sensing states
sensing_state_dict[input_arg_tuple] = set
print(f'SET: {self_dot_str}{sensing_state_dict_name}'
f"[{', '.join(input_arg_strs)}] = {set}")
return None
setattr(decor_sensing_func, _SENSE_DECOR_FLAG, True)
return decor_sensing_func | Agent-Behavior-Model | /Agent-Behavior-Model-23.1.25.tar.gz/Agent-Behavior-Model-23.1.25/src/abm/decor.py | decor.py |
from ast import (Name, Load, Store,
Assign, Call, Constant, Lambda, Module,
fix_missing_locations, parse, unparse)
from collections.abc import Callable
from copy import copy
from getpass import getuser
from inspect import stack
import os
from pathlib import Path
from pprint import pprint
from shutil import copyfile
from sys import executable
from tempfile import NamedTemporaryFile
from typing import Optional
from grader_support.gradelib import Grader
from grader_support.graderutil import change_directory
from grader_support.run import run
from codejail.jail_code import configure
configure(command='python', bin_path=executable, user=getuser())
# pylint: disable=wrong-import-position
from codejail.safe_exec import SafeExecException, safe_exec # noqa: E402
class StateSeqGrader(Grader):
"""State-Sequence Grader."""
__full_qual_name__: str = f'{__name__}.{__qualname__}'
_GRADER_VAR_NAME: str = 'grader'
_SUBMISSION_FILE_TEST_FUNC_VAR_NAME: str = 'SUBMISSION_FILE_TEST_FUNC'
_SUBMISSION_FILE_TEST_RESULT_VAR_NAME: str = \
f'{_SUBMISSION_FILE_TEST_FUNC_VAR_NAME}_RESULT'
_SUBMISSION_MODULE_NAME: str = '_submission'
_SUBMISSION_MODULE_FILE_NAME: str = f'{_SUBMISSION_MODULE_NAME}.py'
def __init__(self,
_unsafe_submission_file_test_func: Callable[[str | Path], bool], /): # noqa: E501
"""Initialize State-Sequence Grader."""
super().__init__()
self.add_input_check(check=self.check_submission_str)
if hasattr(self, 'set_only_check_input'): # S4V customization
self.set_only_check_input(value=True)
# stackoverflow.com/a/56764010
self.file_path: Path = Path(stack()[1].filename)
with open(file=self.file_path,
mode='rt',
buffering=-1,
encoding='utf-8',
errors='strict',
newline=None,
closefd=True,
opener=None) as file:
self.module: Module = parse(source=file.read(),
filename=self.file_path,
mode='exec',
type_comments=False,
feature_version=None)
# REQUIRED assignment to variable named `grader`
grader_assignment: Assign = self.module.body.pop(
next(i for i, node in enumerate(self.module.body)
if isinstance(node, Assign) and
node.targets[0].id == self._GRADER_VAR_NAME))
# REQUIRED instantiation of StateSeqGrader class instance
# with 1 single lambda positional argument
assert isinstance(submission_file_test_func_code :=
grader_assignment.value.args[0], Lambda), \
'*** SUBMISSION FILE TESTING FUNCTION MUST BE A LAMBDA ***'
self.module.body.append(
Assign(targets=[Name(id=self._SUBMISSION_FILE_TEST_FUNC_VAR_NAME, # noqa: E501
ctx=Store())],
value=submission_file_test_func_code,
type_comment=None))
def check_submission_str(self, submission_str: str, /) -> Optional[str]:
"""Test submission string."""
with NamedTemporaryFile(mode='wt',
buffering=-1,
encoding='utf-8',
newline=None,
suffix=None,
prefix=None,
dir=None,
delete=False,
errors='strict') as file:
file.write(submission_str)
(_module := copy(self.module)).body.append(
Assign(targets=[Name(id=self._SUBMISSION_FILE_TEST_RESULT_VAR_NAME,
ctx=Store())],
value=Call(func=Name(id=self._SUBMISSION_FILE_TEST_FUNC_VAR_NAME, # noqa: E501
ctx=Load()),
args=[Constant(value=file.name)],
keywords=[],
starargs=[],
kwargs=[]),
type_comment=None))
try:
safe_exec(code=(unparse(ast_obj=fix_missing_locations(node=_module)) # noqa: E501
.replace('__file__', f"'{self.file_path}'")),
globals_dict=(_globals := {}),
files=None,
python_path=None,
limit_overrides_context=None,
slug=self.__full_qual_name__,
extra_files=None)
return (None
if _globals[self._SUBMISSION_FILE_TEST_RESULT_VAR_NAME]
else '*** INCORRECT ***')
except SafeExecException as err:
return (('*** SUBMISSION TAKES TOO LONG TO RUN '
'(LIKELY INFINITE LOOP) ***')
if (complaint_str := str(err)) in (
"Couldn't execute jailed code: " # Linux
"stdout: b'', stderr: b'' with status code: -9",
"Couldn't execute jailed code: " # MacOS
"stdout: b'', stderr: b'' with status code: -24",
) # noqa: E123
else complaint_str)
finally:
os.remove(path=file.name)
def __call__(self, submission_file_path: str | Path, /,
*, submission_only: bool = False):
"""Run State-Sequence Grader."""
with change_directory(self.file_path.parent):
# pylint: disable=import-outside-toplevel
if submission_only:
copyfile(src=submission_file_path,
dst=self._SUBMISSION_MODULE_FILE_NAME,
follow_symlinks=True)
pprint(run(grader_name=self.file_path.stem,
submission_name=self._SUBMISSION_MODULE_NAME),
stream=None,
indent=2,
width=80,
depth=None,
compact=False,
sort_dicts=False,
underscore_numbers=True)
os.remove(path=self._SUBMISSION_MODULE_FILE_NAME)
else:
from xqueue_watcher.jailedgrader import main
main(args=(self.file_path.name, submission_file_path)) | Agent-Behavior-Model | /Agent-Behavior-Model-23.1.25.tar.gz/Agent-Behavior-Model-23.1.25/src/abm/open_edx_grader.py | open_edx_grader.py |
from collections.abc import Sequence
import json
from typing import Optional
import click
from abm.exec import (exec_and_get_state_seq as _exec_and_get_state_seq,
compare_output as _compare_output)
__all__: Sequence[str] = 'exec_and_get_state_seq', 'compare_output'
@click.command(name='exec',
cls=click.Command,
# Command kwargs
context_settings=None,
# callback=None,
# params=None,
help='Execute script and get State Sequence >>>',
epilog='^^^ Execute script and get State Sequence',
short_help='Execute script and get State Sequence',
options_metavar='[OPTIONS]',
add_help_option=True,
no_args_is_help=True,
hidden=False,
deprecated=False)
@click.argument('script_file_path',
type=str,
required=True,
default=None,
callback=None,
nargs=None,
# multiple=False,
metavar='SCRIPT_FILE_PATH',
expose_value=True,
is_eager=False,
envvar=None,
shell_complete=None)
def exec_and_get_state_seq(script_file_path: str):
"""Execute script and get State Sequence."""
return _exec_and_get_state_seq(module_obj_or_script_file_path=script_file_path) # noqa: E501
@click.command(name='compare-output',
cls=click.Command,
# Command kwargs
context_settings=None,
# callback=None,
# params=None,
help='Compare output of 2 functions or scripts >>>',
epilog='^^^ Compare output of 2 functions or scripts',
short_help='Compare output of 2 functions or scripts',
options_metavar='[OPTIONS]',
add_help_option=True,
no_args_is_help=True,
hidden=False,
deprecated=False)
@click.argument('scripts',
type=str,
required=True,
default=None,
callback=None,
nargs=2,
# multiple=False,
metavar='SCRIPT_FILES',
expose_value=True,
is_eager=False,
envvar=None,
shell_complete=None)
@click.option('--func',
show_default=True,
prompt=False,
confirmation_prompt=False,
prompt_required=True,
hide_input=False,
is_flag=False,
flag_value=None,
multiple=False,
count=False,
allow_from_autoenv=True,
help='Function Name',
hidden=False,
show_choices=True,
show_envvar=False,
type=str,
required=False,
default=None,
callback=None,
nargs=None,
# multiple=False,
metavar='FUNCTION_NAME',
expose_value=True,
is_eager=False,
envvar=None,
shell_complete=None)
@click.option('--context-file',
show_default=True,
prompt=False,
confirmation_prompt=False,
prompt_required=True,
hide_input=False,
is_flag=False,
flag_value=None,
multiple=False,
count=False,
allow_from_autoenv=True,
help='Context File Path',
hidden=False,
show_choices=True,
show_envvar=False,
type=str,
required=False,
default=None,
callback=None,
nargs=None,
# multiple=False,
metavar='CONTEXT_FILE_PATH',
expose_value=True,
is_eager=False,
envvar=None,
shell_complete=None)
@click.option('--func-args',
show_default=True,
prompt=False,
confirmation_prompt=False,
prompt_required=True,
hide_input=False,
is_flag=False,
flag_value=None,
multiple=False,
count=False,
allow_from_autoenv=True,
help='Function Arguments',
hidden=False,
show_choices=True,
show_envvar=False,
type=str,
required=False,
default=None,
callback=None,
nargs=None,
# multiple=False,
metavar='FUNCTION_ARGUMENTS',
expose_value=True,
is_eager=False,
envvar=None,
shell_complete=None)
def compare_output(scripts: tuple[str, str],
func: Optional[str] = None,
context_file: Optional[str] = None,
func_args: Optional[str] = None):
"""Compare output of 2 functions or scripts."""
if func_args:
func_args: dict | list = json.loads(s=func_args,
cls=None,
object_hook=None,
parse_float=None,
parse_int=None,
parse_constant=None,
object_pairs_hook=None)
return _compare_output(script_file_paths=scripts,
func_name=func,
context_file_path=context_file,
func_args=func_args) | Agent-Behavior-Model | /Agent-Behavior-Model-23.1.25.tar.gz/Agent-Behavior-Model-23.1.25/src/abm/cli/exec.py | exec.py |
import os
import numpy as np
import random
import torch
import torch.nn as nn
import torch.optim as optim
from collections import namedtuple, deque
import matplotlib.pyplot as plt
from typing import Union, List, Literal, Tuple
Transition = namedtuple('Transition',
('state', 'action', 'reward', 'next_state', 'done'))
class Transitions:
def __init__(self, maxlen: int) -> None:
self.transitions = deque([], maxlen=maxlen)
def append(self, transition) -> None:
self.transitions.append(transition)
def __len__(self) -> int:
return len(self.transitions)
def __getitem__(self, index) -> Transition:
return self.transitions[index]
def sample(self, count: int) -> List[Transition]:
return random.sample(self.transitions, count)
def sampleTensors(self, count: int, device: Literal['cpu', 'gpu']) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
transitions = random.sample(self.transitions, count)
states = torch.cat(
[i.state for i in transitions])
actions = torch.tensor(
[i.action for i in transitions], device=device)
rewards = torch.tensor(
[i.reward for i in transitions], device=device)
next_states = torch.cat(
[i.next_state for i in transitions])
dones = torch.tensor(np.array(
[i.done for i in transitions], dtype=int), device=device)
states = states if len(states.shape) > 1 else states.view(count, -1)
actions = actions if len(
actions.shape) > 1 else actions.view(count, -1)
rewards = rewards if len(
rewards.shape) > 1 else rewards.view(count, -1)
next_states = next_states if len(
next_states.shape) > 1 else next_states.view(count, -1)
dones = dones if len(dones.shape) > 1 else dones.view(count, -1)
return states, actions, rewards, next_states, dones
class DeepQAgent:
def __init__(self,
env,
policy_network: nn.Module,
target_network: nn.Module,
optimizer: optim.Optimizer,
loss_function,
device: Literal['cpu', 'gpu'] = 'cpu',
state_processor=None,
greedy_function=lambda x: 0.2,
replay_size: int = 50000,
batch_size: int = 64,
gamma: float = 0.95,
target_update_rate: int = 1000) -> None:
self.env = env
self.policy_network = policy_network
self.target_network = target_network
self.optimizer = optimizer
self.loss_function = loss_function
self.device = device
self.greedy_function = greedy_function
self.batch_size = batch_size
self.gamma = gamma
self.target_update_rate = target_update_rate
self.action_size = env.action_space.n
self.replay_buffer = Transitions(replay_size)
if state_processor is not None:
self.state_processor = state_processor
else:
self.state_processor = lambda x: torch.tensor(
x, dtype=torch.float32, device=device)
self.update_target_network()
self.target_network.eval()
def update_target_network(self) -> None:
self.target_network.load_state_dict(self.policy_network.state_dict())
def select_action(self, state: torch.Tensor, epsilon: float) -> int:
if random.uniform(0, 1) > epsilon:
with torch.no_grad():
self.policy_network.eval()
action = torch.argmax(self.policy_network(state)).item()
return action
else:
return np.random.randint(self.action_size)
def optimize(self) -> None:
self.policy_network.train()
batch_states, batch_actions, batch_rewards, batch_next_states, batch_dones = self.replay_buffer.sampleTensors(
self.batch_size, self.device)
q = torch.take_along_dim(self.policy_network(
batch_states), batch_actions.view(-1, 1), dim=1)
expected_q = batch_rewards + self.gamma * \
self.target_network(batch_next_states).amax(
dim=1).unsqueeze(1) * (1 - batch_dones.float())
loss = self.loss_function(q, expected_q)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def plot_returns(self, name: str, returns: List[int], average_window: int, show: bool = True) -> None:
plt.clf()
plt.plot(returns, label='Episode Returns')
if len(returns) >= average_window:
y = np.convolve(returns, np.ones(average_window),
'valid') / average_window
x = np.arange(y.shape[0]) + average_window
plt.plot(x, y, label='%u Episode Avg. Returns' % average_window)
plt.xlabel('Episode')
plt.ylabel('Return')
plt.legend(loc='upper left')
plt.savefig('%s_returns.png' % name)
if show:
plt.ion()
plt.figure(1)
plt.show()
plt.pause(0.001)
def train(self, name: str = 'agent', average_window: int = 20, max_episodes: int = 100, return_goal: float = 10e9, plot_returns: bool = False, render_rate: int = 0, save_rate: int = 10) -> None:
if not os.path.exists('models'):
os.makedirs('models')
episode_returns = []
episode_average_window = deque(maxlen=average_window)
step_count = 0
for episode in range(max_episodes):
done = False
episode_return = 0
state = self.state_processor(self.env.reset())
while done is not True:
step_count += 1
if render_rate > 0 and (episode % render_rate) == 0:
self.env.render()
action = self.select_action(
state, self.greedy_function(episode))
next_state, reward, done, _ = self.env.step(action)
next_state = self.state_processor(next_state)
self.replay_buffer.append(Transition(
state, action, reward, next_state, done))
if len(self.replay_buffer) >= self.batch_size:
self.optimize()
if (step_count % self.target_update_rate) == 0:
self.update_target_network()
state = next_state
episode_return += reward
episode_returns.append(episode_return)
episode_average_window.append(episode_return)
print('\rEpisode: %8u, Return (%8u episode averaged): %8u' %
(episode + 1, average_window, np.mean(episode_average_window)), end='')
self.plot_returns(name, episode_returns,
average_window, plot_returns)
if save_rate != 0 and (episode % save_rate) == 0:
torch.save(self.target_network.state_dict(), 'models/%s_%08u.pt' %
(name, episode + 1))
if len(episode_returns) > average_window and np.mean(episode_returns[:-average_window]) >= return_goal:
break
print('\n')
class ActorCriticAgent:
def __init__(self,
env,
actor_network: nn.Module,
critic_network: nn.Module,
actor_optimizer: optim.Optimizer,
critic_optimizer: optim.Optimizer,
loss_function,
device: Literal['cpu', 'gpu'] = 'cpu',
state_processor=None,
gamma: float = 0.95,
entropy_function=lambda x: 0.01,
) -> None:
self.env = env
self.actor_network = actor_network
self.critic_network = critic_network
self.actor_optimizer = actor_optimizer
self.critic_optimizer = critic_optimizer
self.loss_function = loss_function
self.device = device
self.gamma = gamma
self.entropy_function = entropy_function
self.transitions = Transitions(1)
if state_processor is not None:
self.state_processor = state_processor
else:
self.state_processor = lambda x: torch.tensor(
x, dtype=torch.float32, device=device)
def select_action(self, state: torch.Tensor) -> Tuple[float, float]:
self.actor_network.eval()
return self.actor_network(state)
def optimize(self, entropy_weight: float) -> Tuple[float, float]:
self.actor_network.train()
self.critic_network.train()
transition = self.transitions[0]
state, action, reward, next_state, done = transition.state, transition.action, transition.reward, transition.next_state, transition.done
log_probability = action[1].log_prob(action[0]).sum(dim=-1)
predicted_value = self.critic_network(state)
target_value = reward + self.gamma * \
self.critic_network(next_state) * (1 - done)
critic_loss = self.loss_function(
predicted_value, target_value.detach())
self.critic_optimizer.zero_grad()
critic_loss.backward()
self.critic_optimizer.step()
advantage = (target_value - predicted_value).detach()
actor_loss = - advantage * log_probability
actor_loss += -entropy_weight * log_probability
self.actor_network.zero_grad()
actor_loss.backward()
self.actor_optimizer.step()
return actor_loss.item(), critic_loss.item()
def plot_returns(self, name: str, returns: List[int], average_window: int, losses: List, show: bool = True) -> None:
losses = np.array(losses)
plt.clf()
plt.subplot(3, 1, 1)
plt.plot(returns, label='Episode Returns')
plt.subplot(3, 1, 2)
plt.plot(losses[:, 0], label='Actor Losses')
plt.subplot(3, 1, 3)
plt.plot(losses[:, 1], label='Critic Losses')
if len(returns) >= average_window:
y = np.convolve(returns, np.ones(average_window),
'valid') / average_window
x = np.arange(y.shape[0]) + average_window
plt.subplot(3, 1, 1)
plt.plot(x, y, label='%u Episode Avg. Returns' % average_window)
plt.xlabel('Episode')
plt.ylabel('Return')
plt.legend(loc='upper left')
plt.savefig('%s_returns.png' % name)
if show:
plt.ion()
plt.figure(1)
plt.show()
plt.pause(0.001)
def train(self, name: str = 'agent', average_window: int = 20, max_episodes: int = 100, return_goal: float = 10e9, plot_returns: bool = False, render_rate: int = 0, save_rate: int = 10) -> None:
episode_returns = []
step_losses = []
episode_average_window = deque(maxlen=average_window)
step_count = 0
episode = -1
while True:
episode += 1
done = False
episode_return = 0
state = self.state_processor(self.env.reset())
while done is not True:
step_count += 1
if render_rate > 0 and (episode % render_rate) == 0:
self.env.render()
action = self.select_action(state)
next_state, reward, done, _ = self.env.step(
action[0].cpu().detach().numpy())
next_state = self.state_processor(next_state)
self.transitions.append(Transition(
state, action, reward, next_state, done))
losses = self.optimize(self.entropy_function(episode))
state = next_state
episode_return += reward
step_losses.append(losses)
episode_returns.append(episode_return)
episode_average_window.append(episode_return)
print('\rEpisode: %8u, Return (%8u episode averaged): %8u' %
(episode + 1, average_window, np.mean(episode_average_window)), end='')
self.plot_returns(name, episode_returns,
average_window, step_losses, plot_returns)
if save_rate != 0 and (episode % save_rate) == 0:
torch.save(self.target_network.state_dict(), 'models/%s_%08u.pt' %
(name, episode + 1))
if (episode + 1) >= max_episodes or (len(episode_returns) > average_window and np.mean(episode_returns[:-average_window]) >= return_goal):
break
print('\n') | Agent-Smith | /Agent_Smith-0.1.1-py3-none-any.whl/AgentSmith/Agents.py | Agents.py |
import os
import pickle
from paddle import inference
MODEL_FILE = "model.AgentEncryption"
PARAMS_FILE = "params.AgentEncryption"
OPT_FILE = "opt.AgentEncryption"
class BaseEncryptOp:
def __init__(self, *args, **kwargs):
pass
def encoder(self, text, *args, **kwargs) -> bytes:
"""
定义加密流程
"""
pass
def prepare(self, save_path):
pass
def get_param(self) -> dict:
"""
客户端额外所需的解密信息,此处请勿返回任何公钥与私钥内容
"""
pass
@staticmethod
def decoder(text, *args, **kwargs) -> bytes:
"""
定义解密流程
"""
pass
class BaseEncryptModelMaker:
def __init__(self,
model_path,
param_path,
save_path,
encrypt_op: BaseEncryptOp):
"""
模型加密基类 - 当前仅适配Combine模型
:param model_path: 模型文件路径
:param param_path: 参数文件路径
:param save_path: 加密后模型文件保存路径
:param encrypt_op: 加密相关OP
"""
self.graph_path = model_path
self.params_path = param_path
self.save_path = save_path
self.encrypt_op = encrypt_op
self.graph = None
self.params = None
def pack(self) -> None:
"""
序列化解密流程func
"""
with open(os.path.join(self.save_path, OPT_FILE), "wb") as file:
pickle.dump([self.encrypt_op.decoder, self.encrypt_op.get_param()], file)
def load(self):
with open(self.graph_path, "rb") as graph_file:
self.graph = graph_file.read()
with open(self.params_path, "rb") as params_file:
self.params = params_file.read()
def save(self):
os.makedirs(self.save_path, exist_ok=True)
with open(os.path.join(self.save_path, MODEL_FILE), "wb") as graph_file:
graph_file.write(self.graph)
with open(os.path.join(self.save_path, PARAMS_FILE), "wb") as params_file:
params_file.write(self.params)
def make(self):
self.load()
self.encrypt_op.prepare(self.save_path)
self.graph = self.encrypt_op.encoder(self.graph)
self.params = self.encrypt_op.encoder(self.params)
self.pack()
self.save()
class BaseEncryptConfigMaker:
def __init__(self, load_path, config: inference.Config = None):
self.load_path = load_path
self.config = config
# 占位符
self.graph_path = None
self.params_path = None
self.op_path = None
self.graph = None
self.params = None
self.op_func = None
self.op_param = None
# 准备工作
self.prepare()
def prepare(self):
# 提前做个prepare,以后方便做拓展
if not self.config:
self.config = inference.Config()
if not self.graph_path:
self.graph_path = os.path.join(self.load_path, MODEL_FILE)
if not self.params_path:
self.params_path = os.path.join(self.load_path, PARAMS_FILE)
if not self.op_path:
self.op_path = os.path.join(self.load_path, OPT_FILE)
def load(self):
with open(self.graph_path, "rb") as graph_file:
self.graph = graph_file.read()
with open(self.params_path, "rb") as params_file:
self.params = params_file.read()
with open(self.op_path, "rb") as file:
self.op_func, self.op_param = pickle.load(file)
def make(self, **kwargs):
self.load()
self.graph = self.op_func(self.graph, self, **self.op_param, **kwargs)
self.params = self.op_func(self.params, self, **self.op_param, **kwargs)
self.config.set_model_buffer(self.graph, len(self.graph), self.params, len(self.params))
# 返回加载情况
return self.config.model_from_memory()
@property
def get_config(self):
# 获取Config
return self.config
EncryptConfigMaker = BaseEncryptConfigMaker | AgentEnc | /AgentEnc-0.1-py3-none-any.whl/agentenc/base.py | base.py |
import cv2
import numpy as np
from agentfc.collector import Collector
from agentfc.facedet import get_face, face_seg
class FaceCollector:
def __init__(self,
inp,
save_path: str,
op,
mask=True,
pad=128):
if isinstance(inp, str):
inp = cv2.imread(inp)
self.inp = inp
self.save_path = save_path
self.mask = mask
self.pad = pad
assert hasattr(op, "__call__"), AssertionError("op不可调用,请检查传入的op是否支持op()操作")
self.op = op
def pretreatment(self, frame):
clip, box, seg = get_face(frame, self.mask, self.pad)
cr = Collector(frame, clip, box, seg)
return cr
@staticmethod
def mix(cr):
seg = face_seg(cr.out)
box = cr.c_box
clip = cr.c_im[box.top:box.bottom, box.left:box.right, :]
c_seg = np.array([seg] * clip.shape[-1], dtype="uint8").transpose([1, 2, 0])
clip[c_seg == 1] = cr.out[c_seg == 1]
cr.c_im[box.top:box.bottom, box.left:box.right, :] = clip.copy()
return cr.c_im
def mk_img(self):
cr = self.pretreatment(self.inp)
# 自定义操作
out = self.op(cr.c_clip_im)
cr.set_out(out)
# 后处理
final = self.mix(cr)
if self.save_path:
cv2.imwrite(self.save_path, final)
return final
def mk_mp4(self):
cap = cv2.VideoCapture(self.inp)
fps = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
output_movie = cv2.VideoWriter(self.save_path, fourcc, fps, (height, width))
idx = 0
while cap.isOpened():
ret, frame = cap.read()
if frame is None:
break
print(f"正在处理{idx}帧")
idx += 1
# 前处理
cr = self.pretreatment(frame)
# 自定义操作
out = self.op(cr.c_clip_im)
cr.set_out(out)
# 后处理
final = self.mix(cr)
output_movie.write(final)
cap.release()
output_movie.release()
print("处理完毕") | AgentFC | /AgentFC-0.4-py3-none-any.whl/agentfc/__init__.py | __init__.py |
A project for Third party login
目前只支持 腾讯QQ,微信,微博 第三方登录
安装 pip install AgentLogin
from AgentLogin import AgentLogin
qq_url = AgentLogin.qq_url(client_id, redirect_uri)
把这个qq_url链接放到你的<a href="{{ qq_url }}">QQ登录<a>
(user, user_id) = AgentLogin.qq(client_id, client_secret, redirect_uri, code)
code: 用户授权登录回调参数code
client_id:腾讯开放平台上app的APPID名
client_secret: 腾讯开放平台上app的secret名
redirect_uri: 腾讯开放平台上app的回调url
user: 返回qq的用户名
有使用AgentLogin的项目:http://120.78.176.77, http://101.132.132.181:8080
如有疑问不会使用 请联系作者:[email protected] | AgentLogin | /AgentLogin-3.0.0.tar.gz/AgentLogin-3.0.0/README.md | README.md |
import re
import random
from lxml import etree
from six import string_types
def schema(relaxng):
"""
Parse a RelaxNG schema document and return an etree instance of it
:param relaxng: The RelaxNG schema as a string
:type relaxng: str
:return: LXML etree RelaxNG instance
:rtype : etree.RelaxNG
"""
tree = etree.fromstring(relaxng)
return etree.RelaxNG(tree)
def weighted_choice(choices):
"""
Provides a weighted version of random.choice
:param choices: A dictionary of choices, with the choice as the key and weight the value
:type choices: list of tuple of (str, int)
"""
total = sum(weight for choice, weight in choices)
rand = random.uniform(0, total)
most = 0
for choice, weight in choices:
if most + weight > rand:
return choice
most += weight
def normalize(string, pattern=False, preserve_case=False):
"""
Normalize input for comparison with other input
:param string: The string to normalize
:type string: str
:param pattern: Allow wildcard symbols for triggers
:type pattern: bool
:param preserve_case: Normalize the message without casefolding
:type preserve_case: bool
:rtype: str
"""
regex = re.compile(r'([^\s\w\(\)\[\]\|\*#])+') if pattern else re.compile(r'([^\s\w]|_)+')
if not isinstance(string, string_types):
return ''
# Case folding is not supported in Python2
try:
string = string.strip() if preserve_case else string.strip().casefold()
except AttributeError:
string = string.strip() if preserve_case else string.strip().lower()
return regex.sub('', string)
def attribute(element, attribute, default=None):
"""
Returns the value of an attribute, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param attribute: The name of the attribute to evaluate
:type attribute: basestring
:param default: The default value to return if the attribute is not defined
"""
attribute_value = element.get(attribute)
return attribute_value if attribute_value is not None else default
def bool_attribute(element, attribute, default=True):
"""
Returns the bool value of an attribute, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param attribute: The name of the attribute to evaluate
:type attribute: str
:param default: The default boolean to return if the attribute is not defined
:type default: bool
:rtype: bool
"""
attribute_value = element.get(attribute)
if attribute_value:
return attribute_value == 'true'
return default
def int_attribute(element, attribute, default=0):
"""
Returns the int value of an attribute, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param attribute: The name of the attribute to evaluate
:type attribute: basestring
:param default: The default value to return if the attribute is not defined
:type default: int
:rtype: int
"""
attribute_value = element.get(attribute)
if attribute_value:
try:
return int(attribute_value)
except (TypeError, ValueError):
return default
return default
def element(element, name, default=None):
"""
Returns the value of an element, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param name: The name of the element to evaluate
:type name: str
:param default: The default value to return if the element is not defined
"""
element_value = element.find(name)
return element_value.text if element_value is not None else default
def bool_element(element, name, default=True):
"""
Returns the bool value of an element, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param name: The name of the element to evaluate
:type name: str
:param default: The default value to return if the element is not defined
:type default: bool
"""
element_value = element.find(name)
if element_value is not None:
return element_value.text == 'true'
return default
def int_element(element, name, default=0):
"""
Returns the int value of an element, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param name: The name of the element to evaluate
:type name: str
:param default: The default value to return if the element is not defined
:type default: int
:rtype: int
"""
element_value = element.find(name)
if element_value is not None:
try:
return int(element_value.text)
except (TypeError, ValueError):
return default
return default
def newlines_to_spaces(text):
"""
Strips newlines and any spacing surrounding the newlines and replaces them with a single space
:param text: The text to parse
:type text: str
"""
newline_pattern = re.compile('\s*\n\s*')
return newline_pattern.sub(' ', text) | AgentML | /AgentML-0.3.1.tar.gz/AgentML-0.3.1/agentml/common.py | common.py |
import logging
from collections import deque
class InternalLogger(object):
def __init__(self, max_entries=100):
"""
Initialize a new base Internal Logger instance
:param max_entries: The maximum number of log entries to retain at any given time
:type max_entries: int
"""
self._max_entries = max_entries
self._log_entries = deque(maxlen=self._max_entries)
self._debug_log = logging.getLogger('agentml.logger')
def add(self, *args, **kwargs):
raise NotImplementedError('This logger class has not implemented support for adding log entries')
@property
def entries(self):
"""
Return all log entries as a tuple (this is to prevent any outside manipulation of the deque instance)
:rtype: tuple
"""
return tuple(self._log_entries)
def most_recent(self):
"""
Fetch the most recent log entry
"""
return self._log_entries[0] if len(self._log_entries) else None
@property
def max_entries(self):
"""
Return the currently configured maximum number of log entries
:rtype: int or None
"""
return self._max_entries
@max_entries.setter
def max_entries(self, entries):
"""
Chance the maximum number of retained log entries
:param entries: The maximum number of log entries to retain at any given time
:type entries: int
"""
self._debug_log.info('Changing maximum log entries from {old} to {new}'
.format(old=self._log_entries, new=entries))
self._max_entries = entries
# This is a bit awkward, but since the maxlen can't be changed after instantiation, we have to reverse the
# deque before re-instantiating it, then reverse the new deque back in order to preserve the reverse order
# in case any entries are truncated
self._log_entries.reverse()
self._log_entries = deque(self._log_entries, maxlen=self._max_entries)
self._log_entries.reverse()
@max_entries.deleter
def max_entries(self):
"""
Removes the maximum entry limit
"""
self._debug_log.info('Removing maximum entries restriction')
self._log_entries(deque(self._log_entries))
###############
# Requests #
###############
class RequestLogger(InternalLogger):
def __init__(self, max_entries=100):
"""
Initialize a new Request Logger instance
:param max_entries: The maximum number of log entries to retain at any given time
:type max_entries: int
"""
super(RequestLogger, self).__init__(max_entries)
self._debug_log = logging.getLogger('agentml.logger.requests')
def add(self, user, message, groups):
"""
Add a new log entry
:param user: The requesting user
:type user: agentml.User
:param message: The request Message instance
:type message: agentml.Message
:param groups: The request groups
:type groups: set
:return: The logged Request instance
:rtype : Request
"""
self._debug_log.debug('Logging new Request entry')
request = Request(user, message, groups)
self._log_entries.appendleft(request)
return request
class Request:
def __init__(self, user, message, groups, response=None):
"""
Initialize a new log Request instance
:param user: The requesting user
:type user: agentml.User
:param message: The request message
:type message: agentml.Message or basestring
:param groups: The request groups
:type groups: set
:param response: The Response associated with this Request
:type response: Response or None
"""
self.user = user
self.message = message
self.groups = groups
self.response = response
def __str__(self):
return self.message
###############
# Responses #
###############
class ResponseLogger(InternalLogger):
def __init__(self, max_entries=100):
"""
Initialize a new Response Logger instance
:param max_entries: The maximum number of log entries to retain at any given time
:type max_entries: int
"""
super(ResponseLogger, self).__init__(max_entries)
self._debug_log = logging.getLogger('agentml.logger.responses')
def add(self, message, request):
"""
Add a new log entry
:param message: The request message
:type message: str
:param request: The Request associated with this response
:type request: Request or None
:return: The logged Response instance
:rtype : Response
"""
self._debug_log.debug('Logging new Response entry')
response = Response(message, request)
self._log_entries.appendleft(response)
return response
class Response:
def __init__(self, message, request=None):
"""
Initialize a new log Request instance
:param message: The response message
:type message: str
:param request: The Request associated with this Response
:type request: Request or None
"""
self.message = message
self.request = request
def __str__(self):
return self.message | AgentML | /AgentML-0.3.1.tar.gz/AgentML-0.3.1/agentml/logger.py | logger.py |
from __future__ import print_function, unicode_literals
from six import string_types
import os
import re
import logging
from time import time
from lxml import etree
# from typewriter import typewrite
from agentml.common import schema, normalize, attribute, int_attribute, newlines_to_spaces
from agentml.parser.init import Init
from agentml.parser.trigger import Trigger
from agentml.parser.tags import Condition, Redirect, Random, Var, Tag
from agentml.parser.trigger.condition.types import UserVarType, GlobalVarType, TopicType, UserType, ConditionType
from agentml.logger import RequestLogger, ResponseLogger
from agentml.constants import AnyGroup
from agentml.errors import AgentMLError, VarNotDefinedError, UserNotDefinedError, ParserBlockingError, LimitError
__author__ = "Makoto Fujimoto"
__copyright__ = 'Copyright 2015, Makoto Fujimoto'
__license__ = "MIT"
__version__ = "0.3.1"
__maintainer__ = "Makoto Fujimoto"
class AgentML:
def __init__(self, log_level=logging.WARN):
"""
Initialize a new AgentML instance
:param log_level: The debug logging level, defaults to logging.WARN
:type log_level: int
"""
# Debug logger
self._log = logging.getLogger('agentml')
self._log.setLevel(log_level)
log_formatter = logging.Formatter("[%(asctime)s] %(levelname)s.%(name)s: %(message)s")
console_logger = logging.StreamHandler()
console_logger.setLevel(log_level)
console_logger.setFormatter(log_formatter)
self._log.addHandler(console_logger)
# Paths
self.script_path = os.path.dirname(os.path.realpath(__file__))
self._schema_path = os.path.join(self.script_path, 'schemas', 'agentml.rng')
# Schema validator
with open(self._schema_path) as file:
self._schema = schema(file.read())
# Define our base / system tags
self._tags = {'condition': Condition, 'redirect': Redirect, 'random': Random, 'var': Var}
self.conditions = {'user_var': UserVarType(), 'global_var': GlobalVarType(), 'topic': TopicType(),
'user': UserType()}
# Containers
self._global_vars = {}
self._limits = {}
self._users = {}
self._triggers = {}
self._substitutions = []
# Loggers
self.request_log = RequestLogger()
self.response_log = ResponseLogger()
# Triggers must be sorted before replies are retrieved
self.sorted = False
self._sorted_triggers = []
# Load internal AgentML files
self.load_directory(os.path.join(self.script_path, 'intelligence'))
def load_directory(self, dir_path):
"""
Load all AgentML files contained in a specified directory
:param dir_path: Path to the directory
:type dir_path: str
"""
self._log.info('Loading all AgentML files contained in: ' + dir_path)
# Get a list of file paths
aml_files = []
for root, dirs, files in os.walk(dir_path):
aml_files += ['{root}/{file}'.format(root=root, file=file)
for file in sorted(files) if file.endswith('.aml')]
# Loop through the files and load each one individually
for file in aml_files:
self.load_file(file)
def load_file(self, file_path):
"""
Load a single AgentML file
:param file_path: Path to the file
:type file_path: str
"""
self._log.info('Loading file: ' + file_path)
agentml = etree.parse(file_path)
# Validate the file for proper AgentML syntax
self._schema.assertValid(agentml)
# Get our root element and parse all elements inside of it
root = etree.parse(file_path).getroot()
defaults = {}
def parse_element(element):
for child in element:
# Initialization
if child.tag == 'init':
Init(self, child, file_path)
# Set the group
if child.tag == 'group':
self._log.info('Setting Trigger group: {group}'.format(group=child.get('name')))
defaults['groups'] = {child.get('name')} # TODO
parse_element(child)
del defaults['groups']
continue
# Set the topic
if child.tag == 'topic':
self._log.info('Setting Trigger topic: {topic}'.format(topic=child.get('name')))
defaults['topic'] = child.get('name')
parse_element(child)
del defaults['topic']
continue
# Set the emotion
if child.tag == 'emotion':
self._log.info('Setting Trigger emotion: {emotion}'.format(emotion=child.get('name')))
defaults['emotion'] = child.get('name')
parse_element(child)
del defaults['emotion']
continue
# Parse a standard Trigger element
if child.tag == 'trigger':
try:
self.add_trigger(Trigger(self, child, file_path, **defaults))
except AgentMLError:
self._log.warn('Skipping Trigger due to an error', exc_info=True)
# Begin element iteration by parsing the root element
parse_element(root)
def sort(self):
"""
Sort triggers and their associated responses
"""
# Sort triggers by word and character length first
for priority, triggers in self._triggers.items():
self._log.debug('Sorting priority {priority} triggers'.format(priority=priority))
# Get and sort our atomic and wildcard patterns
atomics = [trigger for trigger in triggers if trigger.pattern_is_atomic]
wildcards = [trigger for trigger in triggers if not trigger.pattern_is_atomic]
atomics = sorted(atomics, key=lambda trigger: (trigger.pattern_words, trigger.pattern_len), reverse=True)
wildcards = sorted(wildcards, key=lambda trigger: (trigger.pattern_words, trigger.pattern_len),
reverse=True)
# Replace our sorted triggers
self._triggers[priority] = atomics + wildcards
# Finally, sort triggers by priority
self._sorted_triggers = []
for triggers in [self._triggers[priority] for priority in sorted(self._triggers.keys(), reverse=True)]:
for trigger in triggers:
self._sorted_triggers.append(trigger)
self.sorted = True
def get_reply(self, user, message, groups=None):
"""
Attempt to retrieve a reply to the provided message
:param user: The user / client. This can be a hostmask, IP address, database ID or any other unique identifier
:type user: str
:param message: The message to retrieve a reply to
:type message: string_types
:param groups: The trigger groups to search, defaults to only matching non-grouped triggers
:type groups: set or AnyGroup
:rtype: str or None
"""
# Make sure triggers have been sorted since the most recent trigger was added
if not self.sorted:
self.sort()
user = self.get_user(user)
groups = groups or {None}
# Log this request
message = Message(self, message)
request_log_entry = self.request_log.add(user, message, groups)
# Fetch triggers in our topic and make sure we're not in an empty topic
triggers = [trigger for trigger in self._sorted_triggers if user.topic == trigger.topic]
if not triggers and user.topic is not None:
self._log.warn('User "{user}" was in an empty topic: {topic}'.format(user=user.id, topic=user.topic))
user.topic = None
triggers = [trigger for trigger in self._sorted_triggers if user.topic == trigger.topic]
# It's impossible to get anywhere if there are no empty topic triggers available to guide us
if not triggers:
raise AgentMLError('There are no empty topic triggers defined, unable to continue')
# Fetch triggers in our group and make sure we're not in an empty topic
if groups is not AnyGroup:
triggers = [trigger for trigger in triggers if groups.issuperset(trigger.groups or {None})]
if not triggers:
if not user.topic:
self._log.info('There are no topicless triggers matching the specific groups available, giving up')
return
self._log.info('The topic "{topic}" has triggers, but we are not in the required groups to match them. '
'Resetting topic to None and retrying'.format(topic=user.topic, groups=str(groups)))
user.topic = None
triggers = [trigger for trigger in self._sorted_triggers if user.topic == trigger.topic]
for trigger in triggers:
try:
match = trigger.match(user, message)
except ParserBlockingError:
return
if match:
message = str(match)
request_log_entry.response = self.response_log.add(message, request_log_entry)
return message
# If we're still here, no reply was matched. If we're in a topic, exit and retry
if user.topic:
self._log.info('No reply matched in the topic "{topic}", resetting topic to None and retrying'
.format(topic=user.topic))
user.topic = None
# noinspection PyTypeChecker
return self.get_reply(user.id, message.raw)
def add_trigger(self, trigger):
"""
Add a new trigger
:param trigger: The Trigger object
:type trigger: Trigger
"""
# Make sure triggers are re-sorted before a new reply can be requested
self.sorted = False
# If no trigger with this priority level has been defined yet, create a new list
if trigger.priority not in self._triggers:
self._triggers[trigger.priority] = [trigger]
return
# Otherwise, add this trigger to an existing priority list
self._triggers[trigger.priority].append(trigger)
def set_substitution(self, word, substitution):
"""
Add a word substitution
:param word: The word to replace
:type word: str
:param substitution: The word's substitution
:type substitution: str
"""
# Parse the word and its substitution
raw_word = re.escape(word)
raw_substitution = substitution
case_word = re.escape(normalize(word, preserve_case=True))
case_substitution = normalize(substitution, preserve_case=True)
word = re.escape(normalize(word))
substitution = normalize(substitution)
# Compile and group the regular expressions
raw_sub = (re.compile(r'\b{word}\b'.format(word=raw_word), re.IGNORECASE), raw_substitution)
case_sub = (re.compile(r'\b{word}\b'.format(word=case_word), re.IGNORECASE), case_substitution)
sub = (re.compile(r'\b{word}\b'.format(word=word), re.IGNORECASE), substitution)
sub_group = (sub, case_sub, raw_sub)
# Make sure this substitution hasn't already been processed and add it to the substitutions list
if sub_group not in self._substitutions:
self._log.info('Appending new word substitution: "{word}" => "{sub}"'.format(word=word, sub=substitution))
self._substitutions.append(sub_group)
# noinspection PyUnboundLocalVariable
def parse_substitutions(self, messages):
"""
Parse substitutions in a supplied message
:param messages: A tuple messages being parsed (normalized, case preserved, raw)
:type messages: tuple of (str, str, str)
:return: Substituted messages (normalized, case preserved, raw)
:rtype : tuple of (str, str, str)
"""
# If no substitutions have been defined, just normalize the message
if not self._substitutions:
self._log.info('No substitutions to process')
return messages
self._log.info('Processing message substitutions')
def substitute(sub_group, sub_message):
word, substitution = sub_group
return word.sub(substitution, sub_message)
normalized, preserve_case, raw = messages
for sub_normalized, sub_preserve_case, sub_raw in self._substitutions:
normalized = substitute(sub_normalized, normalized)
preserve_case = substitute(sub_preserve_case, preserve_case)
raw = substitute(sub_raw, raw)
return normalized, preserve_case, raw
def get_var(self, name, user=None):
"""
Retrieve a global or user variable
:param name: The name of the variable to retrieve
:type name: str
:param user: If retrieving a user variable, the user identifier
:type user: str or None
:rtype: str
:raises UserNotDefinedError: The specified user does not exist
:raises VarNotDefinedError: The requested variable has not been defined
"""
# Retrieve a user variable
if user is not None:
if user not in self._users:
raise UserNotDefinedError
return self._users[user].get_var(name)
# Retrieve a global variable
if name not in self._global_vars:
raise VarNotDefinedError
return self._global_vars[name]
def set_var(self, name, value, user=None):
"""
Set a global or user variable
:param name: The name of the variable to set
:type name: str
:param value: The value of the variable to set
:type value: str
:param user: If defining a user variable, the user identifier
:type user: str
:raises UserNotDefinedError: The specified user does not exist
"""
# Set a user variable
if user is not None:
if user not in self._users:
raise UserNotDefinedError
self._users[user].set_var(name, value)
return
# Set a global variable
self._global_vars[name] = value
def set_limit(self, identifier, expires_at, blocking=False):
"""
Set a new global trigger or response limit
:param identifier: The Trigger or Response object
:type identifier: parser.trigger.Trigger or parser.trigger.response.Response
:param expires_at: The limit expiration as a Unix timestamp
:type expires_at: float
:param blocking: When True and a limit is triggered, no other Trigger or Response's will be attempted
:type blocking: bool
"""
self._limits[identifier] = (expires_at, blocking)
def clear_limit(self, identifier=None):
"""
Remove a single limit or all defined limits
:param identifier: The identifier to clear limits for, or if no identifier is supplied, clears ALL limits
:type identifier: int
:return: True if a limit was successfully found and removed, False if no limit could be matched for removal
:rtype : bool
"""
# Remove a single limit
if identifier:
if identifier in self._limits:
del self._limits[identifier]
return True
else:
return False
# Remove all limits
if self._limits:
self._limits.clear()
return True
else:
return False
def is_limited(self, identifier):
"""
Test whether or not there is an active global limit for the specified Trigger or Response instance
:param identifier: The Trigger or Response object
:type identifier: parser.trigger.Trigger or parser.trigger.response.Response
:return: True if there is a limit enforced, otherwise False
:rtype : bool
"""
# If there is a limit for this Trigger assigned, make sure it hasn't expired
if identifier in self._limits:
limit, blocking = self._limits[identifier]
if time() < limit:
# Limit exists and is active, return True
self._log.debug('Global limit enforced for Object {oid}'
.format(oid=id(identifier)))
if blocking:
raise LimitError
return True
else:
# Limit has expired, remove it
del self._limits[identifier]
# We're still here, so there are no active limits. Return False
self._log.debug('No global limit enforced for Object {oid}'.format(oid=id(identifier)))
return False
def get_user(self, identifier):
# Does this user already exist?
if identifier in self._users:
return self._users[identifier]
# User does not exist, so let's create a new one
self._users[identifier] = User(identifier)
return self._users[identifier]
def add_condition(self, name, cond_class):
"""
Add a new custom condition type parser
:param name: The name of the condition type
:type name: str
:param cond_class: The Class
:return:
"""
# Has this condition type already been defined?
if name in self.conditions:
self._log.warn('Overwriting an existing Condition Type class: {type}'.format(type=name))
if not issubclass(cond_class, ConditionType):
self._log.error('Condition Type class must implement the base ConditionType interface, please review the '
'documentation on defining custom condition types. (Refusing to set the condition type '
'"{type}")'.format(type=name))
return
self.conditions[name] = cond_class(name)
def set_tag(self, name, tag_class):
"""
Define a new tag parser method
:param name: The name of the tag
:type name: str
:param tag_class: The Tag class, this must be a subclass of base parser.tags.Tag
:type tag_class: Tag
"""
# Has this tag already been defined?
if name in self._tags:
self._log.warn('Overwriting an existing Tag class: {tag}'.format(tag=name))
# Make sure the tag class adhered to the base Tag interface
if not issubclass(tag_class, Tag):
self._log.error('Tag class must implement the base Tag interface, please review the documentation on '
'defining custom tags. (Refusing to set the tag "{tag}")'.format(tag=name))
return
self._tags[name] = tag_class
def parse_tags(self, element, trigger):
"""
Parse tags in an XML element
:param element: The response [message] XML element
:type element: etree._Element
:return: A list of strings and Tag objects in the order they are parsed
:rtype : list of (str or parser.tags.tag,Tag)
"""
response = []
# Add the starting text to the response list
head = element.text if isinstance(element.text, string_types) else None
if head:
if head.strip():
head = newlines_to_spaces(head)
self._log.debug('Appending heading text: {text}'.format(text=head))
response.append(head)
# Internal method for appending an elements tail to the response list
def append_tail(e):
tail = e.tail if isinstance(e.tail, string_types) else None
if tail:
if tail.strip():
tail = newlines_to_spaces(tail)
self._log.debug('Appending trailing text: {text}'.format(text=tail))
response.append(tail)
# Parse the contained tags and add their associated string objects to the response list
for child in element:
# Parse star tags internally
if child.tag == 'star':
star_index = int_attribute(child, 'index', 1)
star_format = attribute(child, 'format', 'none')
self._log.debug('Appending Star tag object with index {no}'.format(no=star_index))
response.append(Star(trigger, star_index, star_format))
append_tail(child)
continue
# Make sure a parser for this tag exists
if child.tag not in self._tags:
self._log.warn('No parsers available for Tag "{tag}", skipping'.format(tag=child.tag))
continue
# Append the tag object to the response string
tag = self._tags[child.tag]
self._log.debug('Appending {tag} Tag object'.format(tag=child.tag.capitalize()))
response.append(tag(trigger, child))
# Append the trailing text to the response string (if there is any)
append_tail(child)
return response
def interpreter(self):
"""
Launch an AML interpreter session for testing
"""
while True:
message = input('[#] ')
if message.lower().strip() == 'exit':
break
reply = self.get_reply('#interpreter#', message)
if not reply:
print('No reply received.', end='\n\n')
continue
# typewrite(reply, end='\n\n') TODO
print(reply, end='\n\n')
class Message(object):
"""
Message container object
"""
NORMALIZED = 'normalized'
CASE_PRESERVED = 'case_preserved'
RAW = 'raw'
formats = [NORMALIZED, CASE_PRESERVED, RAW]
def __init__(self, aml, message, message_format=NORMALIZED):
"""
Initialize a new Message instance
:param aml: The parent AgentML instance
:type aml: AgentML
:param message: The message being parsed
:type message: str
:param message_format: The message format to return when the object is interpreted as a string
:type message_format: str
"""
self._log = logging.getLogger('agentml.message')
self._format = message_format
self.aml = aml
# Parsed (and un-parsed) message containers
self._log.debug('Parsing raw message: {message}'.format(message=message))
messages = self.aml.parse_substitutions((normalize(message), normalize(message, preserve_case=True), message))
self._messages = {
'normalized_message': messages[0],
'case_preserved_message': messages[1],
'raw_message': messages[2]
}
self._log.debug('Normalized message processed: {msg}'.format(msg=self._messages['normalized_message']))
self._log.debug('Case preserved message processed: {msg}'.format(msg=self._messages['case_preserved_message']))
self._log.debug('Raw message processed: {msg}'.format(msg=self._messages['raw_message']))
@property
def format(self):
"""
Return the currently set message format
"""
return self._format
@format.setter
def format(self, message_format):
"""
Set the message format
:param message_format: The format to set
:type message_format: str
"""
if message_format not in self.formats:
self._log.error('Invalid Message format specified: {format}'.format(format=message_format))
return
self._log.debug('Setting message format to {format}'.format(format=message_format))
self._format = message_format
@property
def normalized(self):
"""
Return the normalized message
"""
return self._messages['normalized_message']
@property
def case_preserved(self):
"""
Return the case preserved normalized message
"""
return self._messages['case_preserved_message']
@property
def raw(self):
"""
Return the raw message
"""
return self._messages['raw_message']
def __str__(self):
return self._messages['{format}_message'.format(format=self._format)]
class User:
"""
User session object
"""
def __init__(self, identifier):
"""
Initialize a new User instance
:param identifier: The unique identifier for the User. Examples include IRC hostmasks, IP addresses, and DB ID's
:type identifier: str
"""
self._log = logging.getLogger('agentml.user')
self._log.info('Creating new user: {id}'.format(id=identifier))
# User attributes
self.id = identifier
self.topic = None
self._vars = {}
self._limits = {} # Dictionary of objects as keys, tuple of limit expiration's and blocking as values
def get_var(self, name):
"""
Retrieve a variable assigned to this user
:param name: The name of the variable to retrieve
:type name: str
:rtype: str
:raises VarNotDefinedError: The requested variable has not been defined
"""
if name not in self._vars:
raise VarNotDefinedError
return self._vars[name]
def set_var(self, name, value):
"""
Set a variable for this user
:param name: The name of the variable to set
:type name: str
:param value: The value of the variable to set
:type value: str
"""
self._vars[name] = value
def set_limit(self, identifier, expires_at, blocking=False):
"""
Set a new trigger or response limit
:param identifier: The Trigger or Response object
:type identifier: parser.trigger.Trigger or parser.trigger.response.Response
:param expires_at: The limit expiration as a Unix timestamp
:type expires_at: float
:param blocking: When True and a limit is triggered, no other Trigger or Response's will be attempted
:type blocking: bool
"""
self._limits[identifier] = (expires_at, blocking)
def clear_limit(self, identifier=None):
"""
Remove a single limit or all defined limits
:param identifier: The identifier to clear limits for, or if no identifier is supplied, clears ALL limits
:type identifier: int
:return: True if a limit was successfully found and removed, False if no limit could be matched for removal
:rtype : bool
"""
# Remove a single limit
if identifier:
if identifier in self._limits:
del self._limits[identifier]
return True
else:
return False
# Remove all limits
if self._limits:
self._limits.clear()
return True
else:
return False
def is_limited(self, identifier):
"""
Test whether or not there is an active User limit for the specified Trigger or Response instance
:param identifier: The Trigger or Response object
:type identifier: parser.trigger.Trigger or parser.trigger.response.Response
:return: True if there is a limit enforced, otherwise False
:rtype : bool
"""
# If there is a limit for this Trigger assigned, make sure it hasn't expired
if identifier in self._limits:
limit, blocking = self._limits[identifier]
if time() < limit:
# Limit exists and is active, return True
self._log.debug('User "{uid}" has a limit enforced for Object {oid}'
.format(uid=self.id, oid=id(identifier)))
if blocking:
raise LimitError
return True
else:
# Limit has expired, remove it
del self._limits[identifier]
# We're still here, so there are no active limits. Return False
self._log.debug('User "{uid}" has no limit enforced for Object {oid}'.format(uid=self.id, oid=id(identifier)))
return False
class Star:
"""
Wildcard object
"""
def __init__(self, trigger, index=1, star_format='normalized'):
"""
Initialize a new Star wildcard tag object
:param trigger: AgentML Trigger instance
:type trigger: parser.trigger.trigger.Trigger
:param index: The wildcard index to retrieve (Indexes start at 1, not 0)
:type index: int
:param star_format: The formatting to apply to the text value. Can be any valid Python string method
:type star_format: str
"""
self.trigger = trigger
self.index = index
self.format = star_format
self._log = logging.getLogger('agentml.star')
def __str__(self):
try:
if self.format in ['case_preserved', 'raw']:
self._log.debug('Formatting wildcard as {format}'.format(format=self.format))
star = str(self.trigger.stars[self.format][self.index - 1])
else:
star = str(self.trigger.stars['normalized'][self.index - 1])
except IndexError:
self._log.warn('No wildcard with the index {index} exists for this response'.format(index=self.index))
return ''
if self.format in ['title', 'capitalize', 'upper', 'lower']:
self._log.debug('Formatting wildcard as {format}'.format(format=self.format))
star = getattr(star, self.format)()
return star | AgentML | /AgentML-0.3.1.tar.gz/AgentML-0.3.1/agentml/__init__.py | __init__.py |
import logging
from lxml import etree
from agentml.common import attribute, bool_attribute
class Element(object):
"""
Base AgentML element class
"""
def __init__(self, agentml, element, file_path):
"""
Initialize a new Element instance
:param agentml: The parent AgentML instance
:type agentml: AgentML
:param element: The XML Element object
:type element: etree._Element
:param file_path: The absolute path to the AgentML file
:type file_path: str
"""
self.agentml = agentml
self._element = element
self.file_path = file_path
self._log = logging.getLogger('agentml.parser.element')
self._parse()
def _parse(self):
"""
Loop through all child elements and execute any available parse methods for them
"""
for child in self._element:
method_name = '_parse_{0}'.format(str(child.tag)) # TODO: This is a hack, skip comment objects here
if hasattr(self, method_name):
parse = getattr(self, method_name)
parse(child)
class Restrictable(object):
"""
Restrictable element boilerplate parsers
"""
def __init__(self):
"""
Initialize a new Restrictable Element instance
"""
self.user_limit = None
self.global_limit = None
self.mood = None
self.chance = 100
self.ulimit_blocking = True
self.glimit_blocking = True
self.chance_blocking = True
self._log = logging.getLogger('agentml.parser.element')
def _parse_topic(self, element):
"""
Parse a topic element
:param element: The XML Element object
:type element: etree._Element
"""
self.topic = element.text if element.text else None
def _parse_limit(self, element):
"""
Parse a limit element
:param element: The XML Element object
:type element: etree._Element
"""
# Is this a Global or User limit?
limit_type = attribute(element, 'type', 'user')
# Time unit conversions
unit_conversions = {
'seconds': 1,
'minutes': 60,
'hours': 3600,
'days': 86400,
'weeks': 604800,
'months': 2592000,
'years': 31536000
}
units = attribute(element, 'unit', 'seconds')
if units not in unit_conversions:
self._log.warn('Unrecognized time unit: {unit}'.format(unit=units))
return
try:
limit = float(element.text)
except (ValueError, TypeError):
self._log.warn('Limit must contain a valid integer or float (Invalid limit: "{limit}")'
.format(limit=element.text))
return
if limit_type == 'global':
self.global_limit = limit * unit_conversions[units]
self.glimit_blocking = bool_attribute(element, 'blocking', self.glimit_blocking)
elif limit_type == 'user':
self.user_limit = limit * unit_conversions[units]
self.ulimit_blocking = bool_attribute(element, 'blocking', self.ulimit_blocking)
return
def _parse_chance(self, element):
"""
Parse a chance element
:param element: The XML Element object
:type element: etree._Element
"""
try:
chance = float(element.text)
except (ValueError, TypeError, AttributeError):
self._log.warn('Invalid Chance string: {chance}'.format(chance=element.text))
return
# Make sure the chance is a valid percentage
if not (0 <= chance <= 100):
self._log.warn('Chance percent must contain an integer or float between 0 and 100')
return
self.chance = chance
self.chance_blocking = bool_attribute(element, 'blocking', self.chance_blocking) | AgentML | /AgentML-0.3.1.tar.gz/AgentML-0.3.1/agentml/parser/element.py | element.py |
import os
import logging
from agentml.common import schema, attribute
from agentml.parser.tags import Tag
from agentml.errors import VarNotDefinedError
class Var(Tag):
def __init__(self, trigger, element):
"""
Initialize a new Random Tag instance
:param trigger: The executing Trigger instance
:type trigger: parser.trigger.Trigger
:param element: The XML Element object
:type element: etree._Element
"""
super(Var, self).__init__(trigger, element)
self._log = logging.getLogger('agentml.parser.tags.var')
# Define our schema
with open(os.path.join(self.trigger.agentml.script_path, 'schemas', 'tags', 'var.rng')) as file:
self.schema = schema(file.read())
# Is this a User or Global variable?
self.type = attribute(element, 'type', 'user')
def value(self):
"""
Return the current value of a variable
"""
# Does the variable name have tags to parse?
if len(self._element):
var = ''.join(map(str, self.trigger.agentml.parse_tags(self._element, self.trigger)))
else:
var = self._element.text or attribute(self._element, 'name')
# Is there a default value defined?
default = attribute(self._element, 'default')
try:
self._log.debug('Retrieving {type} variable {var}'.format(type=self.type, var=var))
if self.type == 'user':
return self.trigger.user.get_var(var)
else:
return self.trigger.agentml.get_var(var)
except VarNotDefinedError:
# Do we have a default value?
if default:
self._log.info('{type} variable {var} not set, returning default: {default}'
.format(type=self.type.capitalize(), var=var, default=default))
self._log.info('{type} variable {var} not set and no default value has been specified'
.format(type=self.type.capitalize(), var=var))
return '' | AgentML | /AgentML-0.3.1.tar.gz/AgentML-0.3.1/agentml/parser/tags/var.py | var.py |
import logging
import re
import sre_constants
import random
from time import time
from collections import Iterable
from six import string_types
from agentml.parser import Element, Restrictable
from agentml.common import normalize, int_attribute, bool_attribute, bool_element
from agentml.errors import AgentMLSyntaxError, ParserBlockingError, LimitError, ChanceError
from agentml.parser.trigger.response import Response, ResponseContainer
from agentml.parser.trigger.condition import Condition
class Trigger(Element, Restrictable):
"""
AgentML Trigger object
"""
def __init__(self, agentml, element, file_path, **kwargs):
"""
Initialize a new Trigger instance
:param agentml: The parent AgentML instance
:type agentml: AgentML
:param element: The XML Element object
:type element: etree._Element
:param file_path: The absolute path to the AgentML file
:type file_path: str
:param kwargs: Default attributes
"""
# Containers and default attributes
self.priority = int_attribute(element, 'priority')
self.normalize = bool_attribute(element, 'normalize')
self.blocking = bool_element(element, 'blocking')
self.pattern = kwargs['pattern'] if 'pattern' in kwargs else None
self.groups = kwargs['groups'] if 'groups' in kwargs else None
self.topic = kwargs['topic'] if 'topic' in kwargs else None
self._responses = kwargs['responses'] if 'responses' in kwargs else ResponseContainer()
self.vars = [] # list of tuple(type, name, value)
# Pattern metadata
self.pattern_is_atomic = False
self.pattern_words = 0
self.pattern_len = 0
# Temporary response data
self.stars = {
'normalized': (),
'case_preserved': (),
'raw': ()
}
self.user = None
# Parent __init__'s must be initialized BEFORE default attributes are assigned, but AFTER the above containers
Restrictable.__init__(self)
Element.__init__(self, agentml, element, file_path)
self._log = logging.getLogger('agentml.parser.trigger')
def match(self, user, message):
"""
Returns a response message if a match is found, otherwise None
:param user: The requesting client
:type user: agentml.User
:param message: The message to match
:type message: agentml.Message
:rtype: str or None
"""
self._log.info('Attempting to match message against Pattern: {pattern}'
.format(pattern=self.pattern.pattern if hasattr(self.pattern, 'pattern') else self.pattern))
self.user = user
# Make sure the topic matches (if one is defined)
if user.topic != self.topic:
self._log.debug('User topic "{u_topic}" does not match Trigger topic "{t_topic}", skipping check'
.format(u_topic=user.topic, t_topic=self.topic))
return
def get_response():
# Does the user have a limit for this response enforced?
if user.is_limited(self):
if self.ulimit_blocking:
self._log.debug('An active blocking limit for this trigger is being enforced against the user '
'{uid}, no trigger will be matched'.format(uid=user.id))
raise LimitError
self._log.debug('An active limit for this response is being enforced against the user {uid}, '
'skipping'.format(uid=user.id))
return ''
# Is there a global limit for this response enforced?
if self.agentml.is_limited(self):
if self.glimit_blocking:
self._log.debug('An active blocking limit for this trigger is being enforced globally, no trigger '
'will be matched')
raise LimitError
self._log.debug('An active limit for this response is being enforced against the user {uid}, '
'skipping'.format(uid=user.id))
return ''
# Chance testing
if self.chance is not None and self.chance != 100:
# Chance succeeded
if self.chance >= random.uniform(0, 100):
self._log.info('Trigger had a {chance}% chance of being selected and succeeded selection'
.format(chance=self.chance))
# Chance failed
else:
if self.chance_blocking:
self._log.info('Trigger had a blocking {chance}% chance of being selected but failed selection'
', no trigger will be matched'.format(chance=self.chance))
raise ChanceError
self._log.info('Response had a {chance}% chance of being selected but failed selection'
.format(chance=self.chance))
return ''
random_response = self._responses.random(user)
if not random_response and self.blocking:
self._log.info('Trigger was matched, but there are no available responses and the trigger is blocking '
'any further attempts. Giving up')
raise ParserBlockingError
if random_response:
self.apply_reactions(user)
else:
self._log.info('Trigger was matched, but there are no available responses')
random_response = ''
return random_response
# String match
if isinstance(self.pattern, string_types) and str(message) == self.pattern:
self._log.info('String Pattern matched: {match}'.format(match=self.pattern))
return get_response()
# Regular expression match
if hasattr(self.pattern, 'match'):
match = self.pattern.match(str(message))
if match:
self._log.info('Regex pattern matched: {match}'.format(match=self.pattern.pattern))
# Parse pattern wildcards
self.stars['normalized'] = match.groups()
for message_format in [message.CASE_PRESERVED, message.RAW]:
message.format = message_format
format_match = self.pattern.match(str(message))
if format_match:
self.stars[message_format] = format_match.groups()
self._log.debug('Assigning pattern wildcards: {stars}'.format(stars=str(self.stars)))
return get_response()
def apply_reactions(self, user):
"""
Set active topics and limits after a response has been triggered
:param user: The user triggering the response
:type user: agentml.User
"""
# User attributes
if self.global_limit:
self._log.info('Enforcing Global Trigger Limit of {num} seconds'.format(num=self.global_limit))
self.agentml.set_limit(self, (time() + self.global_limit), self.glimit_blocking)
if self.user_limit:
self._log.info('Enforcing User Trigger Limit of {num} seconds'.format(num=self.user_limit))
user.set_limit(self, (time() + self.user_limit), self.ulimit_blocking)
for var in self.vars:
var_type, var_name, var_value = var
var_name = ''.join(map(str, var_name)) if isinstance(var_name, Iterable) else var_name
var_value = ''.join(map(str, var_value)) if isinstance(var_value, Iterable) else var_value
# Set a user variable
if var_type == 'user':
self.user.set_var(var_name, var_value)
# Set a global variable
if var_type == 'global':
self.agentml.set_var(var_name, var_value)
# agentml.mood = self.mood
def _add_response(self, response, weight=1):
"""
Add a new trigger
:param response: The Response object
:type response: Response or Condition
:param weight: The weight of the response
:type weight: int
"""
# If no response with this priority level has been defined yet, create a new list
if response.priority not in self._responses:
self._responses[response.priority] = [(response, weight)]
return
# Otherwise, add this trigger to an existing priority list
self._responses[response.priority].append((response, weight))
@staticmethod
def replace_wildcards(string, wildcard, regex):
"""
Replace wildcard symbols with regular expressions
:param wildcard:
:type wildcard: _sre.SRE_Pattern
:param regex:
:type regex: str
:rtype: tuple of (str, bool)
"""
replaced = False
match = wildcard.search(string)
if match:
string = wildcard.sub(regex, string)
logging.getLogger('agentml.trigger').debug('Parsing Pattern wildcards: {pattern}'.format(pattern=string))
replaced = True
return string, replaced
@staticmethod
def count_words(pattern):
"""
Count the number of words in a pattern as well as the total length of those words
:param pattern: The pattern to parse
:type pattern: str
:return: The word count first, then the total length of all words
:rtype : tuple of (int, int)
"""
word_pattern = re.compile(r'(\b(?<![\(\)\[\]\|])\w\w*\b(?![\(\)\[\]\|]))', re.IGNORECASE)
words = word_pattern.findall(pattern)
word_count = len(words)
word_len = sum(len(word) for word in words)
return word_count, word_len
def _parse_priority(self, element):
"""
Parse and assign the priority for this trigger
:param element: The XML Element object
:type element: etree._Element
"""
self._log.debug('Setting Trigger priority: {priority}'.format(priority=element.text))
self.priority = int(element.text)
def _parse_group(self, element):
"""
Parse and add a group requirement for this trigger
:param element: The XML Element object
:type element: etree._Element
"""
self._log.debug('Adding Trigger group: {group}'.format(group=element.text))
if isinstance(self.groups, set):
self.groups.add(element.text)
elif self.groups is None:
self.groups = {element.text}
else:
raise TypeError('Unrecognized group type, {type}: {groups}'
.format(type=type(self.groups), groups=str(self.groups)))
def _parse_topic(self, element):
"""
Parse and assign the topic for this trigger
:param element: The XML Element object
:type element: etree._Element
"""
self._log.debug('Setting Trigger topic: {topic}'.format(topic=element.text))
super(Trigger, self)._parse_topic(element)
def _parse_emotion(self, element):
"""
Parse an emotion element
:param element: The XML Element object
:type element: etree._Element
"""
self.emotion = normalize(element.text)
def _parse_pattern(self, element):
"""
Parse the trigger pattern
:param element: The XML Element object
:type element: etree._Element
"""
# If this is a raw regular expression, compile it and immediately return
self._log.info('Parsing Trigger Pattern: ' + element.text)
self.pattern_words, self.pattern_len = self.count_words(element.text)
self._log.debug('Pattern contains {wc} words with a total length of {cc}'
.format(wc=self.pattern_words, cc=self.pattern_len))
regex = bool_attribute(self._element, 'regex', False)
if regex:
self._log.info('Attempting to compile trigger as a raw regex')
try:
self.pattern = re.compile(element.text)
except sre_constants.error:
self._log.warn('Attempted to compile an invalid regular expression in {path} ; {regex}'
.format(path=self.file_path, regex=element.text))
raise AgentMLSyntaxError
return
self.pattern = normalize(element.text, True)
self._log.debug('Normalizing pattern: ' + self.pattern)
compile_as_regex = False
# Wildcard patterns and replacements
captured_wildcard = re.compile(r'(?<!\\)\(\*\)')
wildcard = re.compile(r'(?<!\\)\*')
capt_wild_numeric = re.compile(r'(?<!\\)\(#\)')
wild_numeric = re.compile(r'(?<!\\)#')
capt_wild_alpha = re.compile(r'(?<!\\)\(_\)')
wild_alpha = re.compile(r'(?<!\\)_')
wildcard_replacements = [
(captured_wildcard, r'(.+)'),
(wildcard, r'(?:.+)'),
(capt_wild_numeric, r'(\d+)'),
(wild_numeric, r'(?:\d+)'),
(capt_wild_alpha, r'([a-zA-Z]+)'),
(wild_alpha, r'(?:[a-zA-Z]+)'),
]
for wildcard, replacement in wildcard_replacements:
self.pattern, match = self.replace_wildcards(self.pattern, wildcard, replacement)
compile_as_regex = bool(match) or compile_as_regex
# Required and optional choices
req_choice = re.compile(r'\(([\w\s\|]+)\)')
opt_choice = re.compile(r'\s?\[([\w\s\|]+)\]\s?')
if req_choice.search(self.pattern):
def sub_required(pattern):
patterns = pattern.group(1).split('|')
return r'(\b{options})\b'.format(options='|'.join(patterns))
self.pattern = req_choice.sub(sub_required, self.pattern)
self._log.debug('Parsing Pattern required choices: ' + self.pattern)
compile_as_regex = True
if opt_choice.search(self.pattern):
def sub_optional(pattern):
patterns = pattern.group(1).split('|')
return r'\s?(?:\b(?:{options})\b)?\s?'.format(options='|'.join(patterns))
self.pattern = opt_choice.sub(sub_optional, self.pattern)
self._log.debug('Parsing Pattern optional choices: ' + self.pattern)
compile_as_regex = True
if compile_as_regex:
self._log.debug('Compiling Pattern as regex')
self.pattern = re.compile('^{pattern}$'.format(pattern=self.pattern), re.IGNORECASE)
else:
self._log.debug('Pattern is atomic')
self.pattern_is_atomic = True
# Replace any escaped wildcard symbols
self._log.debug('Replacing any escaped sequences in Pattern')
self.pattern = self.pattern.replace('\*', '*')
self.pattern = self.pattern.replace('\#', '#')
self.pattern = self.pattern.replace('\_', '_')
# TODO: This needs revisiting
self.pattern = self.pattern.replace('\(*)', '(*)')
self.pattern = self.pattern.replace('\(#)', '(#)')
self.pattern = self.pattern.replace('\(_)', '(_)')
def _parse_response(self, element):
"""
Parse a trigger response
:param element: The XML Element object
:type element: etree._Element
"""
self._log.info('Parsing new Response')
self._responses.add(Response(self, element, self.file_path))
def _parse_template(self, element):
"""
Parse a trigger shorthand response
:param element: The XML Element object
:type element: etree._Element
"""
self._log.info('Parsing new shorthand Response')
self._responses.add(Response(self, element, self.file_path))
def _parse_redirect(self, element):
"""
Parse a trigger redirect
:param element: The XML Element object
:type element: etree._Element
"""
self._log.info('Parsing new redirected Response')
self._responses.add(Response(self, element, self.file_path))
def _parse_condition(self, element):
"""
Parse a trigger condition
:param element: The XML Element object
:type element: etree._Element
"""
self._log.info('Parsing new Condition')
condition = Condition(self, element, self.file_path)
for statement in condition.statements:
for response in statement.contents:
self._responses.add(response, condition)
if condition.else_statement:
self._responses.add(condition.else_statement[0], condition)
def _parse_chance(self, element):
"""
Parse the chance of this trigger being successfully called
:param element: The XML Element object
:type element: etree._Element
"""
try:
chance = element.text.strip('%')
chance = float(chance)
except (ValueError, TypeError, AttributeError):
self._log.warn('Invalid Chance string: {chance}'.format(chance=element.text))
return
# Make sure the chance is a valid percentage
if not (0 <= chance <= 100):
self._log.warn('Chance percent must contain an integer or float between 0 and 100')
return
self.chance = chance | AgentML | /AgentML-0.3.1.tar.gz/AgentML-0.3.1/agentml/parser/trigger/__init__.py | __init__.py |
import logging
import random
from collections import OrderedDict
from agentml.common import weighted_choice
from agentml.errors import LimitError, ChanceError
class ResponseContainer(object):
"""
Container for Response objects
"""
def __init__(self):
"""
Initialize a new Response Container
"""
# Responses are contained in an ordered dictionary, with the keys being the priority level
self._responses = OrderedDict()
self._conditionals = {} # keys contain response id()'s, values contain Condition objects
self.sorted = False # Priority levels need to be sorted after parsing before they can be iterated
self._log = logging.getLogger('agentml.parser.trigger.response.container')
def _sort(self):
"""
Sort the response dictionaries priority levels for ordered iteration
"""
self._log.debug('Sorting responses by priority')
self._responses = OrderedDict(sorted(list(self._responses.items()), reverse=True))
self.sorted = True
def add(self, response, condition=None):
"""
Add a new Response object
:param response: The Response object
:type response: parser.trigger.response.Response
:param condition: An optional Conditional statement for the Response
:type condition: parser.condition.Condition or None
"""
self._log.info('Adding a new response with the priority level {priority}'.format(priority=response.priority))
# If this is the first time we are seeing this priority level, ready a new response list
if response.priority not in self._responses:
self.sorted = False # Only reset sorted flag on a new priority definition for efficiency
self._responses[response.priority] = []
# If this response requires a condition be met, assign it to the Response object directly
if condition:
self._log.debug('Response has a condition defined')
self._conditionals[response] = condition
self._responses[response.priority].append(response)
def random(self, user=None):
"""
Retrieve a random Response
:param user: The user to test for active limitations and to apply response actions on
:type user: agentml.User or None
:return: A randomly selected Response object
:rtype : parser.trigger.response.Response
"""
if not self.sorted:
self._sort()
self._log.info('Attempting to retrieve a random response')
failed_conditions = []
passed_conditions = {}
successful_response = None
for priority, responses in self._responses.items():
self._log.debug('Attempting priority {priority} responses'.format(priority=priority))
response_pool = []
for response in responses:
# If the response has a condition, attempt to evaluate it
condition = self._conditionals[response] if response in self._conditionals else None
if condition:
# Condition has already been evaluated and the evaluation failed, skip and continue
if condition in failed_conditions:
self._log.debug('Skipping response due to a previously failed condition check')
continue
# Condition has already been evaluated successfully, check if this response is in the cond. results
elif condition in passed_conditions:
if response in passed_conditions[condition]:
self._log.debug('Response is in a condition that has already been successfully evaluated')
else:
# This error is kinda ambiguous, but it basically means the condition evaluated true,
# but this specific response was in a different if / elif / else statement
self._log.debug('Response is in a condition that has already been successfully evaluated, '
'but the response was in the wrong condition statement, skipping')
continue
# Condition has not been evaluated yet, process it now and save the result
elif condition not in passed_conditions:
self._log.debug('Evaluating a new condition')
evaluated = condition.evaluate(user)
# Fail, skip and continue
if not evaluated:
self._log.debug('Condition failed to evaluate successfully, skipping response')
failed_conditions.append(condition)
continue
# Pass
self._log.debug('Condition evaluated successfully, checking if we\'re in the right condition '
'statement')
passed_conditions[condition] = evaluated
if response in passed_conditions[condition]:
self._log.debug('Response is in the successfully evaluated condition statement, continuing')
else:
# This error is kinda ambiguous, but it basically means the condition evaluated true,
# but this specific response was in a different if / elif / else statement
self._log.debug('Response was in the wrong condition statement, skipping')
continue
# Does the user have a limit for this response enforced?
if user and user.is_limited(response):
if response.ulimit_blocking:
self._log.debug('An active blocking limit for this response is being enforced against the user '
'{uid}, no response will be returned'.format(uid=user.id))
raise LimitError
self._log.debug('An active limit for this response is being enforced against the user {uid}, '
'skipping'.format(uid=user.id))
continue
# Is there a global limit for this response enforced?
if response.agentml.is_limited(response):
if response.glimit_blocking:
self._log.debug('An active blocking limit for this response is being enforced globally, no '
'response will be returned')
raise LimitError
self._log.debug('An active limit for this response is being enforced globally, skipping')
continue
self._log.debug('Adding new response to the random pool with a weight of {weight}'
.format(weight=response.weight))
response_pool.append((response, response.weight))
# If we have no responses in the response pool, that means a limit is being enforced for them all and
# we need to move on to responses in the next priority bracket
if not response_pool:
self._log.debug('All responses with a priority of {priority} failed to pass one or more condition '
'checks, continuing to the next priority bracket'.format(priority=priority))
continue
# Start a loop so we can weed out responses that fail chance conditions
while True:
# Retrieve a random weighted response
response = weighted_choice(response_pool)
# Are we out of responses to try?
if not response:
break
# Is there a chance we need to evaluate?
if response.chance is None or response.chance == 100:
successful_response = response
break
# Chance succeeded
if response.chance >= random.uniform(0, 100):
self._log.info('Response had a {chance}% chance of being selected and succeeded selection'
.format(chance=response.chance))
successful_response = response
break
# Chance failed
else:
if response.chance_blocking:
self._log.info('Response had a blocking {chance}% chance of being selected but failed selection'
', no response will be returned'.format(chance=response.chance))
raise ChanceError
self._log.info('Response had a {chance}% chance of being selected but failed selection'
.format(chance=response.chance))
response_pool = [r for r in response_pool if r[0] is not response]
continue
# If we have no successful response defined, that means a chance condition for all the responses failed and
# we need to move on to responses in the next priority bracket
if successful_response is None:
self._log.debug('All responses with a priority of {priority} have chance conditions defined and we '
'failed to pass any of them, continuing to the next priority bracket'
.format(priority=priority))
continue
# If we're still here, that means we DO have a successful response ans we should process it immediately
if user:
successful_response.apply_reactions(user)
return successful_response
# If we looped through everything but haven't returned yet, that means we ran out of responses to attempt
self._log.info('All responses failed to pass one or more condition checks, nothing to return') | AgentML | /AgentML-0.3.1.tar.gz/AgentML-0.3.1/agentml/parser/trigger/response/container.py | container.py |
import logging
from time import time
from collections import Iterable
from agentml.common import attribute, int_attribute, newlines_to_spaces
from agentml.parser import Element, Restrictable
from .container import ResponseContainer
class Response(Element, Restrictable):
"""
AgentML Response object
"""
def __init__(self, trigger, element, file_path, **kwargs):
"""
Initialize a new Response instance
:param trigger: The Trigger instance
:type trigger: Trigger
:param element: The XML Element object
:type element: etree._Element
:param file_path: The absolute path to the AgentML file
:type file_path: str
:param kwargs: Default attributes
"""
self.priority = int_attribute(element, 'priority')
self.weight = int_attribute(element, 'weight', 1)
self.trigger = trigger
# If the redirect attribute is True, the response will contain a template used to request a different response,
# otherwise it contains a template for the response message
self._response = ()
self.redirect = False
# What the topic should be *changed* to after this response is sent. False = No change
self.topic = False
# Variables to set, list of tuple(type, name, value)
self.vars = []
# Wildcard containers
self.stars = {
'normalized': (),
'case_preserved': (),
'raw': ()
}
Restrictable.__init__(self)
Element.__init__(self, trigger.agentml, element, file_path)
# Blocking attributes
self.ulimit_blocking = False
self.glimit_blocking = False
self.chance_blocking = False
self._log = logging.getLogger('agentml.parser.trigger.response')
def get(self):
"""
Parse a response into string format and clear out its temporary containers
:return: The parsed response message
:rtype : str
"""
self._log.debug('Converting Response object to string format')
response = ''.join(map(str, self._response)).strip()
self._log.debug('Resetting parent Trigger temporary containers')
self.stars = {
'normalized': (),
'case_preserved': (),
'raw': ()
}
user = self.trigger.user
self.trigger.user = None
if self.redirect:
self._log.info('Redirecting response to: {msg}'.format(msg=response))
groups = self.agentml.request_log.most_recent().groups
response = self.agentml.get_reply(user.id, response, groups)
if not response:
self._log.info('Failed to retrieve a valid response when redirecting')
return ''
return response
def apply_reactions(self, user):
"""
Set active topics and limits after a response has been triggered
:param user: The user triggering the response
:type user: agentml.User
"""
# User attributes
if self.topic is not False:
self._log.info('Setting User Topic to: {topic}'.format(topic=self.topic))
user.topic = self.topic
if self.global_limit:
self._log.info('Enforcing Global Response Limit of {num} seconds'.format(num=self.global_limit))
self.agentml.set_limit(self, (time() + self.global_limit), self.glimit_blocking)
if self.user_limit:
self._log.info('Enforcing User Response Limit of {num} seconds'.format(num=self.user_limit))
user.set_limit(self, (time() + self.user_limit))
for var in self.vars:
var_type, var_name, var_value = var
var_name = ''.join(map(str, var_name)) if isinstance(var_name, Iterable) else var_name
var_value = ''.join(map(str, var_value)) if isinstance(var_value, Iterable) else var_value
# Set a user variable
if var_type == 'user':
self.trigger.user.set_var(var_name, var_value)
# Set a global variable
if var_type == 'global':
self.trigger.agentml.set_var(var_name, var_value)
def _parse(self):
"""
Loop through all child elements and execute any available parse methods for them
"""
# Is this a shorthand template?
if self._element.tag == 'template':
return self._parse_template(self._element)
# Is this a shorthand redirect?
if self._element.tag == 'redirect':
return self._parse_redirect(self._element)
for child in self._element:
method_name = '_parse_' + child.tag
if hasattr(self, method_name):
parse = getattr(self, method_name)
parse(child)
def _parse_template(self, element):
"""
Parse the response template
:param element: The XML Element object
:type element: etree._Element
"""
# If the response element has no tags, just store the raw text as the only response
if not len(element):
self._response = (newlines_to_spaces(element.text),)
self._log.info('Assigning text only response')
return
# Otherwise, parse the tags now
self._response = tuple(self.agentml.parse_tags(element, self.trigger))
def _parse_redirect(self, element):
"""
Parse a redirect statement
:param element: The XML Element object
:type element: etree._Element
"""
self._log.info('Parsing response as a redirect')
self.redirect = True
return self._parse_template(element)
def _parse_priority(self, element):
"""
Parse and assign the priority for this response
:param element: The XML Element object
:type element: etree._Element
"""
self._log.debug('Setting Trigger priority: {priority}'.format(priority=element.text))
self.priority = int(element.text)
def _parse_var(self, element):
"""
Parse a variable assignment
:param element: The XML Element object
:type element: etree._Element
"""
syntax = 'attribute' if element.get('name') else 'element'
var_type = attribute(element, 'type', 'user')
if syntax == 'attribute':
var_name = attribute(element, 'name')
var_value = self.agentml.parse_tags(element, self.trigger) if len(element) else element.text
else:
name_etree = element.find('name')
var_name = self.agentml.parse_tags(name_etree, self.trigger) if len(name_etree) else name_etree.text
value_etree = element.find('value')
var_value = self.agentml.parse_tags(value_etree, self.trigger) if len(value_etree) else value_etree.text
self.vars.append((var_type, var_name, var_value))
def __str__(self):
return self.get() | AgentML | /AgentML-0.3.1.tar.gz/AgentML-0.3.1/agentml/parser/trigger/response/__init__.py | __init__.py |
import logging
from six import add_metaclass
from abc import ABCMeta, abstractmethod
from agentml.parser import Element
from agentml.common import attribute
from agentml.parser.trigger.response import Response
@add_metaclass(ABCMeta)
class BaseCondition(object):
"""
AgentML Base Condition class
"""
def __init__(self, agentml, element, **kwargs):
"""
Initialize a new Base Condition instance
:param agentml: The parent AgentML instance
:type agentml: AgentML
:param element: The XML Element object
:type element: etree._Element
:param kwargs: Default attributes
"""
self.agentml = agentml
self._element = element
# Containers and default attributes
self.statements = []
self.else_statement = None
self.type = kwargs['type'] if 'type' in kwargs else attribute(self._element, 'type', 'user_var')
self._log = logging.getLogger('agentml.parser.trigger.condition')
def evaluate(self, user):
"""
Evaluate the conditional statement and return its contents if a successful evaluation takes place
:param user: The active user object
:type user: agentml.User or None
:return: True if the condition evaluates successfully, otherwise False
:rtype : bool
"""
for statement in self.statements:
evaluated = statement.evaluate(self.agentml, user)
if evaluated:
return evaluated
return self.else_statement or False
@abstractmethod
def get_contents(self, element):
"""
Retrieve the contents of an element
:param element: The XML Element object
:type element: etree._Element
:return: A list of text and/or XML elements
:rtype : list of etree._Element or str
"""
pass
def _parse(self):
"""
Loop through all child elements and execute any available parse methods for them
"""
self.type = attribute(self._element, 'type') or self.type
for child in self._element:
method_name = '_parse_{0}'.format(str(child.tag)) # TODO: This is a hack, skip comment objects here
if hasattr(self, method_name):
parse = getattr(self, method_name)
parse(child)
def _parse_if(self, element):
"""
Parse the if statement
:param element: The XML Element object
:type element: etree._Element
"""
# Get the key
name = attribute(element, 'name')
cond_type = attribute(element, 'type', self.type)
# Get the comparison operator and its value (if implemented)
operator = None
value = None
for o in ConditionStatement.operators:
if o in element.attrib:
operator = o
value = element.attrib[operator]
break
# Get the contents of the element in tuple form and append our if statement
contents = tuple(self.get_contents(element))
self.statements.append(ConditionStatement(cond_type, operator, contents, value, name))
def _parse_elif(self, element):
"""
Parse an elif statement
:param element: The XML Element object
:type element: etree._Element
"""
self._parse_if(element)
def _parse_else(self, element):
"""
Parse the else statement
:param element: The XML Element object
:type element: etree._Element
"""
self.else_statement = self.get_contents(element)
class Condition(Element, BaseCondition):
"""
AgentML Condition object
"""
def __init__(self, trigger, element, file_path):
"""
Initialize a new Condition instance
:param trigger: The Trigger instance
:type trigger: Trigger
:param element: The XML Element object
:type element: etree._Element
:param file_path: The absolute path to the AgentML file
:type file_path: str
"""
self.trigger = trigger
BaseCondition.__init__(self, trigger.agentml, element)
Element.__init__(self, trigger.agentml, element, file_path)
self._log = logging.getLogger('agentml.parser.trigger.condition')
def get_contents(self, element):
"""
Retrieve the contents of an element
:param element: The XML Element object
:type element: etree._Element
:return: A list of responses
:rtype : list of Response
"""
return [Response(self.trigger, child, self.file_path)
for child in element if child.tag in ['response', 'template']]
class ConditionStatement:
"""
Condition Statement object
"""
# Condition operators
IS = 'is'
IS_NOT = 'is_not'
GREATER_THAN = 'gt'
GREATER_THAN_OR_EQUAL = 'gte'
LESS_THAN = 'lt'
LESS_THAN_OR_EQUAL = 'lte'
operators = [IS, IS_NOT, GREATER_THAN, GREATER_THAN_OR_EQUAL, LESS_THAN, LESS_THAN_OR_EQUAL]
def __init__(self, cond_type, operator, contents, value=None, name=None):
"""
Initialize a new Condition Statement object
:param cond_type: The type of the condition statement
:type cond_type: str
:param operator: The operator of the condition statement
:type operator: str
:param contents: The contents of the condition statement
:type contents: tuple
:param value: The value of the condition statement
:type value: str, int, float or None
:param name: The name of the variable if the condition type is USER_VAR or GLOBAL_VAR
:type name: str
"""
self.type = cond_type
self.operator = operator
self.contents = contents
self.value = value
self.name = name
self._log = logging.getLogger('agentml.parser.trigger.condition.statement')
def evaluate(self, agentml, user=None):
"""
Evaluate the conditional statement and return its contents if a successful evaluation takes place
:param user: The active user object
:type user: agentml.User or None
:param agentml: The active AgentML instance
:type agentml: AgentML
:return: Condition contents if the condition evaluates successfully, otherwise False
:rtype : tuple or bool
"""
self._log.debug('Evaluating conditional statement: {statement}'
.format(statement=' '.join(filter(None, [self.type, self.name, self.operator, self.value]))))
# Get the value of our key type
if self.type not in agentml.conditions:
self._log.error('Unknown condition type, "{type}", unable to evaluate condition statement'
.format(type=self.type))
return
key_value = agentml.conditions[self.type].get(agentml, user, self.name)
# Atomic comparisons
if self.operator is None and key_value:
return self.contents
if (self.operator == self.IS) and (key_value == self.value):
return self.contents
if (self.operator == self.IS_NOT) and (key_value != self.value):
return self.contents
# All remaining self.operators are numeric based, so key_value must contain a valid integer or float
try:
key_value = float(key_value)
value = float(self.value)
except (ValueError, TypeError):
return False
# Numeric comparisons
if (self.operator == self.GREATER_THAN) and (key_value > value):
return self.contents
if (self.operator == self.GREATER_THAN_OR_EQUAL) and (key_value >= value):
return self.contents
if (self.operator == self.LESS_THAN) and (key_value < value):
return self.contents
if (self.operator == self.LESS_THAN_OR_EQUAL) and (key_value <= value):
return self.contents
return False | AgentML | /AgentML-0.3.1.tar.gz/AgentML-0.3.1/agentml/parser/trigger/condition/__init__.py | __init__.py |
# Agently 2.0
## QUICK START
```python
import Agently
worker = Agently.create_worker()
worker.set_llm_name("GPT").set_llm_auth("GPT", "Your-API-Key")
result = worker\
.input("Give me 5 words and 1 sentence.")\
.output({
"words": ("Array",),
"sentence": ("String",),
})\
.start()
print(result)
print(result["words"][2])
```
## MORE INFORMATION
Python`v2.0.0`: [Chinese](https://github.com/Maplemx/Agently/blob/main/README.md)
NodeJS`v1.1.3`: [English](https://github.com/Maplemx/Agently/blob/main/README_node_v1_EN.md) | [Chinese](https://github.com/Maplemx/Agently/blob/main/README_node_v1_CN.md) | Agently | /Agently-2.0.1.post1.tar.gz/Agently-2.0.1.post1/README.md | README.md |
import sys
import math
import bisect
from collections import deque
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtChart import (
QChart,
QChartView,
QLineSeries,
QValueAxis,
QBarSet,
QBarSeries,
QBarCategoryAxis,
)
from PyQt5.QtCore import QPointF, QLineF, Qt
from PyQt5.QtGui import QPainter, QPainterPath, QColor, QPolygonF, QImage
from agents.model import (
get_quickstart_model,
AgentShape,
ButtonSpec,
ToggleSpec,
SliderSpec,
CheckboxSpec,
LineChartSpec,
BarChartSpec,
HistogramSpec,
AgentGraphSpec,
MonitorSpec,
EllipseStruct,
RectStruct,
)
class LineArea(QtWidgets.QWidget):
def __init__(self, model):
super().__init__()
self.model = model
self.lineimage = QImage(
model.width, model.height, QImage.Format_ARGB32
)
self.lineimage.fill(QColor(0, 0, 0, 0))
def paintEvent(self, e):
linepainter = QtGui.QPainter(self.lineimage)
linepainter.setPen(QtCore.Qt.NoPen)
linepainter.setRenderHint(QtGui.QPainter.Antialiasing)
for agent in self.model.agents:
linepainter.setPen(
QColor(agent.color[0], agent.color[1], agent.color[2])
)
for line in agent.path.get_not_drawn():
linepainter.drawLine(
QLineF(line[0][0], line[0][1], line[1][0], line[1][1])
)
agent.path.mark_as_drawn()
linepainter.end()
painter = QtGui.QPainter(self)
painter.setPen(QtCore.Qt.NoPen)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.drawImage(QPointF(0, 0), self.lineimage)
painter.end()
class ShapeArea(QtWidgets.QWidget):
def __init__(self, model):
super().__init__()
self.model = model
self.shapeimage = QImage(
model.width, model.height, QImage.Format_ARGB32
)
self.shapeimage.fill(QColor(0, 0, 0, 0))
def paintEvent(self, e):
painter = QtGui.QPainter(self)
painter.setPen(QtCore.Qt.NoPen)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
for shape in self.model.get_shapes():
c = shape.color
painter.setBrush(QtGui.QColor(c[0], c[1], c[2]))
if type(shape) is EllipseStruct:
painter.drawEllipse(shape.x, shape.y, shape.w, shape.h)
elif type(shape) is RectStruct:
painter.drawRect(shape.x, shape.y, shape.w, shape.h)
painter.end()
class TileArea(QtWidgets.QWidget):
def __init__(self, model):
super().__init__()
self.model = model
self.tileimage = QImage(
model.width, model.height, QImage.Format_ARGB32
)
self.tileimage.fill(QColor(0, 0, 0))
def paintEvent(self, e):
tilepainter = QtGui.QPainter(self.tileimage)
tilepainter.setPen(QtCore.Qt.NoPen)
tilepainter.setRenderHint(QtGui.QPainter.Antialiasing)
if self.model:
for tile in self.model._vu_tiles:
r, g, b = tile.color
color = QtGui.QColor(r, g, b)
tilepainter.setBrush(color)
x = self.model.tile_size * tile.x
y = self.model.tile_size * tile.y
tilepainter.drawRect(
x, y, self.model.tile_size, self.model.tile_size
)
self.model._vu_tiles = []
tilepainter.end()
painter = QtGui.QPainter(self)
painter.setPen(QtCore.Qt.NoPen)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.drawImage(QPointF(0, 0), self.tileimage)
painter.end()
class AgentArea(QtWidgets.QWidget):
def __init__(self, model):
super().__init__()
self.model = model
self.agentimage = QImage(
model.width, model.height, QImage.Format_ARGB32
)
self.agentimage.fill(QColor(0, 0, 0, 0))
def paintEvent(self, e):
painter = QtGui.QPainter(self)
painter.setPen(QtCore.Qt.NoPen)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
if self.model:
self.agentimage.fill(QColor(0, 0, 0, 0))
select = None
for agent in self.model.agents:
self.paintAgent(painter, agent)
if agent.selected:
select = agent
if select:
path = QPainterPath()
path.addRect(0, 0, self.model.width, self.model.height)
path.addEllipse(
select.x - select.size * 1.5,
select.y - select.size * 1.5,
select.size * 3,
select.size * 3,
)
painter.setBrush(QColor(0, 0, 0, 150))
painter.drawPath(path)
painter.end()
def paintAgent(self, painter, agent):
r, g, b = agent.color
painter.setBrush(QColor(r, g, b))
painter.setPen(QColor(r, g, b))
if agent.shape == AgentShape.CIRCLE:
painter.drawEllipse(
agent.x - agent.size / 2,
agent.y - agent.size / 2,
agent.size,
agent.size,
)
elif agent.shape == AgentShape.ARROW:
x = agent.x
y = agent.y
d = math.radians(agent.direction)
s = agent.size
point_list = [
QPointF(x + math.cos(d) * s, y + math.sin(d) * s),
QPointF(x + math.cos(d + 2.3) * s, y + math.sin(d + 2.3) * s),
QPointF(
x + math.cos(d + math.pi) * s / 2,
y + math.sin(d + math.pi) * s / 2,
),
QPointF(x + math.cos(d - 2.3) * s, y + math.sin(d - 2.3) * s),
]
painter.drawPolygon(QPolygonF(point_list))
elif agent.shape == AgentShape.PERSON:
x = agent.x - agent.size / 2
y = agent.y - agent.size / 2
size = agent.size
point_list = [
QPointF(x + 0.4 * size, y + 0.4 * size),
QPointF(x + 0.2 * size, y + 0.5 * size),
QPointF(x + 0.2 * size, y + 0.6 * size),
QPointF(x + 0.4 * size, y + 0.5 * size),
QPointF(x + 0.4 * size, y + 0.8 * size),
QPointF(x + 0.2 * size, y + size),
QPointF(x + 0.3 * size, y + size),
QPointF(x + 0.5 * size, y + 0.85 * size),
QPointF(x + 0.7 * size, y + size),
QPointF(x + 0.8 * size, y + size),
QPointF(x + 0.6 * size, y + 0.8 * size),
QPointF(x + 0.6 * size, y + 0.5 * size),
QPointF(x + 0.8 * size, y + 0.6 * size),
QPointF(x + 0.8 * size, y + 0.5 * size),
QPointF(x + 0.6 * size, y + 0.4 * size),
]
painter.drawPolygon(QPolygonF(point_list))
painter.drawEllipse(x + 0.3 * size, y, 0.4 * size, 0.4 * size)
elif agent.shape == AgentShape.HOUSE:
x = agent.x - agent.size / 2
y = agent.y - agent.size / 2
size = agent.size
point_list = [
QPointF(x + 0.5 * size, y),
QPointF(x, y + 0.5 * size),
QPointF(x + 0.2 * size, y + 0.5 * size),
QPointF(x + 0.2 * size, y + size),
QPointF(x + 0.40 * size, y + size),
QPointF(x + 0.40 * size, y + 0.7 * size),
QPointF(x + 0.60 * size, y + 0.7 * size),
QPointF(x + 0.60 * size, y + size),
QPointF(x + 0.8 * size, y + size),
QPointF(x + 0.8 * size, y + 0.5 * size),
QPointF(x + size, y + 0.5 * size),
]
painter.drawPolygon(QPolygonF(point_list))
class SimulationArea(QtWidgets.QStackedLayout):
def __init__(self, wrapper, model):
super().__init__(wrapper)
self.addWidget(AgentArea(model))
self.addWidget(LineArea(model))
self.addWidget(ShapeArea(model))
self.addWidget(TileArea(model))
self.setStackingMode(1)
self.enable_rendering = True
self.__model = model
def draw(self):
for i in range(self.count()):
self.widget(i).update()
def mousePressEvent(self, e):
x = e.localPos().x()
y = e.localPos().y()
self.model.mouse_click(x, y)
def contextMenuEvent(self, event):
# Create menu
menu = QtWidgets.QMenu(self)
if self.enable_rendering:
pause_action = menu.addAction("Pause rendering")
else:
pause_action = menu.addAction("Start rendering")
# Open menu
action = menu.exec_(self.mapToGlobal(event.pos()))
# Handle user choice
if action == pause_action:
self.enable_rendering = not self.enable_rendering
class QtGraph(QChartView):
def __init__(self, spec):
super().__init__(None)
self.spec = spec
self.chart = QChart()
# self.chart.setTitle(str(self.spec.variables))
# self.chart.legend().hide()
for i in range(len(self.spec.variables)):
series = QLineSeries()
series.setColor(
QColor(
self.spec.colors[i][0],
self.spec.colors[i][1],
self.spec.colors[i][2],
)
)
series.setName(self.spec.variables[i])
self.chart.addSeries(series)
self.setMinimumWidth(400)
self.setMinimumHeight(230)
self.setChart(self.chart)
self.setRenderHint(QPainter.Antialiasing)
self.chart.createDefaultAxes()
self.autoscale_y_axis = True
if self.spec.min_y and self.spec.max_y:
self.autoscale_y_axis = False
self.chart.axes()[1].setRange(self.spec.min_y, self.spec.max_y)
self._updates_per_second = 60
self._data = []
self._min = 0
self._max = 0
def clear(self):
for chart in self.chart.series():
chart.clear()
self._data = []
def add_data(self, data):
self._data.append(data)
def redraw(self):
if len(self._data) > 0:
for i in range(len(self.spec.variables)):
data = [datapoint[i] for datapoint in self._data]
datapoint = sum(data) / len(data)
self.chart.series()[i].append(
QPointF(
self.chart.series()[i].count()
/ self._updates_per_second,
datapoint,
)
)
self._min = min(self._min, datapoint)
self._max = max(self._max, datapoint)
self.chart.axes()[0].setRange(
0, (self.chart.series()[0].count() - 1) / self._updates_per_second
)
diff = self._max - self._min
if self.autoscale_y_axis:
if diff > 0:
self.chart.axes()[1].setRange(self._min, self._max)
else:
self.chart.axes()[1].setRange(self._min - 0.5, self._max + 0.5)
self._data = []
class QtBarChart(QChartView):
def __init__(self, spec):
super().__init__(None)
self.spec = spec
self.chart = QChart()
# self.chart.setTitle(str(self.spec.variables))
self.chart.legend().hide()
self.mainset = QBarSet("")
self.mainset.append([0 for i in range(len(spec.variables))])
self.mainset.setColor(
QColor(spec.color[0], spec.color[1], spec.color[2])
)
self.series = QBarSeries()
self.series.append(self.mainset)
self.setMinimumWidth(400)
self.setMinimumHeight(230)
self.axis_x = QBarCategoryAxis()
self.axis_y = QValueAxis()
self.axis_x.append(spec.variables)
self.chart.addSeries(self.series)
self.chart.setAxisX(self.axis_x, self.series)
self.chart.setAxisY(self.axis_y, self.series)
self.setChart(self.chart)
self.setRenderHint(QPainter.Antialiasing)
self._updates_per_second = 10
self._dataset = []
def clear(self):
self._dataset = []
def update_data(self, dataset):
data = []
for d in dataset:
data.append(d)
self._dataset = data
def redraw(self):
if len(self._dataset) > 0:
for i in range(len(self._dataset)):
self.mainset.replace(i, self._dataset[i])
self.axis_y.setRange(0, max(self._dataset))
class QtHistogram(QChartView):
def __init__(self, spec):
super().__init__(None)
self.spec = spec
self.chart = QChart()
self.chart.setTitle(self.spec.variable)
self.chart.legend().hide()
self.mainset = QBarSet("")
self.mainset.append([0] * len(spec.bins))
self.mainset.setColor(
QColor(spec.color[0], spec.color[1], spec.color[2])
)
self.series = QBarSeries()
self.series.append(self.mainset)
self.setMinimumWidth(400)
self.setMinimumHeight(230)
self.y_ranges = [0, 1, 5, 10, 25, 50, 100, 250, 500, 1000]
self.max_y = 1000
self.max_y_range = 1000
self.lookback = 30
self.recent_max_y = deque([self.max_y_range] * self.lookback)
font = QtGui.QFont()
font.setPixelSize(10)
self.axis_x = QBarCategoryAxis()
self.axis_x.setLabelsAngle(-90)
self.axis_x.setLabelsFont(font)
self.axis_y = QValueAxis()
self.axis_y.setRange(0, self.max_y)
self.axis_x.append(map(str, spec.bins))
self.chart.addSeries(self.series)
self.chart.setAxisX(self.axis_x, self.series)
self.chart.setAxisY(self.axis_y, self.series)
self.setChart(self.chart)
self.setRenderHint(QPainter.Antialiasing)
self._updates_per_second = 10
self._dataset = []
def clear(self):
self._dataset = []
def update_data(self, dataset):
data = []
for d in dataset:
data.append(d)
self._dataset = data
def redraw(self):
if len(self._dataset) > 0:
for i in range(len(self._dataset)):
self.mainset.replace(i, self._dataset[i])
# Calculate max of current values
max_y_range = max(self._dataset)
# Store max value
self.recent_max_y.appendleft(max_y_range)
if len(self.recent_max_y) > self.lookback:
self.recent_max_y.pop()
# Set max based on the last 30 max values,
# to avoid flickering
self.max_y_range = max(self.recent_max_y)
y_range = bisect.bisect_left(self.y_ranges, self.max_y_range)
if y_range < len(self.y_ranges):
self.max_y = self.y_ranges[y_range]
elif max_y_range > self.max_y:
self.max_y += self.max_y
elif max_y_range < self.max_y / 2:
self.max_y = self.max_y / 2
self.axis_y.setRange(0, self.max_y)
class QtAgentGraph(QChartView):
def __init__(self, spec):
super().__init__(None)
self.spec = spec
self.chart = QChart()
self.chart.setTitle(str(self.spec.variable))
self.chart.legend().hide()
self.setMinimumWidth(400)
self.setMinimumHeight(230)
self.setChart(self.chart)
self.setRenderHint(QPainter.Antialiasing)
self.chart.createDefaultAxes()
self.autoscale_y_axis = True
if self.spec.min_y and self.spec.max_y:
self.autoscale_y_axis = False
self.chart.axes()[1].setRange(self.spec.min_y, self.spec.max_y)
self.axis_x = QValueAxis()
self.axis_y = QValueAxis()
self.chart.addAxis(self.axis_x, Qt.AlignBottom)
self.chart.addAxis(self.axis_y, Qt.AlignLeft)
self._updates_per_second = 60
self._data = []
self._min = 0
self._max = 0
def clear(self):
for chart in self.chart.series():
chart.clear()
self._data = []
def update_data(self):
for a in self.spec.agents:
if not hasattr(a, "_agent_series"):
a._agent_series = QLineSeries()
a._agent_series.setColor(
QColor(a.color[0], a.color[1], a.color[2])
)
a._agent_series_data = [getattr(a, self.spec.variable)]
self.chart.addSeries(a._agent_series)
a._agent_series.attachAxis(self.chart.axisX())
a._agent_series.attachAxis(self.chart.axisY())
else:
a._agent_series_data.append(getattr(a, self.spec.variable))
def redraw(self):
for a in self.spec.agents:
if hasattr(a, "_agent_series") and len(a._agent_series_data) > 0:
datapoint = sum(a._agent_series_data) / len(
a._agent_series_data
)
a._agent_series.append(
QPointF(
a._agent_series.count() / self._updates_per_second,
datapoint,
)
)
self._min = min(self._min, datapoint)
self._max = max(self._max, datapoint)
a._agent_series.setColor(
QColor(a.color[0], a.color[1], a.color[2])
)
a._agent_series_data = []
if len(self.spec.agents) > 0:
first_agent = self.spec.agents[0]
if hasattr(first_agent, "_agent_series"):
first_series = first_agent._agent_series
self.chart.axes()[0].setRange(
0, (first_series.count() - 1) / self._updates_per_second
)
diff = self._max - self._min
if self.autoscale_y_axis:
if diff > 0:
self.chart.axes()[1].setRange(self._min, self._max)
else:
self.chart.axes()[1].setRange(
self._min - 0.5, self._max + 0.5
)
class ToggleButton(QtWidgets.QPushButton):
def __init__(self, text, func, model):
super().__init__(text)
self.setCheckable(True)
self.model = model
self.func = func
# Based on https://stackoverflow.com/a/50300848/
class Slider(QtWidgets.QHBoxLayout):
def __init__(self, variable, minval, maxval, initial):
super().__init__()
label = QtWidgets.QLabel()
label.setText(variable)
self.addWidget(label)
self.sliderBar = QtWidgets.QSlider(QtCore.Qt.Horizontal)
self.sliderBar.factor = 1000
self.sliderBar.setMinimum(minval * self.sliderBar.factor)
self.sliderBar.setMaximum(maxval * self.sliderBar.factor)
self.sliderBar.setValue(initial * self.sliderBar.factor)
self.sliderBar.setMinimumWidth(150)
self.addWidget(self.sliderBar)
self.indicator = QtWidgets.QLabel()
self.indicator.setText(str(initial))
self.addWidget(self.indicator)
class Monitor(QtWidgets.QLabel):
def __init__(self, variable, model):
super().__init__()
self.variable = variable
self.setText(variable + ": -")
self.model = model
def update_label(self):
if hasattr(self.model, self.variable):
self.setText(
self.variable + ": " + str(getattr(self.model, self.variable))
)
class Checkbox(QtWidgets.QCheckBox):
def __init__(self, variable):
super().__init__(variable)
self.setText(variable)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, model):
self.model = model
super().__init__()
def closeEvent(self, event):
self.model.close()
super().closeEvent(event)
class Application:
def __init__(self, model):
self.model = model
self.logic_timer = QtCore.QTimer()
self.logic_timer.timeout.connect(self.update_logic)
self.graphics_timer = QtCore.QTimer()
self.graphics_timer.timeout.connect(self.update_graphics)
self.initializeUI()
def initializeUI(self):
# Initialize main window and central widget
self.mainwindow = MainWindow(self.model)
self.mainwindow.setWindowTitle(self.model.title)
self.centralwidget = QtWidgets.QWidget(self.mainwindow)
self.mainwindow.setCentralWidget(self.centralwidget)
# Add horizontal divider
self.horizontal_divider = QtWidgets.QHBoxLayout(self.centralwidget)
self.centralwidget.setLayout(self.horizontal_divider)
# Box for left side (simulation area + controllers)
self.left_box = QtWidgets.QVBoxLayout()
self.constrain_widget = QtWidgets.QWidget()
self.constrain_widget.setLayout(self.left_box)
self.constrain_widget.setMaximumSize(
self.model.width, self.constrain_widget.maximumHeight()
)
self.horizontal_divider.addWidget(self.constrain_widget)
self.controllers = []
# Box for right side (plots)
self.right_box = QtWidgets.QVBoxLayout()
self.plots_box = QtWidgets.QVBoxLayout()
self.horizontal_divider.addLayout(self.right_box)
self.right_box.addLayout(self.plots_box)
# self.right_box.addStretch(1)
# Simulation area
self.area_wrapper = QtWidgets.QWidget()
self.simulation_area = SimulationArea(self.area_wrapper, self.model)
self.area_wrapper.setFixedSize(self.model.width, self.model.height)
self.left_box.addWidget(self.area_wrapper)
# Controller box (bottom left)
self.controller_box = QtWidgets.QVBoxLayout()
self.left_box.addLayout(self.controller_box)
self.left_box.addStretch(1)
self.add_controllers(self.model.controller_rows, self.controller_box)
self.mainwindow.show()
# For some reason best to add matplotlib plots after the
# MainWindow is shown, otherwise the plot size isn't adjusted
# to the window size
self.add_plots(self.model.plot_specs, self.plots_box)
# Start timers
self.logic_timer.start(1000 / 60)
self.graphics_timer.start(1000 / 30)
def update_logic(self):
if not self.model.is_paused():
for controller in self.controllers:
if (
isinstance(controller, ToggleButton)
and controller.isChecked()
):
controller.func(controller.model)
elif isinstance(controller, Monitor):
controller.update_label()
def update_graphics(self):
if self.simulation_area.enable_rendering:
self.simulation_area.draw()
for p in self.model.plots:
p.redraw()
def add_button(self, button_spec, row):
btn = QtWidgets.QPushButton(button_spec.label)
btn.clicked.connect(lambda x: button_spec.function(self.model))
row.addWidget(btn)
self.controllers.append(btn)
def add_toggle(self, toggle_spec, row):
btn = ToggleButton(toggle_spec.label, toggle_spec.function, self.model)
row.addWidget(btn)
self.controllers.append(btn)
def add_slider(self, slider_spec, row):
slider = Slider(
slider_spec.variable,
slider_spec.minval,
slider_spec.maxval,
slider_spec.initial,
)
def update_variable(v):
value = v / slider.sliderBar.factor
setattr(self.model, slider_spec.variable, value)
slider.indicator.setText(str(value))
slider.sliderBar.valueChanged.connect(update_variable)
row.addLayout(slider)
self.controllers.append(slider)
def add_checkbox(self, checkbox_spec, row):
checkbox = Checkbox(checkbox_spec.variable)
def update_variable(v):
setattr(self.model, checkbox_spec.variable, checkbox.isChecked())
checkbox.stateChanged.connect(update_variable)
row.addWidget(checkbox)
self.controllers.append(checkbox)
def add_monitor(self, monitor_spec, plots_box):
monitor = Monitor(monitor_spec.variable, self.model)
plots_box.addWidget(monitor)
self.controllers.append(monitor)
def add_line_chart(self, line_chart_spec, plots_box):
chart = QtGraph(line_chart_spec)
plots_box.addWidget(chart)
self.model.plots.add(chart)
def add_bar_chart(self, bar_chart_spec, plots_box):
chart = QtBarChart(bar_chart_spec)
plots_box.addWidget(chart)
self.model.plots.add(chart)
def add_histogram(self, histogram_spec, plots_box):
histogram = QtHistogram(histogram_spec)
plots_box.addWidget(histogram)
self.model.plots.add(histogram)
def add_agent_graph(self, agent_graph_spec, plots_box):
chart = QtAgentGraph(agent_graph_spec)
plots_box.addWidget(chart)
self.model.plots.add(chart)
def add_controllers(self, rows, controller_box):
first_row = True
for row in rows:
# Create a horizontal box layout for this row
rowbox = QtWidgets.QHBoxLayout()
controller_box.addLayout(rowbox)
if first_row:
first_row = False
# Add controllers
for controller in row:
if isinstance(controller, ButtonSpec):
self.add_button(controller, rowbox)
elif isinstance(controller, ToggleSpec):
self.add_toggle(controller, rowbox)
elif isinstance(controller, SliderSpec):
self.add_slider(controller, rowbox)
elif isinstance(controller, CheckboxSpec):
self.add_checkbox(controller, rowbox)
elif isinstance(controller, MonitorSpec):
self.add_monitor(controller, rowbox)
rowbox.addStretch(1)
def add_plots(self, plot_specs, plots_box):
for plot_spec in plot_specs:
if type(plot_spec) is LineChartSpec:
self.add_line_chart(plot_spec, plots_box)
elif type(plot_spec) is BarChartSpec:
self.add_bar_chart(plot_spec, plots_box)
elif type(plot_spec) is HistogramSpec:
self.add_histogram(plot_spec, plots_box)
elif type(plot_spec) is AgentGraphSpec:
self.add_agent_graph(plot_spec, plots_box)
def run(model):
# Initialize application
qapp = QtWidgets.QApplication(sys.argv)
# We need to store a reference to the application, even though we are not
# using it, as otherwise it will be garbage-collected and the UI will get
# some very weird behavior.
app = Application(model) # noqa: F841
# Launch the application
qapp.exec_()
# Temporarily disabling sys.exit(0), as
# it provokes an error / stack trace being shown
# Application was closed, clean up and exit
# sys.exit(0)
def quick_run():
run(get_quickstart_model()) | AgentsPy | /AgentsPy-1.0.tar.gz/AgentsPy-1.0/agents/ui.py | ui.py |
import math
import random
import operator
import colorsys
from enum import Enum
class AgentShape(Enum):
CIRCLE = 1
ARROW = 2
PERSON = 3
HOUSE = 4
class AgentPath:
def __init__(self):
self.__not_drawn = []
self.__drawn = []
def add_point(self, old, new):
self.__not_drawn.append((old, new))
def get_not_drawn(self):
return self.__not_drawn
def mark_as_drawn(self):
self.__drawn.extend(self.__not_drawn)
self.__not_drawn = []
class Agent:
"""
Creates an agent with a random position, direction and color. Has no
initial model; this must be provided by ``Agent.set_model``.
"""
def __init__(self):
# Destroyed agents are not drawn and are removed from their area.
self.__destroyed = False
# Number of edges in the regular polygon representing the agent.
self.__resolution = 10
# Generate agent color in HSL and convert to RGB, to avoid
# dark colors, with low contrast to the default black
# background
hue = random.random()
saturation = random.uniform(0.8, 1.0)
lightness = random.uniform(0.25, 1.0)
r, g, b = colorsys.hls_to_rgb(hue, lightness, saturation)
self.__color = (int(r * 255), int(g * 255), int(b * 255))
self.x = 0
self.y = 0
self.__size = 8
self.__direction = random.randint(0, 359)
self.speed = 1
self.__current_tile = None
self.__draw_path = False
self.path = AgentPath()
self.__prev_pos = (self.x, self.y)
self.selected = False
self.__shape = AgentShape.ARROW
# Associated simulation area.
get_quickstart_model().add_agent(self, setup=False)
# Should be overwritten by a subclass
def setup(self, model):
"""
This method is run when the agent is added to a model. The method is
empty by default, and is intented to be overwritten by a subclass.
Parameters
----------
model
The model object that the agent has been added to.
"""
pass
# Update current tile
def update_current_tile(self):
"""
Updates the tile that the agent is currently standing on.
Effectively, this removes the agent from the set of agents standing on
the previous tile, and adds it to the set of agents standing on the
current tile.
"""
new_tile = self.current_tile()
if not self.__current_tile:
self.__current_tile = new_tile
self.__current_tile.add_agent(self)
elif not (self.__current_tile is new_tile):
self.__current_tile.remove_agent(self)
new_tile.add_agent(self)
self.__current_tile = new_tile
# To be called after each movement step
def __post_move(self):
skip_draw = False # Dont draw a path while wrapping around
if self.__model.wrapping():
skip_draw = self.__wraparound()
else:
self.__stay_inside()
self.update_current_tile()
new_pos = (self.x, self.y)
if self.__draw_path and not skip_draw:
self.path.add_point(self.__prev_pos, new_pos)
self.__prev_pos = new_pos
# Makes the agent wrap around the simulation area
def __wraparound(self):
# We've found need to introduce this hack, where we do modulus
# twice, as there's some problems with the built-in Python
# modulus operator
# Example where it's necessary:
# >>> -1.8369701987210297e-16 % 400
# 400.0
#
# This should've returned 0.
prev_x = self.x
prev_y = self.y
self.x = self.x % self.__model.width % self.__model.width
self.y = self.y % self.__model.height % self.__model.height
# Returns true if a wrap occurred
return prev_x != self.x or prev_y != self.y
# If the agent is outside the simulation area,
# return it to the closest point inside
def __stay_inside(self):
epsilon = 0.0001 # Due to a bug with current_tile detection
self.x = min(max(self.x, 0 + epsilon), self.__model.width - epsilon)
self.y = min(max(self.y, 0 + epsilon), self.__model.height - epsilon)
def center_in_tile(self):
"""
Move the agent to the center of the tile it is standing on.
"""
w = self.__model.width
h = self.__model.height
tx = self.__model.x_tiles
ty = self.__model.y_tiles
self.x = math.floor(self.x * tx / w) * w / tx + (w / tx) / 2
self.y = math.floor(self.y * ty / h) * h / ty + (h / ty) / 2
self.__post_move()
def jump_to(self, x, y):
"""
Move the agent to a specified point.
Parameters
----------
x
Destination x-coordinate.
y
Destination y-coordinate.
"""
self.x = x
self.y = y
self.__post_move()
def jump_to_tile(self, t):
"""
Move the agent to the center of a specified tile.
Parameters
----------
t
Destination tile.
"""
w = self.__model.width
h = self.__model.height
x_tiles = self.__model.x_tiles
y_tiles = self.__model.y_tiles
self.x = t.x * w / x_tiles
self.y = t.y * h / y_tiles
self.center_in_tile()
self.__post_move()
def set_model(self, model):
"""
Provides the Model object that the agents belongs to.
The stored model is used in other methods such as
``Agent.agents_nearby`` and ``Agent.current_tile``, which rely on
information about other objects in the model.
Parameters
----------
model
The model to assign the agent to.
"""
self.__model = model
def direction_to(self, other_x, other_y):
"""
Calculate the direction in degrees from the agent to a given point.
Parameters
----------
other_x
The x-coordinate of the target point.
other_y
The y-coordinate of the target point.
"""
direction = 0
dist = self.distance_to(other_x, other_y)
if dist > 0:
direction = math.degrees(math.acos((other_x - self.x) / dist))
if (self.y - other_y) > 0:
direction = 360 - direction
return direction
def point_towards(self, other_x, other_y):
"""
Make the agent orient itself towards a given point.
Parameters
----------
other_x
The x-coordinate of the target point.
other_y
The y-coordinate of the target point.
"""
dist = self.distance_to(other_x, other_y)
if dist > 0:
self.direction = math.degrees(math.acos((other_x - self.x) / dist))
if (self.y - other_y) > 0:
self.direction = 360 - self.direction
def forward(self, distance=None):
"""
Moves the agent forward in the direction it is currently facing.
Parameters
----------
Distance
The distance to move the agent. If none is specified, it moves a
distance equal to its speed-attribute.
"""
if distance is None:
distance = self.speed
self.x += math.cos(math.radians(self.direction)) * distance
self.y += math.sin(math.radians(self.direction)) * distance
self.__post_move()
def backward(self, distance=None):
"""
Moves the agent in the opposite direction of its current orientation.
Parameters
----------
Distance
The distance to move the agent. If none is specified, it moves a
distance equal to its speed-attribute.
"""
if distance is None:
distance = self.speed
self.x -= math.cos(math.radians(self.direction)) * distance
self.y -= math.sin(math.radians(self.direction)) * distance
self.__post_move()
def rotate(self, degrees):
"""
Make the agent turn the given number of degrees. Positive is
counter-clockwise, negative is clockwise.
Parameters
----------
degrees
The amount of degrees to turn.
"""
self.direction += degrees
def distance_to(self, other_x, other_y):
"""
Returns the distance between the agent and another point.
Parameters
----------
other_x
The x-coordinate of the target point.
other_y
The y-coordinate of the target point.
"""
return ((self.x - other_x) ** 2 + (self.y - other_y) ** 2) ** 0.5
def agents_nearby(self, distance, agent_type=None):
"""
Returns a list of nearby agents.
May take a type as argument and only return agents of that type.
Parameters
----------
distance
The radius around the agent to search in.
agent_type
If provided, only returns agents of this type.
"""
nearby = set()
for a in self.__model.agents:
if self.distance_to(a.x, a.y) <= distance and not (a is self):
if agent_type is None or type(a) is agent_type:
nearby.add(a)
return nearby
def current_tile(self):
"""
Returns the tile that the agent is currently standing on, based on its
coordinates.
The tile returned is the one that overlaps with the exact center of the
agent, so even if the agent visually covers multiple tiles due to its
size, only one tile is returned.
"""
x = math.floor((self.__model.x_tiles * self.x) / self.__model.width)
y = math.floor((self.__model.y_tiles * self.y) / self.__model.height)
return self.__model.tile(x, y)
def neighbor_tiles(self):
"""
Returns the surrounding tiles as a 3x3 grid. Includes the current tile.
"""
return self.nearby_tiles(-1, -1, 1, 1)
def nearby_tiles(self, x1, y1, x2, y2):
"""
Returns a rectangle of tiles relative to the agent's current position.
Parameters
----------
x1
The x-coordinate of the top-left tile
(relative to the current tile).
y1
The y-coordinate of the top-left tile
(relative to the current tile).
x2
The x-coordinate of the bottom-right tile
(relative to the current tile).
y2
The y-coordinate of the bottom-right tile
(relative to the current tile).
"""
tile = self.__current_tile
tiles = []
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
tiles.append(self.__model.tile((tile.x + x), (tile.y + y)))
return tiles
def is_destroyed(self):
"""
Returns True or False whether or not the agent is destroyed.
"""
return self.__destroyed
def destroy(self):
"""
Marks the agent for destruction, removing it from the set of agents in
the model.
"""
if not self.__destroyed:
self.__destroyed = True
def pendown(self):
self.__draw_path = True
def penup(self):
self.__stored_paths = False
def get_stored_paths(self):
return self.__stored_paths
def clear_stored_paths(self):
self.__stored_paths = []
@property
def color(self):
"""
The color of the agent. Must be provided as an RGB 3-tuple, e.g. (255,
255, 255) to color the agent white.
"""
return self.__color
@color.setter
def color(self, color):
r, g, b = color
self.__color = [r, g, b]
@property
def direction(self):
"""
The direction of the agent, measured in degrees.
"""
return self.__direction % 360
@direction.setter
def direction(self, direction):
self.__direction = direction % 360
@property
def size(self):
"""
The size of the agent. For an agent with the circle shape, this
corresponds to its radius.
"""
return self.__size
@size.setter
def size(self, size):
self.__size = size
@property
def shape(self):
"""
The shape of the agent.
"""
return self.__shape
@shape.setter
def shape(self, shape):
self.__shape = shape
class Tile:
"""
Creates a tile. *x* and *y* is the tile's position in the *tile grid*, not
absolute coordinates for the model.
Parameters
----------
x
The tile's x-coordinate in the tile grid.
y
The tile's y-cooridnate in the tile grid.
model
The model that the tile is a part of.
"""
def __init__(self, x, y, model):
self.x = x
self.y = y
self.info = {}
self.__color = (0, 0, 0)
self.__agents = set()
self.__model = model
def add_agent(self, agent):
"""
Adds an Agent to the set of agents standing on the tile. Usually called
by the method ``Agent.update_current_tile``.
Parameters
----------
agent
The agent to add.
"""
self.__agents.add(agent)
def remove_agent(self, agent):
"""
Removes an Agent ``agent`` from the set of agents standing on the tile.
Usually called by the method ``Agent.update_current_tile``.
Parameters
----------
agent
The agent to remove.
"""
self.__agents.discard(agent)
def get_agents(self):
"""
Gets the set of agents currently on the tile.
"""
return self.__agents
@property
def color(self):
"""
The color of the agent. Must be provided as an RGB 3-tuple, e.g. (255,
255, 255) to color the agent white.
"""
return self.__color
@color.setter
def color(self, color):
r, g, b = color
if self.__color != [r, g, b]:
self.__model._vu_tiles.append(self)
self.__color = [r, g, b]
class Spec:
pass
class ButtonSpec(Spec):
def __init__(self, label, function):
self.label = label
self.function = function
class ToggleSpec(Spec):
def __init__(self, label, function):
self.label = label
self.function = function
class SliderSpec(Spec):
def __init__(self, variable, initial, minval, maxval):
self.variable = variable
self.minval = minval
self.maxval = maxval
self.initial = initial
class CheckboxSpec(Spec):
def __init__(self, variable):
self.variable = variable
class LineChartSpec(Spec):
def __init__(self, variables, colors, min_y, max_y):
self.variables = variables
self.colors = colors
self.min_y = min_y
self.max_y = max_y
class MonitorSpec(Spec):
def __init__(self, variable):
self.variable = variable
class BarChartSpec(Spec):
def __init__(self, variables, color):
self.variables = variables
self.color = color
class HistogramSpec(Spec):
def __init__(self, variable, minimum, maximum, intervals, color):
self.variable = variable
self.minimum = minimum
self.maximum = maximum
i_size = (maximum - minimum) / intervals
self.bins = [
(minimum + i_size * i, minimum + i_size * (i + 1))
for i in range(intervals)
]
self.color = color
class AgentGraphSpec(Spec):
def __init__(self, agents, variable, min_y, max_y):
self.agents = agents
self.variable = variable
self.min_y = min_y
self.max_y = max_y
class EllipseStruct:
def __init__(self, x, y, w, h, color):
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
class RectStruct:
def __init__(self, x, y, w, h, color):
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
class Model:
"""
Creates a model with the given title. There are two ways of creating a
model; creating a blank model of size *x_tiles* times *y_tiles* with no
predetermined data, or creating a model with predetermined data from a
*cell_data_fille*.
Parameters
----------
title
The title of the model (to show in the simulation window).
x_tiles
The number of tiles on the x-axis. Ignored if a *cell_data_file* is
provided.
y_tiles
The number of tiles on the y-axis. Ignored if a *cell_data_file* is
provided.
tile_size
The width/height of each tile in pixels.
cell_data_file
If provided, generates a model from the data file instead. The data is
not immediately to the tiles, but must be applied with
``Model.reload()``.
"""
def __init__(
self, title, x_tiles=50, y_tiles=50, tile_size=8, cell_data_file=None
):
# Title of model, shown in window title
self.title = title
if not cell_data_file:
# Number of tiles on the x/y axis.
self.x_tiles = x_tiles
self.y_tiles = y_tiles
else:
cell_data = open(cell_data_file, "r")
cell_data.readline()
cell_data.readline()
header_line = cell_data.readline()[:-1]
self.header_info = header_line.split("\t")
self.x_tiles = 0
self.y_tiles = 0
self.load_data = []
for line in cell_data:
cell = line[:-1].split("\t")
x = int(cell[0])
y = int(cell[1])
self.x_tiles = max(x + 1, self.x_tiles)
self.y_tiles = max(y + 1, self.y_tiles)
self.load_data.append(cell)
cell_data.close()
# Initial tileset (empty).
self.tiles = [
Tile(x, y, self)
for y in range(self.y_tiles)
for x in range(self.x_tiles)
]
# Pixel sizes
self.tile_size = tile_size
self.width = self.x_tiles * tile_size
self.height = self.y_tiles * tile_size
self.__agents = []
self.variables = {}
self.plot_specs = []
self.controller_rows = []
self.add_controller_row()
self.plots = set() # Filled in during initialization
self.show_direction = False
self._paused = False
self._wrapping = True
self._close_func = None
self._shapes = []
# Model elements that have been visually updated
self._vu_tiles = []
def add_agent(self, agent, setup=True):
"""
Adds an agent to the model.
Parameters
----------
agent
The agent to add to the model.
setup
Whether or not to run the agent's ``setup`` function (default
``True``).
"""
agent.set_model(self)
agent.jump_to(
random.randint(0, self.width), random.randint(0, self.height)
)
agent.update_current_tile()
self.__agents.append(agent)
if setup:
agent.setup(self)
for plot in self.plots:
if type(plot.spec) is AgentGraphSpec:
plot.spec.agents.append(agent)
def add_agents(self, agents):
"""
Adds a collection of agents.
Parameters
----------
agents
The agents to add.
"""
for a in agents:
self.add_agent(a)
def tile(self, x, y):
"""
Returns the tile at the (x,y) position in the tile-grid (*not* the
(x,y) position of the simulation area).
Parameters
----------
x
The x-coordinate of the tile.
y
The y-coordinate of the tile.
"""
row = y % self.y_tiles
column = x % self.x_tiles
return self.tiles[row * self.x_tiles + column]
# Based on
# kite.com
# /python
# /answers
# /how-to-sort-a-list-of-objects-by-attribute-in-python
def agents_ordered(self, variable, increasing=True):
"""
Returns a list of agents in the model, ordered based on one of their
attributes. Agents who do not have the attribute are not included in
the list.
Parameters
----------
variable
The attribute to order by.
increasing
Whether or not to order the agents in increasing or decreasing
order (default ``True``).
"""
# Only returns the list of agents that actually have that attribute
agent_list = filter(lambda a: hasattr(a, variable), self.__agents)
ret_list = sorted(agent_list, key=operator.attrgetter(variable))
if not increasing:
ret_list.reverse()
return iter(ret_list)
# Destroys all agents, clears the agent set, and resets all tiles.
def reset(self):
"""
Resets the model by doing the following:
* Destroys all agents.
* Clears the set of agents.
* Clears the set of shapes.
* Clears all tiles (removes all of their ``info`` and colors them
black).
* Clears all plots.
* Unpauses the model.
"""
for a in self.__agents:
a.destroy()
self.__agents = []
self._shapes = []
for x in range(self.x_tiles):
for y in range(self.y_tiles):
i = y * self.x_tiles + x
self.tiles[i].color = (0, 0, 0)
self.tiles[i].info = {}
self.clear_plots()
self.unpause()
def reload(self):
"""
Applies the data from the cell-data-file to the tiles in the model.
Only usable if the model was created with a ``cell_data_file`` in the
constructor.
"""
for tile_data in self.load_data:
x = int(tile_data[0])
y = int(tile_data[1])
for i in range(2, len(tile_data)):
variable = self.header_info[i]
tile = self.tiles[y * self.x_tiles + x]
tile.info[variable] = float(tile_data[i])
def update_plots(self):
"""
Updates all plots with the relevant data. Usually called in each
iteration of the simulation (i.e. in a ``step`` function or similar).
"""
for plot in self.plots:
if type(plot.spec) is LineChartSpec:
dataset = []
for d in plot.spec.variables:
dataset.append(getattr(self, d))
plot.add_data(dataset)
elif type(plot.spec) is BarChartSpec:
dataset = []
for d in plot.spec.variables:
dataset.append(getattr(self, d))
plot.update_data(dataset)
elif type(plot.spec) is HistogramSpec:
dataset = []
for b in plot.spec.bins:
bin_count = 0
for a in self.__agents:
if hasattr(a, plot.spec.variable):
val = getattr(a, plot.spec.variable)
if val >= b[0] and val <= b[1]:
bin_count += 1
dataset.append(bin_count)
plot.update_data(dataset)
elif type(plot.spec) is AgentGraphSpec:
plot.update_data()
def remove_destroyed_agents(self):
new_agents = []
for a in self.__agents:
if not a.is_destroyed():
new_agents.append(a)
else:
a.current_tile().remove_agent(a)
self.__agents = new_agents
def clear_plots(self):
"""
Clears the data from all plots.
"""
for plot in self.plots:
plot.clear()
def mouse_click(self, x, y):
for a in self.__agents:
a.selected = False
if (
a.x - a.size / 2 < x
and a.x + a.size / 2 > x
and a.y - a.size / 2 < y
and a.y + a.size / 2 > y
):
for b in self.__agents:
b.selected = False
a.selected = True
def add_controller_row(self):
"""
Creates a new row to place controller widgets on (buttons, sliders,
etc.).
"""
self.current_row = []
self.controller_rows.append(self.current_row)
def add_button(self, label, func, toggle=False):
"""
Adds a button that runs a provided function when pressed. Can be
specified to be a toggled button, which will cause the button to
continuously call the function while toggled on.
Parameters
----------
label
The label on the button.
func
The function to run when the button is pressed.
toggle
Whether or not the button should be a toggled button.
"""
if not toggle:
self.current_row.append(ButtonSpec(label, func))
else:
self.current_row.append(ToggleSpec(label, func))
def add_slider(self, variable, initial, minval=0, maxval=100):
"""
Adds a slider that can be used to adjust the value of a variable in the
model.
Parameters
----------
variable
The name of the variable to adjust. Must be privded as a string.
minval
The minimum value of the variable.
maxval
The maximum value of the variable.
initial
The initial value of the variable.
"""
if len(self.current_row) > 0:
self.add_controller_row()
setattr(self, variable, initial)
self.variables[variable] = initial
self.current_row.append(SliderSpec(variable, initial, minval, maxval))
def add_checkbox(self, variable):
"""
Adds a checkbox that can be used to change the value of a variable
between true and false.
Parameters
----------
variable
The name of the variable to adjust. Must be provided as a string.
"""
if len(self.current_row) > 0:
self.add_controller_row()
setattr(self, variable, False)
self.current_row.append(CheckboxSpec(variable))
def line_chart(self, variables, colors, min_y=None, max_y=None):
"""
Adds a line chart to the simulation window that shows the trend of
multiple variables over time.
Parameters
----------
variables
The names of the variables. Must be provided as a list of strings.
colors
The color of each line.
min_y
The minimum value on the y-axis.
max_y
The maximum value on the y-axis.
"""
self.plot_specs.append(LineChartSpec(variables, colors, min_y, max_y))
def bar_chart(self, variables, color):
"""
Adds a bar chart to the simulation window that shows the relation
between multiple variables.
Parameters
----------
variables
The list of the variables. Must be provided as a list of strings.
color
The color of all the bars.
"""
self.plot_specs.append(BarChartSpec(variables, color))
def histogram(self, variable, minimum, maximum, bins, color):
"""
Adds a histogram to the simulation window that shows how the agents in
the model are distributed based on a specific attribute.
Parameters
----------
variable
The name of the attribute to base the distribution on. Must be
provided as a string.
minimum
The minimum value of the distribution.
maximum
The maximum value of the distribution.
bins
The number of bins in the histogram.
color
The color of all the bars.
"""
self.plot_specs.append(
HistogramSpec(variable, minimum, maximum, bins, color)
)
def agent_line_chart(self, variable, min_y=None, max_y=None):
"""
Adds a line chart to the simulation window that shows the trend of
multiple variables over time.
Parameters
----------
variables
The names of the variables. Must be provided as a list of strings.
colors
The color of each line.
min_y
The minimum value on the y-axis.
max_y
The maximum value on the y-axis.
"""
self.plot_specs.append(AgentGraphSpec([], variable, min_y, max_y))
def monitor(self, variable):
"""
Adds a single line that shows the value of the given variable.
Parameters
----------
variable
The variable to monitor.
"""
if len(self.current_row) > 0:
self.add_controller_row()
self.current_row.append(MonitorSpec(variable))
def add_ellipse(self, x, y, w, h, color):
"""
Draws an ellipse on the simulation area. Returns a shape object that
can be used to refer to the ellipse.
Parameters
----------
x
The top-left x-coordinate of the ellipse.
y
The top-left y-coordinate of the ellipse.
w
The width of the ellipse.
h
The height of the ellipse.
color
The color of the ellipse.
"""
new_shape = EllipseStruct(x, y, w, h, color)
self._shapes.append(new_shape)
return new_shape
def add_rect(self, x, y, w, h, color):
"""
Draws a square on the simulation area. Returns a shape object that can
be used to refer to the square.
Parameters
----------
x
The top-left x-coordinate of the square.
y
The top-left y-coordinate of the square.
w
The width of the square.
h
The height of the square.
color
The color of the square.
"""
new_shape = RectStruct(x, y, w, h, color)
self._shapes.append(new_shape)
return new_shape
def get_shapes(self):
"""
Returns an iterator containing all the shapes in the model.
"""
return iter(self._shapes)
def clear_shapes(self):
"""
Clears all shapes in the model.
"""
self._shapes.clear()
def is_paused(self):
"""
Returns whether the model is paused or not.
"""
return self._paused
def pause(self):
"""
Pauses the model. The main effect of this is to ignore the "on" status
of any toggled buttons, meaning that `step` functions and similar are
not run.
"""
self._paused = True
def unpause(self):
"""
Unpauses the model. See `Model.pause()`.
"""
self._paused = False
def on_close(self, func):
"""
Defines a function to be run when the simulation window is closed. This
is generally used to close any open file pointers.
"""
self._on_close = func
def close(self):
self.pause()
if self._close_func:
self._close_func(self)
def enable_wrapping(self):
"""
Enables wrapping, i.e. turns the simulation area *toroidal*. Agents
exiting the simulation area on one side will enter on the other side.
"""
self._wrapping = True
def disable_wrapping(self):
"""
Disables wrapping. Agents attempting to move outside the simulation
area will collide with the border and be moved back to the closest
point inside.
"""
self._wrapping = False
def wrapping(self):
"""
Returns whether wrapping is enabled or not.
"""
return self._wrapping
def agent_count(self):
return len(self.__agents)
@property
def agents(self):
self.remove_destroyed_agents()
return iter(self.__agents)
@agents.setter
def agents(self, agents):
self.__agents = list(agents)
def __setitem__(self, key, item):
self.variables[key] = item
def __getitem__(self, key):
return self.variables[key]
def __delitem__(self, key):
del self.variables[key]
class SimpleModel(Model):
def __init__(
self, title, x_tiles, y_tiles, setup_func, step_func, tile_size=8
):
super().__init__(title, x_tiles, y_tiles, tile_size)
self.setup_first = False
def setup_wrapper(model):
model.setup_first = True
setup_func(model)
def step_wrapper(model):
if model.setup_first:
step_func(model)
else:
print("Remember to click 'Setup' first!")
self.add_button("Setup", setup_wrapper)
self.add_button("Go", step_wrapper, toggle=True)
def get_quickstart_model():
global quickstart_model
if "quickstart_model" not in globals():
quickstart_model = Model("AgentsPy model", 50, 50)
return quickstart_model
def contains_agent_type(agents, agent_type):
"""
Returns a boolean indicating whether an agent of agent_type is in agents.
"""
for a in agents:
if type(a) == agent_type:
return True
return False
def only_agents_type(agents, agent_type):
"""
Returns agents where all agents of type agent_type are removed.
"""
agents_t = []
for a in agents:
if type(a) == agent_type:
agents_t.add(a)
return agents_t
def remove_agents_type(agents, agent_type):
"""
Returns agents where all agents not of type agent_type are removed.
"""
agents_t = []
for a in agents:
if not (type(a) == agent_type):
agents_t.add(a)
return agents_t
# kite.com/python/answers/how-to-sort-a-list-of-objects-by-attribute-in-python
def agents_ordered(agents, variable, increasing=True):
"""
Returns the agents list, sorted by variable in either increasing or
decreasing order. Prints an error if not all agents in the list have the
attribute.
"""
try:
sorted_agents = sorted(list(agents), key=operator.attrgetter(variable))
if not increasing:
sorted_agents.reverse()
return iter(sorted_agents)
except AttributeError:
print(
"Failed to sort agents. Do all agents have the attribute "
+ variable
+ " ?"
)
return agents
def agents_random(agents):
l_agents = list(agents)
random.shuffle(l_agents)
return l_agents
def destroy_agents(agents):
"""
Destroys all agents in agents.
"""
for a in agents:
a.destroy() | AgentsPy | /AgentsPy-1.0.tar.gz/AgentsPy-1.0/agents/model.py | model.py |
from multiprocessing import Pool
import multiprocessing
import random
import copy
class Individuo:
def __init__(self,inicia=None):
self.pontos=0
self.pontos_t=0
self.volta=0
self.id=int(random.random()*1000)
self.ini_d=inicia
def void():
pass
def inicia(self):
if(self.ini_d!=None):
self.ini_d()
return self
def update(self):
pass
def cross(a,b):
pass
def muta(self):
pass
def reset_individuo(self,func=void):
self.pontos=0
self.pontos_t=0
self.volta=0
func()
def semi_reset_individuo(self,func=void):
self.pontos=0
func()
def end(self):
pass
class Temp_pool:
def __call__(self, indiv):
d=copy.deepcopy(indiv)
d.update()
d.pontos_t+=d.pontos
return d
class Genetico:
def __init__(self,individuo,geracao=3,indiv=10,indiv_selec=3,mutacao=0.3,cross=0.7,voltas=1,call_inicio=True,ordena='d',show_v=False,show_g=False,thread=multiprocessing.cpu_count()):
self.geracao=geracao
self.indiv=indiv
self.mutacao=mutacao
self.indiv_selec=indiv_selec
self.cross=cross
self.voltas=voltas
self.call_inicio=call_inicio
self.individuo=individuo
self.list_indiv=[]
self.melhores=[]
self.cont_geracao=0
self.ordena=ordena
self.show_v=show_v
self.show_g=show_g
self.pool = Pool(thread)
print("Número de thread : ",thread)
def cria_populacao(self):
for i in range(self.indiv):
self.list_indiv.append(copy.deepcopy(self.individuo))
if(self.call_inicio):
#print("inicia")
self.list_indiv[-1:][0].inicia()
self.list_indiv[-1:][0].id='g: '+str(self.cont_geracao)+' - i: '+str(i)#int(random.random()*1000)
def update(self):
#att = xmp.Vectorizer(self.att_individual, num_workers=2)
#result=att.process(copy.deepcopy(self.list_indiv))
result=self.pool.map(Temp_pool(),list(self.list_indiv))
self.list_indiv=copy.deepcopy(list(result))
#for i in self.list_indiv:
# i.update()
# i.pontos_t+=i.pontos
def ordenar(self):
if(self.ordena=='d'):
aux=0
for i in range(len(self.list_indiv)):
for c in range(len(self.list_indiv)):
if(self.list_indiv[i].pontos>self.list_indiv[c].pontos):
aux=copy.deepcopy(self.list_indiv[i])
self.list_indiv[i]=copy.deepcopy(self.list_indiv[c])
self.list_indiv[c]=copy.deepcopy(aux)
if(self.ordena=='c'):
aux=0
for i in range(len(self.list_indiv)):
for c in range(len(self.list_indiv)):
if(self.list_indiv[i].pontos<self.list_indiv[c].pontos):
aux=copy.deepcopy(self.list_indiv[i])
self.list_indiv[i]=copy.deepcopy(self.list_indiv[c])
self.list_indiv[c]=copy.deepcopy(aux)
def ordenar_t(self):
if(self.ordena=='d'):
aux=0
for i in range(len(self.list_indiv)):
for c in range(len(self.list_indiv)):
if(self.list_indiv[i].pontos_t>self.list_indiv[c].pontos_t):
aux=copy.deepcopy(self.list_indiv[i])
self.list_indiv[i]=copy.deepcopy(self.list_indiv[c])
self.list_indiv[c]=copy.deepcopy(aux)
if(self.ordena=='c'):
aux=0
for i in range(len(self.list_indiv)):
for c in range(len(self.list_indiv)):
if(self.list_indiv[i].pontos_t<self.list_indiv[c].pontos_t):
aux=copy.deepcopy(self.list_indiv[i])
self.list_indiv[i]=copy.deepcopy(self.list_indiv[c])
self.list_indiv[c]=copy.deepcopy(aux)
def get_melhores(self):
self.melhores=copy.deepcopy(self.list_indiv[:self.indiv_selec])
self.list_indiv=copy.deepcopy(self.melhores)
def semi_reset(self):
for i in self.list_indiv:
i.semi_reset_individuo()
def reset(self):
for i in self.list_indiv:
i.reset_individuo()
def crossOver(self):
for i in range(self.indiv-self.indiv_selec):
self.list_indiv.append(copy.deepcopy(self.individuo))
self.list_indiv[-1:][0].inicia()
self.list_indiv[-1:][0].id='g: '+str(self.cont_geracao+1)+' - i: '+str(i)
if(self.cross>random.random()):
a,b=random.sample(self.melhores,2)
self.list_indiv[-1:][0].cross(a,b)
if(self.mutacao>random.random()):
self.list_indiv[-1:][0].muta()
def iniciar(self):
self.cria_populacao()
while True:
self.reset()
for i in range(self.voltas):
self.semi_reset()
self.update()
self.ordenar()
self.get_melhores()
if(self.show_v):
print(" --- v: {} ---".format(i))
for i in self.melhores:
print(' id: {} - pontos: {}'.format(i.id,i.pontos))
self.ordenar_t()
self.get_melhores()
if(self.show_g):
print("------- G: {} ------".format(self.cont_geracao))
for i in self.melhores:
print('id: {} - pontos: {}'.format(i.id,i.pontos_t))
self.melhores[0].end()
print('--------------------------------')
self.crossOver()
self.cont_geracao+=1
if(self.cont_geracao == self.geracao and self.geracao!=0):
break
self.melhores[0].end() | Aggenerico | /Aggenerico-0.0.3-py3-none-any.whl/aggenerico/AG.py | AG.py |
from . strings_with_arrows import *
import string
import os
import math
#######################################
# CONSTANTS
#######################################
DIGITS = '0123456789'
LETTERS = string.ascii_letters
LETTERS_DIGITS = LETTERS + DIGITS
#######################################
# ERRORS
#######################################
class Error:
def __init__(self, pos_start, pos_end, error_name, details):
self.pos_start = pos_start
self.pos_end = pos_end
self.error_name = error_name
self.details = details
def as_string(self):
result = f'{self.error_name}: {self.details}\n'
result += f'File {self.pos_start.fn}, line {self.pos_start.ln + 1}'
result += '\n\n' + string_with_arrows(self.pos_start.ftxt, self.pos_start, self.pos_end)
return result
class IllegalCharError(Error):
def __init__(self, pos_start, pos_end, details):
super().__init__(pos_start, pos_end, 'Illegal Character', details)
class ExpectedCharError(Error):
def __init__(self, pos_start, pos_end, details):
super().__init__(pos_start, pos_end, 'Expected Character', details)
class InvalidSyntaxError(Error):
def __init__(self, pos_start, pos_end, details=''):
super().__init__(pos_start, pos_end, 'Invalid Syntax', details)
class RTError(Error):
def __init__(self, pos_start, pos_end, details, context):
super().__init__(pos_start, pos_end, 'Runtime Error', details)
self.context = context
def as_string(self):
result = self.generate_traceback()
result += f'{self.error_name}: {self.details}'
result += '\n\n' + string_with_arrows(self.pos_start.ftxt, self.pos_start, self.pos_end)
return result
def generate_traceback(self):
result = ''
pos = self.pos_start
ctx = self.context
while ctx:
result = f' File {pos.fn}, line {str(pos.ln + 1)}, in {ctx.display_name}\n' + result
pos = ctx.parent_entry_pos
ctx = ctx.parent
return 'Traceback (most recent call last):\n' + result
#######################################
# POSITION
#######################################
class Position:
def __init__(self, idx, ln, col, fn, ftxt):
self.idx = idx
self.ln = ln
self.col = col
self.fn = fn
self.ftxt = ftxt
def advance(self, current_char=None):
self.idx += 1
self.col += 1
if current_char == '\n':
self.ln += 1
self.col = 0
return self
def copy(self):
return Position(self.idx, self.ln, self.col, self.fn, self.ftxt)
#######################################
# TOKENS
#######################################
TT_INT = 'INT'
TT_FLOAT = 'FLOAT'
TT_STRING = 'STRING'
TT_IDENTIFIER = 'IDENTIFIER'
TT_KEYWORD = 'KEYWORD'
TT_PLUS = 'PLUS'
TT_MINUS = 'MINUS'
TT_MUL = 'MUL'
TT_DIV = 'DIV'
TT_POW = 'POW'
TT_EQ = 'EQ'
TT_LPAREN = 'LPAREN'
TT_RPAREN = 'RPAREN'
TT_LSQUARE = 'LSQUARE'
TT_RSQUARE = 'RSQUARE'
TT_EE = 'EE'
TT_NE = 'NE'
TT_LT = 'LT'
TT_GT = 'GT'
TT_LTE = 'LTE'
TT_GTE = 'GTE'
TT_COMMA = 'COMMA'
TT_ARROW = 'ARROW'
TT_NEWLINE = 'NEWLINE'
TT_EOF = 'EOF'
KEYWORDS = [
'VAR',
'AND',
'OR',
'NOT',
'IF',
'ELIF',
'ELSE',
'FOR',
'TO',
'STEP',
'WHILE',
'FUN',
'THEN',
'END',
'RETURN',
'CONTINUE',
'BREAK',
]
class Token:
def __init__(self, type_, value=None, pos_start=None, pos_end=None):
self.type = type_
self.value = value
if pos_start:
self.pos_start = pos_start.copy()
self.pos_end = pos_start.copy()
self.pos_end.advance()
if pos_end:
self.pos_end = pos_end.copy()
def matches(self, type_, value):
return self.type == type_ and self.value == value
def __repr__(self):
if self.value: return f'{self.type}:{self.value}'
return f'{self.type}'
#######################################
# LEXER
#######################################
class Lexer:
def __init__(self, fn, text):
self.fn = fn
self.text = text
self.pos = Position(-1, 0, -1, fn, text)
self.current_char = None
self.advance()
def advance(self):
self.pos.advance(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def make_tokens(self):
tokens = []
while self.current_char != None:
if self.current_char in ' \t':
self.advance()
elif self.current_char == '#':
self.skip_comment()
elif self.current_char in ';\n':
tokens.append(Token(TT_NEWLINE, pos_start=self.pos))
self.advance()
elif self.current_char in DIGITS:
tokens.append(self.make_number())
elif self.current_char in LETTERS:
tokens.append(self.make_identifier())
elif self.current_char == '"':
tokens.append(self.make_string())
elif self.current_char == '+':
tokens.append(Token(TT_PLUS, pos_start=self.pos))
self.advance()
elif self.current_char == '-':
tokens.append(self.make_minus_or_arrow())
elif self.current_char == '*':
tokens.append(Token(TT_MUL, pos_start=self.pos))
self.advance()
elif self.current_char == '/':
tokens.append(Token(TT_DIV, pos_start=self.pos))
self.advance()
elif self.current_char == '^':
tokens.append(Token(TT_POW, pos_start=self.pos))
self.advance()
elif self.current_char == '(':
tokens.append(Token(TT_LPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == ')':
tokens.append(Token(TT_RPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == '[':
tokens.append(Token(TT_LSQUARE, pos_start=self.pos))
self.advance()
elif self.current_char == ']':
tokens.append(Token(TT_RSQUARE, pos_start=self.pos))
self.advance()
elif self.current_char == '!':
token, error = self.make_not_equals()
if error: return [], error
tokens.append(token)
elif self.current_char == '=':
tokens.append(self.make_equals())
elif self.current_char == '<':
tokens.append(self.make_less_than())
elif self.current_char == '>':
tokens.append(self.make_greater_than())
elif self.current_char == ',':
tokens.append(Token(TT_COMMA, pos_start=self.pos))
self.advance()
else:
pos_start = self.pos.copy()
char = self.current_char
self.advance()
return [], IllegalCharError(pos_start, self.pos, "'" + char + "'")
tokens.append(Token(TT_EOF, pos_start=self.pos))
return tokens, None
def make_number(self):
num_str = ''
dot_count = 0
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in DIGITS + '.':
if self.current_char == '.':
if dot_count == 1: break
dot_count += 1
num_str += self.current_char
self.advance()
if dot_count == 0:
return Token(TT_INT, int(num_str), pos_start, self.pos)
else:
return Token(TT_FLOAT, float(num_str), pos_start, self.pos)
def make_string(self):
string = ''
pos_start = self.pos.copy()
escape_character = False
self.advance()
escape_characters = {
'n': '\n',
't': '\t'
}
while self.current_char != None and (self.current_char != '"' or escape_character):
if escape_character:
string += escape_characters.get(self.current_char, self.current_char)
else:
if self.current_char == '\\':
escape_character = True
else:
string += self.current_char
self.advance()
escape_character = False
self.advance()
return Token(TT_STRING, string, pos_start, self.pos)
def make_identifier(self):
id_str = ''
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in LETTERS_DIGITS + '_':
id_str += self.current_char
self.advance()
tok_type = TT_KEYWORD if id_str in KEYWORDS else TT_IDENTIFIER
return Token(tok_type, id_str, pos_start, self.pos)
def make_minus_or_arrow(self):
tok_type = TT_MINUS
pos_start = self.pos.copy()
self.advance()
if self.current_char == '>':
self.advance()
tok_type = TT_ARROW
return Token(tok_type, pos_start=pos_start, pos_end=self.pos)
def make_not_equals(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '=':
self.advance()
return Token(TT_NE, pos_start=pos_start, pos_end=self.pos), None
self.advance()
return None, ExpectedCharError(pos_start, self.pos, "'=' (after '!')")
def make_equals(self):
tok_type = TT_EQ
pos_start = self.pos.copy()
self.advance()
if self.current_char == '=':
self.advance()
tok_type = TT_EE
return Token(tok_type, pos_start=pos_start, pos_end=self.pos)
def make_less_than(self):
tok_type = TT_LT
pos_start = self.pos.copy()
self.advance()
if self.current_char == '=':
self.advance()
tok_type = TT_LTE
return Token(tok_type, pos_start=pos_start, pos_end=self.pos)
def make_greater_than(self):
tok_type = TT_GT
pos_start = self.pos.copy()
self.advance()
if self.current_char == '=':
self.advance()
tok_type = TT_GTE
return Token(tok_type, pos_start=pos_start, pos_end=self.pos)
def skip_comment(self):
self.advance()
while self.current_char != '\n':
self.advance()
self.advance()
#######################################
# NODES
#######################################
class NumberNode:
def __init__(self, tok):
self.tok = tok
self.pos_start = self.tok.pos_start
self.pos_end = self.tok.pos_end
def __repr__(self):
return f'{self.tok}'
class StringNode:
def __init__(self, tok):
self.tok = tok
self.pos_start = self.tok.pos_start
self.pos_end = self.tok.pos_end
def __repr__(self):
return f'{self.tok}'
class ListNode:
def __init__(self, element_nodes, pos_start, pos_end):
self.element_nodes = element_nodes
self.pos_start = pos_start
self.pos_end = pos_end
class VarAccessNode:
def __init__(self, var_name_tok):
self.var_name_tok = var_name_tok
self.pos_start = self.var_name_tok.pos_start
self.pos_end = self.var_name_tok.pos_end
class VarAssignNode:
def __init__(self, var_name_tok, value_node):
self.var_name_tok = var_name_tok
self.value_node = value_node
self.pos_start = self.var_name_tok.pos_start
self.pos_end = self.value_node.pos_end
class BinOpNode:
def __init__(self, left_node, op_tok, right_node):
self.left_node = left_node
self.op_tok = op_tok
self.right_node = right_node
self.pos_start = self.left_node.pos_start
self.pos_end = self.right_node.pos_end
def __repr__(self):
return f'({self.left_node}, {self.op_tok}, {self.right_node})'
class UnaryOpNode:
def __init__(self, op_tok, node):
self.op_tok = op_tok
self.node = node
self.pos_start = self.op_tok.pos_start
self.pos_end = node.pos_end
def __repr__(self):
return f'({self.op_tok}, {self.node})'
class IfNode:
def __init__(self, cases, else_case):
self.cases = cases
self.else_case = else_case
self.pos_start = self.cases[0][0].pos_start
self.pos_end = (self.else_case or self.cases[len(self.cases) - 1])[0].pos_end
class ForNode:
def __init__(self, var_name_tok, start_value_node, end_value_node, step_value_node, body_node, should_return_null):
self.var_name_tok = var_name_tok
self.start_value_node = start_value_node
self.end_value_node = end_value_node
self.step_value_node = step_value_node
self.body_node = body_node
self.should_return_null = should_return_null
self.pos_start = self.var_name_tok.pos_start
self.pos_end = self.body_node.pos_end
class WhileNode:
def __init__(self, condition_node, body_node, should_return_null):
self.condition_node = condition_node
self.body_node = body_node
self.should_return_null = should_return_null
self.pos_start = self.condition_node.pos_start
self.pos_end = self.body_node.pos_end
class FuncDefNode:
def __init__(self, var_name_tok, arg_name_toks, body_node, should_auto_return):
self.var_name_tok = var_name_tok
self.arg_name_toks = arg_name_toks
self.body_node = body_node
self.should_auto_return = should_auto_return
if self.var_name_tok:
self.pos_start = self.var_name_tok.pos_start
elif len(self.arg_name_toks) > 0:
self.pos_start = self.arg_name_toks[0].pos_start
else:
self.pos_start = self.body_node.pos_start
self.pos_end = self.body_node.pos_end
class CallNode:
def __init__(self, node_to_call, arg_nodes):
self.node_to_call = node_to_call
self.arg_nodes = arg_nodes
self.pos_start = self.node_to_call.pos_start
if len(self.arg_nodes) > 0:
self.pos_end = self.arg_nodes[len(self.arg_nodes) - 1].pos_end
else:
self.pos_end = self.node_to_call.pos_end
class ReturnNode:
def __init__(self, node_to_return, pos_start, pos_end):
self.node_to_return = node_to_return
self.pos_start = pos_start
self.pos_end = pos_end
class ContinueNode:
def __init__(self, pos_start, pos_end):
self.pos_start = pos_start
self.pos_end = pos_end
class BreakNode:
def __init__(self, pos_start, pos_end):
self.pos_start = pos_start
self.pos_end = pos_end
#######################################
# PARSE RESULT
#######################################
class ParseResult:
def __init__(self):
self.error = None
self.node = None
self.last_registered_advance_count = 0
self.advance_count = 0
self.to_reverse_count = 0
def register_advancement(self):
self.last_registered_advance_count = 1
self.advance_count += 1
def register(self, res):
self.last_registered_advance_count = res.advance_count
self.advance_count += res.advance_count
if res.error: self.error = res.error
return res.node
def try_register(self, res):
if res.error:
self.to_reverse_count = res.advance_count
return None
return self.register(res)
def success(self, node):
self.node = node
return self
def failure(self, error):
if not self.error or self.last_registered_advance_count == 0:
self.error = error
return self
#######################################
# PARSER
#######################################
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.tok_idx = -1
self.advance()
def advance(self):
self.tok_idx += 1
self.update_current_tok()
return self.current_tok
def reverse(self, amount=1):
self.tok_idx -= amount
self.update_current_tok()
return self.current_tok
def update_current_tok(self):
if self.tok_idx >= 0 and self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
def parse(self):
res = self.statements()
if not res.error and self.current_tok.type != TT_EOF:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Token cannot appear after previous tokens"
))
return res
###################################
def statements(self):
res = ParseResult()
statements = []
pos_start = self.current_tok.pos_start.copy()
while self.current_tok.type == TT_NEWLINE:
res.register_advancement()
self.advance()
statement = res.register(self.statement())
if res.error: return res
statements.append(statement)
more_statements = True
while True:
newline_count = 0
while self.current_tok.type == TT_NEWLINE:
res.register_advancement()
self.advance()
newline_count += 1
if newline_count == 0:
more_statements = False
if not more_statements: break
statement = res.try_register(self.statement())
if not statement:
self.reverse(res.to_reverse_count)
more_statements = False
continue
statements.append(statement)
return res.success(ListNode(
statements,
pos_start,
self.current_tok.pos_end.copy()
))
def statement(self):
res = ParseResult()
pos_start = self.current_tok.pos_start.copy()
if self.current_tok.matches(TT_KEYWORD, 'RETURN'):
res.register_advancement()
self.advance()
expr = res.try_register(self.expr())
if not expr:
self.reverse(res.to_reverse_count)
return res.success(ReturnNode(expr, pos_start, self.current_tok.pos_start.copy()))
if self.current_tok.matches(TT_KEYWORD, 'CONTINUE'):
res.register_advancement()
self.advance()
return res.success(ContinueNode(pos_start, self.current_tok.pos_start.copy()))
if self.current_tok.matches(TT_KEYWORD, 'BREAK'):
res.register_advancement()
self.advance()
return res.success(BreakNode(pos_start, self.current_tok.pos_start.copy()))
expr = res.register(self.expr())
if res.error:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected 'RETURN', 'CONTINUE', 'BREAK', 'VAR', 'IF', 'FOR', 'WHILE', 'FUN', int, float, identifier, '+', '-', '(', '[' or 'NOT'"
))
return res.success(expr)
def expr(self):
res = ParseResult()
if self.current_tok.matches(TT_KEYWORD, 'VAR'):
res.register_advancement()
self.advance()
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected identifier"
))
var_name = self.current_tok
res.register_advancement()
self.advance()
if self.current_tok.type != TT_EQ:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '='"
))
res.register_advancement()
self.advance()
expr = res.register(self.expr())
if res.error: return res
return res.success(VarAssignNode(var_name, expr))
node = res.register(self.bin_op(self.comp_expr, ((TT_KEYWORD, 'AND'), (TT_KEYWORD, 'OR'))))
if res.error:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected 'VAR', 'IF', 'FOR', 'WHILE', 'FUN', int, float, identifier, '+', '-', '(', '[' or 'NOT'"
))
return res.success(node)
def comp_expr(self):
res = ParseResult()
if self.current_tok.matches(TT_KEYWORD, 'NOT'):
op_tok = self.current_tok
res.register_advancement()
self.advance()
node = res.register(self.comp_expr())
if res.error: return res
return res.success(UnaryOpNode(op_tok, node))
node = res.register(self.bin_op(self.arith_expr, (TT_EE, TT_NE, TT_LT, TT_GT, TT_LTE, TT_GTE)))
if res.error:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected int, float, identifier, '+', '-', '(', '[', 'IF', 'FOR', 'WHILE', 'FUN' or 'NOT'"
))
return res.success(node)
def arith_expr(self):
return self.bin_op(self.term, (TT_PLUS, TT_MINUS))
def term(self):
return self.bin_op(self.factor, (TT_MUL, TT_DIV))
def factor(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (TT_PLUS, TT_MINUS):
res.register_advancement()
self.advance()
factor = res.register(self.factor())
if res.error: return res
return res.success(UnaryOpNode(tok, factor))
return self.power()
def power(self):
return self.bin_op(self.call, (TT_POW, ), self.factor)
def call(self):
res = ParseResult()
atom = res.register(self.atom())
if res.error: return res
if self.current_tok.type == TT_LPAREN:
res.register_advancement()
self.advance()
arg_nodes = []
if self.current_tok.type == TT_RPAREN:
res.register_advancement()
self.advance()
else:
arg_nodes.append(res.register(self.expr()))
if res.error:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ')', 'VAR', 'IF', 'FOR', 'WHILE', 'FUN', int, float, identifier, '+', '-', '(', '[' or 'NOT'"
))
while self.current_tok.type == TT_COMMA:
res.register_advancement()
self.advance()
arg_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RPAREN:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected ',' or ')'"
))
res.register_advancement()
self.advance()
return res.success(CallNode(atom, arg_nodes))
return res.success(atom)
def atom(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (TT_INT, TT_FLOAT):
res.register_advancement()
self.advance()
return res.success(NumberNode(tok))
elif tok.type == TT_STRING:
res.register_advancement()
self.advance()
return res.success(StringNode(tok))
elif tok.type == TT_IDENTIFIER:
res.register_advancement()
self.advance()
return res.success(VarAccessNode(tok))
elif tok.type == TT_LPAREN:
res.register_advancement()
self.advance()
expr = res.register(self.expr())
if res.error: return res
if self.current_tok.type == TT_RPAREN:
res.register_advancement()
self.advance()
return res.success(expr)
else:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ')'"
))
elif tok.type == TT_LSQUARE:
list_expr = res.register(self.list_expr())
if res.error: return res
return res.success(list_expr)
elif tok.matches(TT_KEYWORD, 'IF'):
if_expr = res.register(self.if_expr())
if res.error: return res
return res.success(if_expr)
elif tok.matches(TT_KEYWORD, 'FOR'):
for_expr = res.register(self.for_expr())
if res.error: return res
return res.success(for_expr)
elif tok.matches(TT_KEYWORD, 'WHILE'):
while_expr = res.register(self.while_expr())
if res.error: return res
return res.success(while_expr)
elif tok.matches(TT_KEYWORD, 'FUN'):
func_def = res.register(self.func_def())
if res.error: return res
return res.success(func_def)
return res.failure(InvalidSyntaxError(
tok.pos_start, tok.pos_end,
"Expected int, float, identifier, '+', '-', '(', '[', IF', 'FOR', 'WHILE', 'FUN'"
))
def list_expr(self):
res = ParseResult()
element_nodes = []
pos_start = self.current_tok.pos_start.copy()
if self.current_tok.type != TT_LSQUARE:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected '['"
))
res.register_advancement()
self.advance()
if self.current_tok.type == TT_RSQUARE:
res.register_advancement()
self.advance()
else:
element_nodes.append(res.register(self.expr()))
if res.error:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ']', 'VAR', 'IF', 'FOR', 'WHILE', 'FUN', int, float, identifier, '+', '-', '(', '[' or 'NOT'"
))
while self.current_tok.type == TT_COMMA:
res.register_advancement()
self.advance()
element_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RSQUARE:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected ',' or ']'"
))
res.register_advancement()
self.advance()
return res.success(ListNode(
element_nodes,
pos_start,
self.current_tok.pos_end.copy()
))
def if_expr(self):
res = ParseResult()
all_cases = res.register(self.if_expr_cases('IF'))
if res.error: return res
cases, else_case = all_cases
return res.success(IfNode(cases, else_case))
def if_expr_b(self):
return self.if_expr_cases('ELIF')
def if_expr_c(self):
res = ParseResult()
else_case = None
if self.current_tok.matches(TT_KEYWORD, 'ELSE'):
res.register_advancement()
self.advance()
if self.current_tok.type == TT_NEWLINE:
res.register_advancement()
self.advance()
statements = res.register(self.statements())
if res.error: return res
else_case = (statements, True)
if self.current_tok.matches(TT_KEYWORD, 'END'):
res.register_advancement()
self.advance()
else:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected 'END'"
))
else:
expr = res.register(self.statement())
if res.error: return res
else_case = (expr, False)
return res.success(else_case)
def if_expr_b_or_c(self):
res = ParseResult()
cases, else_case = [], None
if self.current_tok.matches(TT_KEYWORD, 'ELIF'):
all_cases = res.register(self.if_expr_b())
if res.error: return res
cases, else_case = all_cases
else:
else_case = res.register(self.if_expr_c())
if res.error: return res
return res.success((cases, else_case))
def if_expr_cases(self, case_keyword):
res = ParseResult()
cases = []
else_case = None
if not self.current_tok.matches(TT_KEYWORD, case_keyword):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected '{case_keyword}'"
))
res.register_advancement()
self.advance()
condition = res.register(self.expr())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD, 'THEN'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'THEN'"
))
res.register_advancement()
self.advance()
if self.current_tok.type == TT_NEWLINE:
res.register_advancement()
self.advance()
statements = res.register(self.statements())
if res.error: return res
cases.append((condition, statements, True))
if self.current_tok.matches(TT_KEYWORD, 'END'):
res.register_advancement()
self.advance()
else:
all_cases = res.register(self.if_expr_b_or_c())
if res.error: return res
new_cases, else_case = all_cases
cases.extend(new_cases)
else:
expr = res.register(self.statement())
if res.error: return res
cases.append((condition, expr, False))
all_cases = res.register(self.if_expr_b_or_c())
if res.error: return res
new_cases, else_case = all_cases
cases.extend(new_cases)
return res.success((cases, else_case))
def for_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD, 'FOR'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'FOR'"
))
res.register_advancement()
self.advance()
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected identifier"
))
var_name = self.current_tok
res.register_advancement()
self.advance()
if self.current_tok.type != TT_EQ:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected '='"
))
res.register_advancement()
self.advance()
start_value = res.register(self.expr())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD, 'TO'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'TO'"
))
res.register_advancement()
self.advance()
end_value = res.register(self.expr())
if res.error: return res
if self.current_tok.matches(TT_KEYWORD, 'STEP'):
res.register_advancement()
self.advance()
step_value = res.register(self.expr())
if res.error: return res
else:
step_value = None
if not self.current_tok.matches(TT_KEYWORD, 'THEN'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'THEN'"
))
res.register_advancement()
self.advance()
if self.current_tok.type == TT_NEWLINE:
res.register_advancement()
self.advance()
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD, 'END'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'END'"
))
res.register_advancement()
self.advance()
return res.success(ForNode(var_name, start_value, end_value, step_value, body, True))
body = res.register(self.statement())
if res.error: return res
return res.success(ForNode(var_name, start_value, end_value, step_value, body, False))
def while_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD, 'WHILE'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'WHILE'"
))
res.register_advancement()
self.advance()
condition = res.register(self.expr())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD, 'THEN'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'THEN'"
))
res.register_advancement()
self.advance()
if self.current_tok.type == TT_NEWLINE:
res.register_advancement()
self.advance()
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD, 'END'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'END'"
))
res.register_advancement()
self.advance()
return res.success(WhileNode(condition, body, True))
body = res.register(self.statement())
if res.error: return res
return res.success(WhileNode(condition, body, False))
def func_def(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD, 'FUN'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'FUN'"
))
res.register_advancement()
self.advance()
if self.current_tok.type == TT_IDENTIFIER:
var_name_tok = self.current_tok
res.register_advancement()
self.advance()
if self.current_tok.type != TT_LPAREN:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected '('"
))
else:
var_name_tok = None
if self.current_tok.type != TT_LPAREN:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected identifier or '('"
))
res.register_advancement()
self.advance()
arg_name_toks = []
if self.current_tok.type == TT_IDENTIFIER:
arg_name_toks.append(self.current_tok)
res.register_advancement()
self.advance()
while self.current_tok.type == TT_COMMA:
res.register_advancement()
self.advance()
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected identifier"
))
arg_name_toks.append(self.current_tok)
res.register_advancement()
self.advance()
if self.current_tok.type != TT_RPAREN:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected ',' or ')'"
))
else:
if self.current_tok.type != TT_RPAREN:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected identifier or ')'"
))
res.register_advancement()
self.advance()
if self.current_tok.type == TT_ARROW:
res.register_advancement()
self.advance()
body = res.register(self.expr())
if res.error: return res
return res.success(FuncDefNode(
var_name_tok,
arg_name_toks,
body,
True
))
if self.current_tok.type != TT_NEWLINE:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected '->' or NEWLINE"
))
res.register_advancement()
self.advance()
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD, 'END'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected 'END'"
))
res.register_advancement()
self.advance()
return res.success(FuncDefNode(
var_name_tok,
arg_name_toks,
body,
False
))
###################################
def bin_op(self, func_a, ops, func_b=None):
if func_b == None:
func_b = func_a
res = ParseResult()
left = res.register(func_a())
if res.error: return res
while self.current_tok.type in ops or (self.current_tok.type, self.current_tok.value) in ops:
op_tok = self.current_tok
res.register_advancement()
self.advance()
right = res.register(func_b())
if res.error: return res
left = BinOpNode(left, op_tok, right)
return res.success(left)
#######################################
# RUNTIME RESULT
#######################################
class RTResult:
def __init__(self):
self.reset()
def reset(self):
self.value = None
self.error = None
self.func_return_value = None
self.loop_should_continue = False
self.loop_should_break = False
def register(self, res):
self.error = res.error
self.func_return_value = res.func_return_value
self.loop_should_continue = res.loop_should_continue
self.loop_should_break = res.loop_should_break
return res.value
def success(self, value):
self.reset()
self.value = value
return self
def success_return(self, value):
self.reset()
self.func_return_value = value
return self
def success_continue(self):
self.reset()
self.loop_should_continue = True
return self
def success_break(self):
self.reset()
self.loop_should_break = True
return self
def failure(self, error):
self.reset()
self.error = error
return self
def should_return(self):
# Note: this will allow you to continue and break outside the current function
return (
self.error or
self.func_return_value or
self.loop_should_continue or
self.loop_should_break
)
#######################################
# VALUES
#######################################
class Value:
def __init__(self):
self.set_pos()
self.set_context()
def set_pos(self, pos_start=None, pos_end=None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def set_context(self, context=None):
self.context = context
return self
def added_to(self, other):
return None, self.illegal_operation(other)
def subbed_by(self, other):
return None, self.illegal_operation(other)
def multed_by(self, other):
return None, self.illegal_operation(other)
def dived_by(self, other):
return None, self.illegal_operation(other)
def powed_by(self, other):
return None, self.illegal_operation(other)
def get_comparison_eq(self, other):
return None, self.illegal_operation(other)
def get_comparison_ne(self, other):
return None, self.illegal_operation(other)
def get_comparison_lt(self, other):
return None, self.illegal_operation(other)
def get_comparison_gt(self, other):
return None, self.illegal_operation(other)
def get_comparison_lte(self, other):
return None, self.illegal_operation(other)
def get_comparison_gte(self, other):
return None, self.illegal_operation(other)
def anded_by(self, other):
return None, self.illegal_operation(other)
def ored_by(self, other):
return None, self.illegal_operation(other)
def notted(self, other):
return None, self.illegal_operation(other)
def execute(self, args):
return RTResult().failure(self.illegal_operation())
def copy(self):
raise Exception('No copy method defined')
def is_true(self):
return False
def illegal_operation(self, other=None):
if not other: other = self
return RTError(
self.pos_start, other.pos_end,
'Illegal operation',
self.context
)
class Number(Value):
def __init__(self, value):
super().__init__()
self.value = value
def added_to(self, other):
if isinstance(other, Number):
return Number(self.value + other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def subbed_by(self, other):
if isinstance(other, Number):
return Number(self.value - other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def multed_by(self, other):
if isinstance(other, Number):
return Number(self.value * other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def dived_by(self, other):
if isinstance(other, Number):
if other.value == 0:
return None, RTError(
other.pos_start, other.pos_end,
'Division by zero',
self.context
)
return Number(self.value / other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def powed_by(self, other):
if isinstance(other, Number):
return Number(self.value ** other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_eq(self, other):
if isinstance(other, Number):
return Number(int(self.value == other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_ne(self, other):
if isinstance(other, Number):
return Number(int(self.value != other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lt(self, other):
if isinstance(other, Number):
return Number(int(self.value < other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gt(self, other):
if isinstance(other, Number):
return Number(int(self.value > other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lte(self, other):
if isinstance(other, Number):
return Number(int(self.value <= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gte(self, other):
if isinstance(other, Number):
return Number(int(self.value >= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def anded_by(self, other):
if isinstance(other, Number):
return Number(int(self.value and other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def ored_by(self, other):
if isinstance(other, Number):
return Number(int(self.value or other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def notted(self):
return Number(1 if self.value == 0 else 0).set_context(self.context), None
def copy(self):
copy = Number(self.value)
copy.set_pos(self.pos_start, self.pos_end)
copy.set_context(self.context)
return copy
def is_true(self):
return self.value != 0
def __str__(self):
return str(self.value)
def __repr__(self):
return str(self.value)
Number.null = Number(0)
Number.false = Number(0)
Number.true = Number(1)
Number.math_PI = Number(math.pi)
class String(Value):
def __init__(self, value):
super().__init__()
self.value = value
def added_to(self, other):
if isinstance(other, String):
return String(self.value + other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def multed_by(self, other):
if isinstance(other, Number):
return String(self.value * other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def is_true(self):
return len(self.value) > 0
def copy(self):
copy = String(self.value)
copy.set_pos(self.pos_start, self.pos_end)
copy.set_context(self.context)
return copy
def __str__(self):
return self.value
def __repr__(self):
return f'"{self.value}"'
class List(Value):
def __init__(self, elements):
super().__init__()
self.elements = elements
def added_to(self, other):
new_list = self.copy()
new_list.elements.append(other)
return new_list, None
def subbed_by(self, other):
if isinstance(other, Number):
new_list = self.copy()
try:
new_list.elements.pop(other.value)
return new_list, None
except:
return None, RTError(
other.pos_start, other.pos_end,
'Element at this index could not be removed from list because index is out of bounds',
self.context
)
else:
return None, Value.illegal_operation(self, other)
def multed_by(self, other):
if isinstance(other, List):
new_list = self.copy()
new_list.elements.extend(other.elements)
return new_list, None
else:
return None, Value.illegal_operation(self, other)
def dived_by(self, other):
if isinstance(other, Number):
try:
return self.elements[other.value], None
except:
return None, RTError(
other.pos_start, other.pos_end,
'Element at this index could not be retrieved from list because index is out of bounds',
self.context
)
else:
return None, Value.illegal_operation(self, other)
def copy(self):
copy = List(self.elements)
copy.set_pos(self.pos_start, self.pos_end)
copy.set_context(self.context)
return copy
def __str__(self):
return ", ".join([str(x) for x in self.elements])
def __repr__(self):
return f'[{", ".join([repr(x) for x in self.elements])}]'
class BaseFunction(Value):
def __init__(self, name):
super().__init__()
self.name = name or "<anonymous>"
def generate_new_context(self):
new_context = Context(self.name, self.context, self.pos_start)
new_context.symbol_table = SymbolTable(new_context.parent.symbol_table)
return new_context
def check_args(self, arg_names, args):
res = RTResult()
if len(args) > len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(args) - len(arg_names)} too many args passed into {self}",
self.context
))
if len(args) < len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(arg_names) - len(args)} too few args passed into {self}",
self.context
))
return res.success(None)
def populate_args(self, arg_names, args, exec_ctx):
for i in range(len(args)):
arg_name = arg_names[i]
arg_value = args[i]
arg_value.set_context(exec_ctx)
exec_ctx.symbol_table.set(arg_name, arg_value)
def check_and_populate_args(self, arg_names, args, exec_ctx):
res = RTResult()
res.register(self.check_args(arg_names, args))
if res.should_return(): return res
self.populate_args(arg_names, args, exec_ctx)
return res.success(None)
class Function(BaseFunction):
def __init__(self, name, body_node, arg_names, should_auto_return):
super().__init__(name)
self.body_node = body_node
self.arg_names = arg_names
self.should_auto_return = should_auto_return
def execute(self, args):
res = RTResult()
interpreter = Interpreter()
exec_ctx = self.generate_new_context()
res.register(self.check_and_populate_args(self.arg_names, args, exec_ctx))
if res.should_return(): return res
value = res.register(interpreter.visit(self.body_node, exec_ctx))
if res.should_return() and res.func_return_value == None: return res
ret_value = (value if self.should_auto_return else None) or res.func_return_value or Number.null
return res.success(ret_value)
def copy(self):
copy = Function(self.name, self.body_node, self.arg_names, self.should_auto_return)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def __repr__(self):
return f"<function {self.name}>"
class BuiltInFunction(BaseFunction):
def __init__(self, name):
super().__init__(name)
def execute(self, args):
res = RTResult()
exec_ctx = self.generate_new_context()
method_name = f'execute_{self.name}'
method = getattr(self, method_name, self.no_visit_method)
res.register(self.check_and_populate_args(method.arg_names, args, exec_ctx))
if res.should_return(): return res
return_value = res.register(method(exec_ctx))
if res.should_return(): return res
return res.success(return_value)
def no_visit_method(self, node, context):
raise Exception(f'No execute_{self.name} method defined')
def copy(self):
copy = BuiltInFunction(self.name)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def __repr__(self):
return f"<built-in function {self.name}>"
#####################################
def execute_print(self, exec_ctx):
print(str(exec_ctx.symbol_table.get('value')))
return RTResult().success(Number.null)
execute_print.arg_names = ['value']
def execute_print_ret(self, exec_ctx):
return RTResult().success(String(str(exec_ctx.symbol_table.get('value'))))
execute_print_ret.arg_names = ['value']
def execute_input(self, exec_ctx):
text = input()
return RTResult().success(String(text))
execute_input.arg_names = []
def execute_input_int(self, exec_ctx):
while True:
text = input()
try:
number = int(text)
break
except ValueError:
print(f"'{text}' must be an integer. Try again!")
return RTResult().success(Number(number))
execute_input_int.arg_names = []
def execute_clear(self, exec_ctx):
os.system('cls' if os.name == 'nt' else 'cls')
return RTResult().success(Number.null)
execute_clear.arg_names = []
def execute_is_number(self, exec_ctx):
is_number = isinstance(exec_ctx.symbol_table.get("value"), Number)
return RTResult().success(Number.true if is_number else Number.false)
execute_is_number.arg_names = ["value"]
def execute_is_string(self, exec_ctx):
is_number = isinstance(exec_ctx.symbol_table.get("value"), String)
return RTResult().success(Number.true if is_number else Number.false)
execute_is_string.arg_names = ["value"]
def execute_is_list(self, exec_ctx):
is_number = isinstance(exec_ctx.symbol_table.get("value"), List)
return RTResult().success(Number.true if is_number else Number.false)
execute_is_list.arg_names = ["value"]
def execute_is_function(self, exec_ctx):
is_number = isinstance(exec_ctx.symbol_table.get("value"), BaseFunction)
return RTResult().success(Number.true if is_number else Number.false)
execute_is_function.arg_names = ["value"]
def execute_append(self, exec_ctx):
list_ = exec_ctx.symbol_table.get("list")
value = exec_ctx.symbol_table.get("value")
if not isinstance(list_, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"First argument must be list",
exec_ctx
))
list_.elements.append(value)
return RTResult().success(Number.null)
execute_append.arg_names = ["list", "value"]
def execute_pop(self, exec_ctx):
list_ = exec_ctx.symbol_table.get("list")
index = exec_ctx.symbol_table.get("index")
if not isinstance(list_, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"First argument must be list",
exec_ctx
))
if not isinstance(index, Number):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Second argument must be number",
exec_ctx
))
try:
element = list_.elements.pop(index.value)
except:
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
'Element at this index could not be removed from list because index is out of bounds',
exec_ctx
))
return RTResult().success(element)
execute_pop.arg_names = ["list", "index"]
def execute_extend(self, exec_ctx):
listA = exec_ctx.symbol_table.get("listA")
listB = exec_ctx.symbol_table.get("listB")
if not isinstance(listA, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"First argument must be list",
exec_ctx
))
if not isinstance(listB, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Second argument must be list",
exec_ctx
))
listA.elements.extend(listB.elements)
return RTResult().success(Number.null)
execute_extend.arg_names = ["listA", "listB"]
def execute_len(self, exec_ctx):
list_ = exec_ctx.symbol_table.get("list")
if not isinstance(list_, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Argument must be list",
exec_ctx
))
return RTResult().success(Number(len(list_.elements)))
execute_len.arg_names = ["list"]
def execute_run(self, exec_ctx):
fn = exec_ctx.symbol_table.get("fn")
if not isinstance(fn, String):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Second argument must be string",
exec_ctx
))
fn = fn.value
try:
with open(fn, "r") as f:
script = f.read()
except Exception as e:
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
f"Failed to load script \"{fn}\"\n" + str(e),
exec_ctx
))
_, error = run(fn, script)
if error:
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
f"Failed to finish executing script \"{fn}\"\n" +
error.as_string(),
exec_ctx
))
return RTResult().success(Number.null)
execute_run.arg_names = ["fn"]
BuiltInFunction.print = BuiltInFunction("print")
BuiltInFunction.print_ret = BuiltInFunction("print_ret")
BuiltInFunction.input = BuiltInFunction("input")
BuiltInFunction.input_int = BuiltInFunction("input_int")
BuiltInFunction.clear = BuiltInFunction("clear")
BuiltInFunction.is_number = BuiltInFunction("is_number")
BuiltInFunction.is_string = BuiltInFunction("is_string")
BuiltInFunction.is_list = BuiltInFunction("is_list")
BuiltInFunction.is_function = BuiltInFunction("is_function")
BuiltInFunction.append = BuiltInFunction("append")
BuiltInFunction.pop = BuiltInFunction("pop")
BuiltInFunction.extend = BuiltInFunction("extend")
BuiltInFunction.len = BuiltInFunction("len")
BuiltInFunction.run = BuiltInFunction("run")
#######################################
# CONTEXT
#######################################
class Context:
def __init__(self, display_name, parent=None, parent_entry_pos=None):
self.display_name = display_name
self.parent = parent
self.parent_entry_pos = parent_entry_pos
self.symbol_table = None
#######################################
# SYMBOL TABLE
#######################################
class SymbolTable:
def __init__(self, parent=None):
self.symbols = {}
self.parent = parent
def get(self, name):
value = self.symbols.get(name, None)
if value == None and self.parent:
return self.parent.get(name)
return value
def set(self, name, value):
self.symbols[name] = value
def remove(self, name):
del self.symbols[name]
#######################################
# INTERPRETER
#######################################
class Interpreter:
def visit(self, node, context):
method_name = f'visit_{type(node).__name__}'
method = getattr(self, method_name, self.no_visit_method)
return method(node, context)
def no_visit_method(self, node, context):
raise Exception(f'No visit_{type(node).__name__} method defined')
###################################
def visit_NumberNode(self, node, context):
return RTResult().success(
Number(node.tok.value).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_StringNode(self, node, context):
return RTResult().success(
String(node.tok.value).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_ListNode(self, node, context):
res = RTResult()
elements = []
for element_node in node.element_nodes:
elements.append(res.register(self.visit(element_node, context)))
if res.should_return(): return res
return res.success(
List(elements).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_VarAccessNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = context.symbol_table.get(var_name)
if not value:
return res.failure(RTError(
node.pos_start, node.pos_end,
f"'{var_name}' is not defined",
context
))
value = value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(value)
def visit_VarAssignNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = res.register(self.visit(node.value_node, context))
if res.should_return(): return res
context.symbol_table.set(var_name, value)
return res.success(value)
def visit_BinOpNode(self, node, context):
res = RTResult()
left = res.register(self.visit(node.left_node, context))
if res.should_return(): return res
right = res.register(self.visit(node.right_node, context))
if res.should_return(): return res
if node.op_tok.type == TT_PLUS:
result, error = left.added_to(right)
elif node.op_tok.type == TT_MINUS:
result, error = left.subbed_by(right)
elif node.op_tok.type == TT_MUL:
result, error = left.multed_by(right)
elif node.op_tok.type == TT_DIV:
result, error = left.dived_by(right)
elif node.op_tok.type == TT_POW:
result, error = left.powed_by(right)
elif node.op_tok.type == TT_EE:
result, error = left.get_comparison_eq(right)
elif node.op_tok.type == TT_NE:
result, error = left.get_comparison_ne(right)
elif node.op_tok.type == TT_LT:
result, error = left.get_comparison_lt(right)
elif node.op_tok.type == TT_GT:
result, error = left.get_comparison_gt(right)
elif node.op_tok.type == TT_LTE:
result, error = left.get_comparison_lte(right)
elif node.op_tok.type == TT_GTE:
result, error = left.get_comparison_gte(right)
elif node.op_tok.matches(TT_KEYWORD, 'AND'):
result, error = left.anded_by(right)
elif node.op_tok.matches(TT_KEYWORD, 'OR'):
result, error = left.ored_by(right)
if error:
return res.failure(error)
else:
return res.success(result.set_pos(node.pos_start, node.pos_end))
def visit_UnaryOpNode(self, node, context):
res = RTResult()
number = res.register(self.visit(node.node, context))
if res.should_return(): return res
error = None
if node.op_tok.type == TT_MINUS:
number, error = number.multed_by(Number(-1))
elif node.op_tok.matches(TT_KEYWORD, 'NOT'):
number, error = number.notted()
if error:
return res.failure(error)
else:
return res.success(number.set_pos(node.pos_start, node.pos_end))
def visit_IfNode(self, node, context):
res = RTResult()
for condition, expr, should_return_null in node.cases:
condition_value = res.register(self.visit(condition, context))
if res.should_return(): return res
if condition_value.is_true():
expr_value = res.register(self.visit(expr, context))
if res.should_return(): return res
return res.success(Number.null if should_return_null else expr_value)
if node.else_case:
expr, should_return_null = node.else_case
expr_value = res.register(self.visit(expr, context))
if res.should_return(): return res
return res.success(Number.null if should_return_null else expr_value)
return res.success(Number.null)
def visit_ForNode(self, node, context):
res = RTResult()
elements = []
start_value = res.register(self.visit(node.start_value_node, context))
if res.should_return(): return res
end_value = res.register(self.visit(node.end_value_node, context))
if res.should_return(): return res
if node.step_value_node:
step_value = res.register(self.visit(node.step_value_node, context))
if res.should_return(): return res
else:
step_value = Number(1)
i = start_value.value
if step_value.value >= 0:
condition = lambda: i < end_value.value
else:
condition = lambda: i > end_value.value
while condition():
context.symbol_table.set(node.var_name_tok.value, Number(i))
i += step_value.value
value = res.register(self.visit(node.body_node, context))
if res.should_return() and res.loop_should_continue == False and res.loop_should_break == False: return res
if res.loop_should_continue:
continue
if res.loop_should_break:
break
elements.append(value)
return res.success(
Number.null if node.should_return_null else
List(elements).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_WhileNode(self, node, context):
res = RTResult()
elements = []
while True:
condition = res.register(self.visit(node.condition_node, context))
if res.should_return(): return res
if not condition.is_true():
break
value = res.register(self.visit(node.body_node, context))
if res.should_return() and res.loop_should_continue == False and res.loop_should_break == False: return res
if res.loop_should_continue:
continue
if res.loop_should_break:
break
elements.append(value)
return res.success(
Number.null if node.should_return_null else
List(elements).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_FuncDefNode(self, node, context):
res = RTResult()
func_name = node.var_name_tok.value if node.var_name_tok else None
body_node = node.body_node
arg_names = [arg_name.value for arg_name in node.arg_name_toks]
func_value = Function(func_name, body_node, arg_names, node.should_auto_return).set_context(context).set_pos(node.pos_start, node.pos_end)
if node.var_name_tok:
context.symbol_table.set(func_name, func_value)
return res.success(func_value)
def visit_CallNode(self, node, context):
res = RTResult()
args = []
value_to_call = res.register(self.visit(node.node_to_call, context))
if res.should_return(): return res
value_to_call = value_to_call.copy().set_pos(node.pos_start, node.pos_end)
for arg_node in node.arg_nodes:
args.append(res.register(self.visit(arg_node, context)))
if res.should_return(): return res
return_value = res.register(value_to_call.execute(args))
if res.should_return(): return res
return_value = return_value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(return_value)
def visit_ReturnNode(self, node, context):
res = RTResult()
if node.node_to_return:
value = res.register(self.visit(node.node_to_return, context))
if res.should_return(): return res
else:
value = Number.null
return res.success_return(value)
def visit_ContinueNode(self, node, context):
return RTResult().success_continue()
def visit_BreakNode(self, node, context):
return RTResult().success_break()
#######################################
# RUN
#######################################
global_symbol_table = SymbolTable()
global_symbol_table.set("NULL", Number.null)
global_symbol_table.set("FALSE", Number.false)
global_symbol_table.set("TRUE", Number.true)
global_symbol_table.set("MATH_PI", Number.math_PI)
global_symbol_table.set("PRINT", BuiltInFunction.print)
global_symbol_table.set("PRINT_RET", BuiltInFunction.print_ret)
global_symbol_table.set("INPUT", BuiltInFunction.input)
global_symbol_table.set("INPUT_INT", BuiltInFunction.input_int)
global_symbol_table.set("CLEAR", BuiltInFunction.clear)
global_symbol_table.set("CLS", BuiltInFunction.clear)
global_symbol_table.set("IS_NUM", BuiltInFunction.is_number)
global_symbol_table.set("IS_STR", BuiltInFunction.is_string)
global_symbol_table.set("IS_LIST", BuiltInFunction.is_list)
global_symbol_table.set("IS_FUN", BuiltInFunction.is_function)
global_symbol_table.set("APPEND", BuiltInFunction.append)
global_symbol_table.set("POP", BuiltInFunction.pop)
global_symbol_table.set("EXTEND", BuiltInFunction.extend)
global_symbol_table.set("LEN", BuiltInFunction.len)
global_symbol_table.set("RUN", BuiltInFunction.run)
def run(fn, text):
# Generate tokens
lexer = Lexer(fn, text)
tokens, error = lexer.make_tokens()
if error: return None, error
# Generate AST
parser = Parser(tokens)
ast = parser.parse()
if ast.error: return None, ast.error
# Run program
interpreter = Interpreter()
context = Context('<program>')
context.symbol_table = global_symbol_table
result = interpreter.visit(ast.node, context)
return result.value, result.error | AggiNScript | /AggiNScript-0.3-py3-none-any.whl/aggin/aggin.py | aggin.py |
[](https://travis-ci.org/MSeal/agglom_cluster)
# hac
Agglomerative clustering tool for network-x graphs
## Clustering
Implements the algorithm described by:
"Fast algorithm for detecting community structure in networks"
M. E. J. Newman. 2004
http://arxiv.org/pdf/cond-mat/0309508v1.pdf
The algorithm efficiently clusters large number of nodes and is one of the best scaling clustering algorithms available. It relies on building and slicing a dendrogram of potential clusters from the base of a networkx graph. Each possible pairing of elements is evaluated and clustering in quality (see paper reference) increasing order. The greedy aspect of this approach is in the avoidance of backtracking. Each pass on the dengrogram assume prior passes were the global minimum for overall quality. Given decent edge associations, this is a relatively safe assumption to make and vastly increases the speed of the algorithm.
See papers on scaling and accuracy questions regarding greedy Newman.
This implementation uses a heap to select the best pair to cluster at each iteration
- A naive implementation considers all "n" edges in the graph (O(n))
- A heap reduces this search dramatically (O(log(n))
## Installation
pip install agglomcluster
## Dependencies
networkx -- supported graphing library
## Examples
import networkx as nx
from hac import GreedyAgglomerativeClusterer
clusterer = GreedyAgglomerativeClusterer()
# This cluster call is where most of the heavy lifting happens
karate_dendrogram = clusterer.cluster(nx.karate_club_graph())
karate_dendrogram.clusters(1)
# => [set(range(34))]
karate_dendrogram.clusters(2)
# => [set([0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 16, 17, 19, 21]),
set([32, 33, 8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])]
karate_dendrogram.clusters(3)
# => [set([32, 33, 8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]),
set([1, 2, 3, 7, 9, 12, 13, 17, 21]),
set([0, 4, 5, 6, 10, 11, 16, 19])]
# We can ask the dendrogram to pick the optimal number of clusters
karate_dendrogram.clusters()
# => [set([32, 33, 8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]),
set([1, 2, 3, 7, 9, 12, 13, 17, 21]),
set([0, 4, 5, 6, 10, 11, 16, 19])]
karate_dendrogram.labels()
# => { 0: 2, 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2, 7: 1, 8: 0, 9: 1, 10: 2, 11: 2,
12: 1, 13: 1, 14: 0, 15: 0, 16: 2, 17: 1, 18: 0, 19: 2, 20: 0, 21: 1, 22: 0,
23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 0, 33: 0 }
# We can also force certain nodes to always be clustered together
forced_clusters = [set([33,0]), set([32,1])]
forced_karate_dendrogram = clusterer.cluster(nx.karate_club_graph(), forced_clusters=forced_clusters)
forced_karate_dendrogram.clusters()
# => [set([0, 33, 9, 11, 12, 14, 15, 17, 18, 19, 21, 26, 29]),
set([32, 1, 2, 3, 7, 8, 13, 20, 22, 30]),
set([23, 24, 25, 27, 28, 31]),
set([16, 10, 4, 5, 6])]
## Issues
* The actual Modularity score does not exactly match the Modularity score of the example on the wikipedia page (extensive use and investigation indicates it's not affecting the quality of results, just makes it difficult to match referenced paper's exact results)
- http://en.wikipedia.org/wiki/Modularity_(networks)
* Does not handle disconnected components (unless they are components of size 1)
* Node relabeling is messy (adds hashable nodes dependency)
* Dendrogram crawling is used for two separate purposes which aren't clearly defined/called
## Limitations:
* Nodes inside clustered graph must be hashable elements
* Does not work for directed graphs (TODO operate on the undirected graph)
* Does not work for negative graphs (TODO add this capability)
## TODO
* Move issues to github issues and out of README
* Consider using a scikit sparse matrix for the dengrogram generation as an optimization
* Convert clustering process into a multi-thread/process capable version
* Consider interface/capabilty parity with scikit AgglomerativeCluster
* Add evaluation function options to clusterer other than originally defined quality
* A few methods could use documentation
## Classes
### GreedyAgglomerativeClusterer
Used to generate Dendrogram objects that represent a clustered graph. Use `.cluster()` to process a graph.
### Dendrogram
The clustered result from an agglomerative clustering pass. Use `.clusters()` and `.labels()` to get the desired cluster results. Additionally you this class has some built-in graphing methods `.plot()` and `.plot_quality_history()`.
## Performance
Approximate performance runs on natural graph sizes on high-end machine:
Nodes | Edges | Time | Memory
1000 | 6000 | 1.5 s | 28 MB
10000 | 80000 | 350 s | 2.5 GB
TODO More sizes
## Author
Author(s): Matthew Seal
Past Author/Contributors(s): Ethan Lozano, Zubin Jelveh
| AgglomCluster | /AgglomCluster-2.0.7.tar.gz/AgglomCluster-2.0.7/README.md | README.md |
=================
Aggregator README
=================
This package contains a class for aggregation of high resolution data on coarse grids.
Installation:
-------------
After downloading the source from github_ install via pip, descending
into the top-level of the source tree
and launching::
pip3 install .
or to install in developers mode::
pip3 install -e .
Or install the latest releaase from PyPI::
pip install Aggregator
.. _github: https://github.com/mommebutenschoen/Aggregator
Documentation:
--------------
Documentation to this package can be found on readthedocs_.
.. _readthedocs: https://Aggregator.readthedocs.io/
| Aggregator | /Aggregator-20.5.tar.gz/Aggregator-20.5/README.rst | README.rst |

This is a repository for Aggrescan3D standalone application.
## Detailed instructions and tutorials are provided on [Aggrescan3D WIKI PAGE](https://bitbucket.org/lcbio/aggrescan3d/wiki/Home) ##
-------------------------------------------
### Table of contents
[1. Introduction](#markdown-header-introduction)
[2. Windows installation guide](#markdown-header-windows-users)
[3. Linux installation guide](#markdown-header-linux-users)
[4. macOS installation guide](#markdown-header-macos-users)
[5. Docker image](#markdown-header-docker-image)
---
## Introduction
*Aggrescan3D* can be installed on Linux, macOS or Windows. This comprehensive tutorial is aimed to guide users through the installation process and is split into three parts for corresponding systems.
*Aggrescan3D* is a python package using *Python 2.7* version. We *highly* recommend that you use the scientific Anaconda distribution that comes with pre-installed packages
and conda package manager which allows for an easier and less error prone installation. If you choose to use Anaconda simply go to [their web page](https://www.anaconda.com/download/)
and download a Python 2.7 installation for your target operating system (the installer will suggest installing only for current user for Windows systems we also advise that as managing an all-user install can be more challenging
and this guide assumes that the user chooses the recommended option). Further steps will give specific instructions for conda users as well as for vanilla python.
##### Tips for users who are not familiar with Python or using command prompt/terminal:
- *Python3.X* is **NOT** the latest version of *Python2.7* and you should always use *Python2.7* to run Aggrescan3D.
- Throughout this tutorial a PATH will be frequently mentioned. PATH is a variable that tells the system where to look for your installed programs when you issue commands. Detailed instructions on how to modify it will be given in appropriate parts of this guide.
- Most sections of this guide contain a correctness test step which can be executed to see wether or not the isntallation was successful. When in doubt run the test.
- While this tutorial attempts to covers much ground as possible if something goes wrong please contact us for assistance this will also help us improve our software and this guide too!
---
## Windows users
#### 1. Python 2.7
##### Anaconda distribution
If you have chosen to use Anaconda this step is already done.
* Please do note that at this point you should always use the Anaconda Prompt available in the start menu under that name instead of the regular command prompt.
##### Vanilla Python distribution
- Follow instructions on [python.org](https://python.org). During the installation process select to include pip and setuptools as those will be necessary.
- Add Python27/Scripts (by default under C:\Python27\Scripts) folder to your PATH. This folder contains pip which will install Aggrescan3D as well as it is the folder which will contain the Aggrescan3D program once its installed.
Follow the steps described in GFortran section. The folder should be located at ```C:\Python27\Scripts``` by default so either follow the steps in the Control Panel or type:
```
set PATH=%PATH%;C:\Python27\Scripts
```
- Note that you have to re-type that in each command prompt in which you want to use *pip* or *Aggrescan3D*.
##### pip not installed with Python
If you chose not to install pip with your Python installation you need to do that manually.
Assuming you've already made Python2.7 accessible under command "python", download [this](https://bootstrap.pypa.io/get-pip.py) script,
change to the directory with downloaded script and run:
```python get-pip.py```
##### Correctness test
To check if pip (hence also Python) are working open a `command
prompt` (press `cmd + R`; enter "cmd"; hit `enter`) and run the following command:
```pip freeze```
This should list all the packages that you have currently installed.
If you wish to check that you have the correct Python version add the Python binary (python.exe) replacing the example path with your respective one:
```set PATH=%PATH%;C:\Python27```
And then type:
```python --version```
Minimum recommended python version for Aggrescan3D is 2.7.12 but as low as 2.7.6 should work. We recommend that you download the latest version from
[python.org](https://python.org).
#### 2. FoldX (optional)
In order to run stability calculations or mutant calculations FoldX has to be present on the system and PATH to it provided to the program upon running a calculation.
FoldX is free for academic use and the licence can be obtained at http://foldxsuite.crg.eu/
#### 3. *CABS-flex* (optional)
In order to run the dynamic mode (*highly recommneded*) one has to install *CABS-flex*. Detailed instructions how to do so can be found [here](https://bitbucket.org/lcbio/cabsflex/src/master/README.md)
#### 4. *Aggrescan3D*
##### Anaconda users
In your Anaconda Prompt type:
```conda install -c lcbio aggrescan3d```
##### Vanilla Python
In the regular command prompt type:
```pip install aggrescan3d```
##### Correctness test
Run a simulation of lcbio's favorite 2gb1 with:
```aggrescan -i 2gb1 -w test_run -v 4```
- If the result is `'aggrescan3d' is not recognized as an internal or external command, operable program or batch file.` it means that your Python's Scripts folder is not on the PATH variable.
- If you see a ```Simulation completed successfully``` message, congratulations you have completed your first *aggrescan3d* simulation.
To check if the server app works:
```a3d_server```
- Open your favourite web browser (Be warned though - Internet Explorer will not be able to provide full functionality)
- Go to localhost:5000
- ** Some of the app functionality might not work on the Windows system (namely job stopping) and the app is generally less responsive and more prone to hang should work well in most cases though **
---
## Linux users ##
#### 1. Python 2.7
##### Anaconda distribution
If you have chosen to use Anaconda this step is already done. Anaconda installer should ask you if you want it to be added to your PATH,
for most users this is desirable because it means that when typing ```python``` it will call Anaconda's Python rather than regular one.
* Check if the ```python``` command refers to Anaconda Python type:
```python --version```
The output should be something like ```Python 2.7.14 :: Anaconda, Inc. ```. If it is not add a following line to your ~/.bashrc file (found in the user's home directory)
replacing the path with your anaconda's installation path:
```export $PATH="/absolute/path/to/anaconda2/bin:$PATH"```
and then close and reopen the terminal or simply run:
```source ~/.bashrc```
##### Vanilla Python distribution
Python 2.7 should be present on all unix systems, to verify the version, open your terminal and type:
```python --version```
We recommended python version for 2.7.12 or higher but earlier releases might also work.
##### pip not installed with Python
pip should also be installed by default on most unix systems, verify that it works issuing the following command:
```pip freeze```
This should return a list of installed packages for your Python.
if that is not the case install it using your system's package manager:
```sudo apt-get install python-pip```
#### 2. FoldX (optional)
In order to run stability calculations or mutant calculations FoldX has to be present on the system and PATH to it provided to the program upon running a calculation.
FoldX is free for academic use and the licence can be obtained at http://foldxsuite.crg.eu/
#### 3. *CABS-flex* (optional)
In order to run the dynamic mode (*highly recommneded*) one has to install *CABS-flex*. Detailed instructions how to do so can be found [here](https://bitbucket.org/lcbio/cabsflex/src/master/README.md)
#### 4. *Aggrescan3D*
##### Anaconda users
Simply type:
```conda install -c lcbio aggrescan3d```
##### Vanilla Python
Simply type:
```pip install aggrescan3d```
##### **Troubleshooting**
- If pip install fails due to writing rights **do not use sudo pip install.**
- Depending on your privileges and the way your system is managed you might want or need to install *Aggrescan3D* just for the current user:
```pip install --user aggrescan3d```
- When using the --user flag the binary is placed in a folder that is usually not on your PATH. Usually it is located in your
```$HOME/.local/bin``` but check if that is the case before continuing. Once you located the binary add its location to your path via editing your .bashrc folder in home directory. Add the line:
```export PATH="$HOME/.local/bin:$PATH"```
##### Correctness test
Run a simulation of lcbio's favorite 2gb1 with:
```aggrescan -i 2gb1 -w test_run -v 4```
- If the result is `'aggrescan3d' is not recognized as an internal or external command, operable program or batch file.` it means that your Python's Scripts folder is not on the PATH variable.
- If you see a ```Simulation completed successfully``` message, congratulations you have completed your first *aggrescan3d* simulation.
To check if the server app works:
```a3d_server```
- Open your favourite web browser
- Go to 0.0.0.0:5000 (if the server is not responding depending on the loopback settings localhost:5000 might work)
---
## macOS users
#### 1. Python 2.7
##### Anaconda distribution
If you have chosen to use Anaconda this step is already done. Anaconda installer should ask you if you want it to be added to your PATH,
for most users this is desirable because it means that when typing ```python``` it will call Anaconda's Python rather than regular one.
* Check if the ```python``` command refers to Anaconda Python type:
```python --version```
If the result doesnt include the word Anaconda it means your system is using other Python version by default this can be changed by prepending Anaconda to your PATH.
- Move into home directory
- Create a .bash_profile file using a text editor (like nano) ```nano .bash_profile```
- Add the line ```export PATH="/absolute/path/to/anaconda2/bin:$PATH"``` with your respective path to anaconda2 installation
- Save the file and relaunch the terminal
##### Vanilla Python distribution
macOS comes with *Python2.7* already installed. To check if you have the correct Python version open the `Terminal.app` and type:
```python --version```
If you get the message: `bash: python: command not found` it may mean that your system doesn't have Python installed, or
Python's binary is not in the system `PATH`. To check this run in the `Terminal.app` the following command:
```/Library/Frameworks/Python.framework/Versions/2.7/bin/python --version```
If you still get the message: `bash: python: command not found` you need to install *Python2.7*. Otherwise add Python's
binary to the system's `PATH` by running in the `Terminal.app` the following command and then reopen the terminal:
```echo "export PATH=/Library/Frameworks/Python.framework/Versions/2.7/bin/:$PATH" >> ~/.bash_profile```
##### pip not installed with Python
Assuming you've already installed Python2.7 and made it accessible under command "python" simply install pip via setuptools by:
```sudo easy_install pip```
#### 2. FoldX (optional)
In order to run stability calculations or mutant calculations FoldX has to be present on the system and PATH to it provided to the program upon running a calculation.
FoldX is free for academic use and the licence can be obtained at http://foldxsuite.crg.eu/
#### 3. *CABS-flex* (optional)
In order to run the dynamic mode (*highly recommneded*) one has to install *CABS-flex*. Detailed instructions how to do so can be found [here](https://bitbucket.org/lcbio/cabsflex/src/master/README.md)
#### 4. *Aggrescan3D*
##### Anaconda users
Simply type:
```conda install -c lcbio aggrescan3d```
##### Vanilla Python
Simply type:
```pip install aggrescan3d```
*For macOS "El Captian" are newer `six` library comes preinstalled and may cause installation erros. Try running: `pip install aggrescan3d --ignore-installed six` instead.*
##### Correctness test
Run a simulation of lcbio's favorite 2gb1 with:
```aggrescan -i 2gb1 -w test_run -v 4```
- If the result is `'aggrescan3d' is not recognized as an internal or external command, operable program or batch file.` it means that your Python's Scripts folder is not on the PATH variable.
- If you see a ```Simulation completed successfully``` message, congratulations you have completed your first *aggrescan3d* simulation.
To check if the server app works:
```a3d_server```
- Open your favourite web browser
- Go to 0.0.0.0:5000 (if the server is not responding depending on the loopback settings localhost:5000 might work)
---
## Docker image
*Aggrescan3D* is also available as a docker image and this tutorial will guide the user through how to create a local, always available *Aggrescan3D* server on their PC using the Docker technology. This could also be a good workaround for
users facing compatibility and installation issues.
*Please note we cannot include FoldX nor Modeller software in distributed images as they require a licence to run. We however explain how to get those running easly and unlok the full potentail of Aggrescan3D inside a Docker container*
- ```lcbio/a3d_server``` - [conda](https://hub.docker.com/r/lcbio/a3d_server/) based distribution. Included Dockerfile should allow the users to build a Docker Image with dynamic mode support
### Beginner's tutorial
While we cannot provide a ground-up guide on Docker usage we do provide basic instructions and further reading material that should make it possible to use this without prior experience. This tutorial is Linux oriented but Docker is also available on Windows10 Pro.
#### 1. Installing Docker
Please refer to the [docs](https://docs.docker.com/install/) which contain detailed and well written guides for different systems:
We also recommend you read [this](https://docs.docker.com/get-started/) starter article on the docker docs
And [this](https://docs.docker.com/install/linux/linux-postinstall/) post-installation tips (especially if you get permission errors and have to always run docker with sudo)
#### 2. Using dynamic mode in the container
To do that one has to create their own image based on our conda image.
- Create a new folder and cd into it ```mkdir docker_build && cd docker_build```
- Create a Dockerfile and copy the contents which can be found [here](https://hub.docker.com/r/lcbio/a3d_server/)
- Uncomment the suggested lines and replace XXXX with your Modeller licence key
- Run ```docker build -t image_name .```
- If the process is successful the image will be available under 'image_name'
#### 3. Get the *Aggrescan3D* image (skip if you did point 2)
To make the image available on your system run:
```
#!bash
docker pull lcbio/a3d_server
```
#### 4. Running the Docker container
The basic goal of the conatiner is to provide a server-like service locally. We recommend to use a following command (explained below):
```
#!bash
docker run --name a3d_service -p 5000:5000 -v /your/absolute/path/to/FoldX:/home/FoldX --restart unless-stopped -d a3d_server
```
- The name command will assign a name to your container which will make it easier to manipulate it in the future
- The -p option exposes your container's 5000 port to your machine's 5000 port. This will mean that you can access the service from your machine.
- The -v option mounts your FoldX folder inside the container which makes it available to the service. This is necessary if you wish to use the stability calculations or mutations. Please leave the second part (after ':') unchanged and make sure you provide an absoulte path.
- The restrart unless-stopped will restart the container on system restart meaning it will be always available (Blocking port 5000 though).
- The -d options means detach - the container will run in the background
Addition interaction with the container can be performed as follows:
- To stop the service: ```docker stop a3d_service```
- To start it again: ```docker start a3d_service```
- To restart a running container (in case it hung, etc): ```docker start a3d_service ```
- To copy files from container to local system (results on the container are stored inside /opt/conda/lib/python2.7/site-packages/a3d_gui/computations/): ```docker cp a3d_service:path/inside/the/container local/path```
- To delete the container (*this will delete all the simulation results that were not copied to the filesystem!*): ```docker rm a3d_service```
To interact with the container's console for purposes other than the server run it via which will give access to a shell with aggrescan installed:
```docker run --name my_container a3d_server /bin/bash```
#### 5. Further reading
- Running docker images [explained](https://www.pluralsight.com/guides/docker-a-beginner-guide)
- We found [this](https://docker-curriculum.com/) guide to be quite informative and well-written.
| Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/README.md | README.md |
import os
import json
import re
import sqlite3
import numpy as np
from os.path import join
from glob import glob
from utils import query_db, status_color, sort_dict
from a3d_gui import app
from collections import OrderedDict
from aggrescan.optparser import parse_config_file, get_parser_object, _parse_mut
def generate_config(jid):
"""
Function that that reads a database and creates a config file
that then can be easily run by Aggrescan3D on the cluster
paths to cabs and foldx might need to be changed if changes happen
:param jid: job unique id
:return: None
"""
# There should be exactly one entry in that table. The location needs to be validated on submit
foldx_loc = query_db("SELECT foldx_path FROM system_data WHERE id=1", one=True)[0]
file_header = "# Generated for job: %s" % jid
try:
project_settings = query_db("SELECT dynamic, mutate, mutation, chains, \
foldx, distance, auto_mutation FROM project_details WHERE jid=?", [jid], one=True)
except sqlite3.OperationalError: # Backwards compatibility when the auto_mutation column didn't exist
query_db("ALTER TABLE project_details ADD COLUMN auto_mutation TEXT", insert=True)
project_settings = query_db("SELECT dynamic, mutate, mutation, chains, \
foldx, distance, auto_mutation FROM project_details WHERE jid=?", [jid], one=True)
project_name = query_db("SELECT project_name FROM user_queue WHERE jid=?", [jid], one=True)
with open(join(app.config['USERJOB_DIRECTORY'], jid, "config.ini"), 'w') as f:
_write(f, file_header)
_write(f, "# The job can also be identified by its name: %s" % project_name['project_name'])
_write(f, "v = 3")
_write(f, "protein = input.pdb")
_write(f, "movie = webm")
_write(f, "distance = %s" % project_settings["distance"])
_write(f, "remote")
if project_settings["chains"]:
if len(project_settings["chains"]) == 1: # Aggrescan only accepts 1 specific chain
_write(f, "chain = %s" % project_settings["chains"])
if project_settings["foldx"]:
_write(f, "foldx = %s" % foldx_loc)
if project_settings["dynamic"]:
_write(f, "dynamic")
if project_settings["auto_mutation"]:
_write(f, "auto_mutation = %s" % project_settings["auto_mutation"])
if project_settings["mutation"]:
for entry in project_settings["mutation"].split():
_write(f, "m = %s" % entry)
def reverse_config(filepath):
argv, mutations = parse_config_file(filepath)
parser = get_parser_object()
options = parser.parse_args(argv)
mutations = _parse_mut(mutations)
final_options = {
'dynamic': options.dynamic,
'distance': options.distance,
'chain': options.chain,
"foldx": options.foldx,
'auto_mutation': options.auto_mutation,
}
print final_options, mutations
return final_options, mutations
def prepare_data(jid):
"""
Pull all the necessary data from the database and prepare an OrderedDict
The dict is then used to display the job_info page
raises an IO error if there is no data in current database for the specified job ID
:param jid: unique job ID
:return: dict of option:value pairs
"""
system_info = query_db("SELECT chain_sequence, distance, mutt_energy_diff, dynamic, \
mutation, mutate, chains, foldx, auto_mutation FROM project_details WHERE jid=?", [jid], one=True)
basic_info = query_db("SELECT started, project_name, status , working_dir FROM "
"user_queue WHERE jid=?", [jid], one=True)
project_info = OrderedDict()
if not basic_info or not system_info:
raise IOError
project_info['status'] = basic_info['status']
project_info['status_color'] = status_color(project_info['status'])
# Example projects will not exist by their abspath on users machine
if os.path.exists(os.path.join(app.config['USERJOB_DIRECTORY'], basic_info['working_dir'].split("/")[-1])):
project_info['working_dir'] = os.path.join(app.config['USERJOB_DIRECTORY'], basic_info['working_dir'].split("/")[-1])
else:
project_info['working_dir'] = basic_info['working_dir']
# csv table reading
mut = {}
if system_info['mutate'] == 1:
for mutation in system_info['mutation'].strip().replace(" ", "").split(","):
k = mutation[-1] + mutation[2:-1] # the last letter is the chain ID letter, starting from index 2 is the cahin ID number
mut[k] = mutation
if system_info['foldx']: # foldx is app
project_info['foldx'] = "Yes"
else:
project_info['foldx'] = "No"
avg_scores = ''
a3d_table = []
a3dtable = ''
chains = set()
models = ["input.pdb"]
models.extend(["model_%s.pdb" % str(i) for i in range(12)])
project_info['models'] = models
project_info['error'] = ''
project_info['table'] = ''
project_info['avg_scores'] = {'dummy': 'dummy'} # click highest model would cause template errors otheriwse for static jobs
project_info['chains'] = system_info['chains'] or ""
project_info['distance'] = system_info['distance']
project_info['chain_sequence'] = system_info['chain_sequence']
project_info['project_name'] = basic_info['project_name']
project_info['started'] = basic_info['started']
project_info['mutation'] = mut
project_info['mutate'] = system_info['mutate']
project_info['mutt_energy_diff'] = system_info['mutt_energy_diff']
project_info['auto_mutation'] = False
project_info['auto_mutation_used'] = system_info['auto_mutation']
project_info['autom_data'] = {'dummy': 'dummy'}
if system_info['dynamic'] == 1:
project_info['dynamic'] = True
pdb_in_dir = set([os.path.basename(i) for i in glob(join(project_info['working_dir'], "*.pdb"))])
models = set(models)
if len(models-pdb_in_dir) > 0:
project_info['model_files'] = 'missing'
else:
project_info['model_files'] = 'ok'
else:
project_info['dynamic'] = False
if project_info['status'] == 'done':
if system_info['auto_mutation']:
project_info['autom_data'] = _parse_auto_mut_info(
join(project_info['working_dir'], 'Mutations_summary.csv'))
project_info['auto_mutation'] = True
if project_info['dynamic']:
with open(os.path.join(project_info['working_dir'], "averages")) as f:
loaded_data = json.load(f)
project_info['avg_scores'] = sort_dict(loaded_data)
with open(os.path.join(project_info['working_dir'],
"A3D.csv")) as fw:
rec = re.compile(r"^(.*),(.*),(.*),(.*),(.*)$", re.M)
d = rec.findall(fw.read().replace("\r", ""))[1:]
dat = []
for row in d:
if len(row) != 5:
continue
chain = row[1]
chains.update(chain)
residx = row[2]
resname = row[3]
v = float(row[4])
dat.append(v)
a3d_table.append((residx, resname, chain, "%01.4f" % (v)))
min3d = min(dat)
max3d = max(dat)
sum3d = np.sum(dat)
avg3d = sum3d/len(dat)
a3dtable = {'min': min3d, 'avg': avg3d, 'max': max3d,
'sum': sum3d, 'tab': a3d_table}
project_info['table'] = a3dtable
return project_info
def _write(obj, text):
obj.write(text)
obj.write("\n")
def _parse_mut(mut_list):
"""Necessary for now as those come as a list of dicts and the db needs a simple string"""
return ["%s%s%s%s" % (i['oldres'], i['newres'], i['idx'], i['chain']) for i in mut_list]
def _parse_auto_mut_info(filename):
"""
Reads the file and returns an ordered dict with the first column as keys, and the next 3 as a list
Currently will return top x results - another parameter to decide on
"""
data = OrderedDict()
max_results = 12
counter = 0
try:
with open(filename, 'r') as f:
f.readline() # Skip first line with labels
for line in f:
counter += 1
parsed = line.split(",")
data[parsed[0]] = [float(parsed[1]), float(parsed[2]), float(parsed[3])]
if counter >= max_results:
break
except IOError:
return {'Data missing': False} # The template will recognize this as a sign not to load the tab
if not data: # File is empty, the likely case is that there were no suitable mutations found
data = {'No mutants': False}
return data | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/create_config.py | create_config.py |
import re
import urllib2
import gzip
import os
from StringIO import StringIO
from utils import query_db
from wtforms.validators import DataRequired, Length, Email, optional, \
ValidationError, NumberRange
from parsePDB import PdbParser
# from config_manager import config
###
### Validators shared by CABS and aggrescan
###
def pdb_input_validator(form, field):
if form.input_pdb_code.data and form.input_file.data:
raise ValidationError('Please provide either a PDB code or file, not both.')
if not form.input_pdb_code.data and not form.input_file.data:
raise ValidationError('Protein PDB code or PDB file is required')
if len(field.data) < 4 and not form.input_file.data:
raise ValidationError('Protein code must be 4-letter (2PCY).'
'Leave empty only if PDB file is provided')
def sequence_validator(form, field):
allowed_seq = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N',
'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
for letter in re.sub("\s", "", field.data):
if letter not in allowed_seq:
raise ValidationError('Sequence contains non-standard aminoacid \
symbol: %s' % letter)
def pdb_file_validator(form, field):
if form.input_file.data:
p = PdbParser(form.input_file.data.stream, form.chain.data.strip())
_structure_pdb_validator(p)
def pdb_code_validator(form, field):
if len(form.input_pdb_code.data.strip()) == 4:
pdb_code = field.data.strip()
try:
buraki = urllib2.urlopen('http://www.rcsb.org/pdb/files/'+pdb_code+'.pdb.gz')
except:
raise ValidationError("Could not download your protein file from pdb server. Wrong code perhaps?")
b2 = buraki.read()
ft = StringIO(b2)
buraki.close()
with gzip.GzipFile(fileobj=ft, mode="rb") as f:
p = PdbParser(f)
_structure_pdb_validator(p, form.chain.data.strip())
elif not form.input_pdb_code.data:
pass
else:
raise ValidationError("PDB code should contain exactly 4 characters.")
def non_empty_file(form, field):
"""To be used with files only"""
if field.data:
field.data.stream.seek(0, os.SEEK_END)
if field.data.stream.tell() < 1:
raise ValidationError("Empty file provided.")
field.data.stream.seek(0)
def _structure_pdb_validator(p, chains=''):
"""
:param p: parsePDB PdbParser object
:param chains: a list of chain (might also be an empty string)
:return: None, raises ValidationError if any errors are found
"""
missing = p.getMissing()
seq = p.getSequence()
n_chains = p.get_num_chains()
defined_chains = set(chains)
actual_chains = set(p.getChains())
allowed_seq = ['A', 'C', 'D', ' ', 'E', 'F', 'G', 'H', 'I', 'K', 'L',
'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
_max_length = 2000
_max_chains = 10
for e in seq:
if e not in allowed_seq:
raise ValidationError('Non-standard residue in the input \
structure')
for length in p.getChainLengths():
if length < 4:
raise ValidationError("One of the chains in the supplied pdb file is too short."
" Minimal chain length for the simulation is 4.")
if len(seq) == 0:
raise ValidationError('Your pdb file doesnt seem to contain a chain. The server could not extract a sequence.')
if len(seq) > _max_length:
raise ValidationError('CABS-flex allows max %d receptor \
residues. Provided file contains \
%d' % (_max_length, len(seq)))
if n_chains > _max_chains:
raise ValidationError('CABS-flex allows a maximum of %d chains.'
'Your protein has: %d' % (n_chains, _max_chains))
if missing > 5:
raise ValidationError('Missing atoms within protein (M+N = %d). \
Protein must fulfill M+N<6, where M - number of \
chains, N - number of breaks' % (missing))
if not defined_chains.issubset(actual_chains):
raise ValidationError("Wrong chain selection. Your PDB contains chain(s): %s and you tried to select chain(s): %s" %
(", ".join(actual_chains), ", ".join(defined_chains)))
def only_letters_validator(form, field):
pattern = re.compile("[^a-zA-Z\s]")
if pattern.findall(field.data):
raise ValidationError("Only letters and whitespaces are allowed in the chain field. You entered: %s" % field.data)
###
### Aggrescan specific validators
###
def foldx_validator(form, field):
"""check if a valid foldx loc is stored in the database"""
if field.data == '1':
foldx_path = query_db("SELECT foldx_path FROM system_data WHERE id=1", one=True)[0]
req_file = os.path.join(foldx_path, 'rotabase.txt')
if not os.path.isfile(req_file):
raise ValidationError("Trying to run Stability calculations without a proper FoldX path specified."
" (%s missing rotabase.txt file)" % foldx_path)
def foldx_and_m_validator(form, field):
if field.data == "1" and form.foldx.data != "1":
raise ValidationError("Please select the Stability calculations option if you wish to create a mutant.")
def single_chain_validator(form, field):
pattern = re.compile("[^a-zA-Z\s]")
if pattern.findall(field.data):
raise ValidationError("Only letters and whitespaces are allowed in the chain field. You entered: %s" % field.data)
elif len(field.data.replace(" ", "")) > 1:
raise ValidationError("Please select a single chain")
def auto_mut_validator(form, field):
if field.data == "1" and form.foldx.data != "1":
raise ValidationError("Please select the Stability calculations option if you wish to use mutation options.")
if field.data == "1" and form.dynamic.data == "1":
raise ValidationError("Automatic mutations do not support the dynamic module. Please select either of those") | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/validators.py | validators.py |
import json
import shutil
import sqlite3
from flask import render_template, url_for, request, flash, redirect, jsonify, g, abort, Response
from flask_wtf import Form
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, BooleanField, HiddenField, RadioField
from wtforms.validators import Length, Email, optional, ValidationError
from a3d_gui import app
from utils import query_db, unique_id, gunzip, connect_db, parse_out, aminoacids, get_undefined_job_ids
from job_handling import run_job, check_jobs
from create_config import generate_config, prepare_data
from validators import *
##############################################################################
@app.before_request
def before_request():
g.sqlite_db = connect_db()
def flash_errors(form):
for field, errors in form.errors.items():
for error in errors:
flash(u"Error in the %s field - %s\n " %
(getattr(form, field).label.text, error), 'error')
class MyForm(Form):
name = StringField('Project name',
validators=[Length(min=4, max=50), optional()],
description="Project name",
default="")
input_pdb_code = StringField('PDB code',
validators=[pdb_input_validator,
pdb_code_validator],
description="1YWO",
default="")
chain = StringField('Chain',
validators=[Length(min=1, max=5),
optional(), single_chain_validator],
description="A",
default="")
input_file = FileField('Local PDB file',
validators=[pdb_file_validator,
non_empty_file])
jid = HiddenField(default=unique_id())
foldx = RadioField("Stability calculations",
validators=[foldx_validator],
choices=[('1', 'Yes'), ('0', 'No')], default='1')
mutation = RadioField('Mutate residues',
choices=[('1', 'Yes'), ('0', 'No')],
validators=[foldx_and_m_validator],
default='0')
auto_mutation = RadioField('Enhance protein solubility',
choices=[('1', 'Yes'), ('0', 'No')],
validators=[auto_mut_validator],
default='0')
dynamic = RadioField("Dynamic mode",
choices=[('1', 'Yes'), ('0', 'No')], default='0')
distance = RadioField('Distance of aggregation analysis: ',
choices=[('5', '5Å'.decode('utf-8')),
('10', '10Å'.decode('utf-8'))],
default='10')
def add_init_data_to_db(form):
jid = unique_id()
name = form.name.data
if len(name) < 2:
name = jid
chains = form.chain.data.strip()
dest_directory = os.path.abspath(os.path.join(app.config['USERJOB_DIRECTORY'], jid))
dest_file = os.path.join(dest_directory, "input.pdb.gz")
os.makedirs(dest_directory)
if form.input_pdb_code.data:
pdb_code = form.input_pdb_code.data.strip()
stream = urllib2.urlopen('http://www.rcsb.org/pdb/files/' + pdb_code + '.pdb.gz')
b2 = stream.read()
string_io_data = StringIO(b2)
with gzip.GzipFile(fileobj=string_io_data, mode="rb") as f:
p = PdbParser(f, chains)
input_seq = p.getSequence()
p.savePdbFile(dest_file)
gunzip(dest_file)
stream.close()
else:
p = PdbParser(form.input_file.data.stream, chains)
input_seq = p.getSequence()
p.savePdbFile(dest_file)
gunzip(dest_file)
chain_numbering = p.getChainIdxResname()
distance = form.distance.data
dynamic = form.dynamic.data
mutate = form.mutation.data
foldx = form.foldx.data
all_chains = chains or "".join(p.getChains())
if mutate == "1":
query_db("INSERT INTO user_queue (jid, project_name, working_dir, status)\
VALUES(?,?,?,?)",
[jid, name, dest_directory, 'mut_wait'], insert=True)
query_db("INSERT INTO project_details (jid, chain_numbering, chain_sequence, \
dynamic, mutate, distance, chains, foldx) \
VALUES(?,?,?,?,?,?,?,?)",
[jid, chain_numbering, input_seq, dynamic, mutate, distance, all_chains, foldx], insert=True)
else:
query_db("INSERT INTO user_queue (jid, project_name, working_dir, status)\
VALUES(?,?,?,?)",
[jid, name, dest_directory, 'running'], insert=True)
query_db("INSERT INTO project_details (jid, chain_numbering, chain_sequence, \
dynamic, mutate, distance, chains, foldx) \
VALUES(?,?,?,?,?,?,?,?)",
[jid, chain_numbering, input_seq, dynamic, mutate, distance, all_chains, foldx], insert=True)
return jid, dest_directory
@app.route('/job/<jid>/')
def job_status(jid):
try:
all_info = prepare_data(jid)
except IOError as e:
flash("Your job tried to access files that don't exists. Perhaps a job with status done had its files removed? "
"Or you tried to set done on a job that misses aggrescan files. "
"Changed status to error.")
flash("Your error: %s" % str(e))
query_db("UPDATE user_queue SET status='error'\
WHERE jid=?", [jid], insert=True)
return job_status(jid)
aa_t = aminoacids()
return render_template('job_info.html',
jid=jid, aa_dict=aa_t, info=all_info)
@app.route('/mutate/<jid>', methods=['GET', 'POST'])
def mutate(jid):
q = query_db("SELECT chain_numbering FROM project_details \
WHERE jid=?", [jid], one=True)
chains = json.loads(q['chain_numbering'])
aa_t = aminoacids()
return render_template('mutate.html', sequence=chains,
jid=jid, aa_dict=aa_t)
@app.route('/auto_mutate/<jid>', methods=['GET', 'POST'])
def auto_mutate(jid):
q = query_db("SELECT chain_numbering FROM project_details \
WHERE jid=?", [jid], one=True)
chains = json.loads(q['chain_numbering'])
aa_t = aminoacids()
return render_template('auto_mutate.html', sequence=chains,
jid=jid, aa_dict=aa_t)
@app.route('/_upmut2', methods=['GET', 'POST'])
def up_remutation():
if request.method == 'POST':
jid = unique_id()
old_jid = request.form.get('oldjid', '')
mut = ", ".join(request.form.getlist('toreplace[]'))
old_queue = query_db("SELECT project_name, working_dir FROM \
user_queue WHERE jid=?", [old_jid], one=True)
new_name = old_queue['project_name']+" [mutate: "+str(mut)+"]"
d = query_db("SELECT foldx, dynamic, distance, chains FROM project_details WHERE jid=?",
[old_jid], one=True)
dest_directory = os.path.join(app.config['USERJOB_DIRECTORY'], jid)
old_directory = old_queue['working_dir']
os.mkdir(dest_directory)
shutil.copy(os.path.join(old_directory, "output.pdb"),
os.path.join(dest_directory, "input.pdb"))
with open(os.path.join(dest_directory, "input.pdb"), "rb") as rea:
p = PdbParser(rea)
sequence = p.getSequence()
chain_numbering = p.getChainIdxResname()
query_db("INSERT INTO user_queue(jid, project_name, working_dir, status) VALUES(?,?,?,?)",
[jid, new_name, dest_directory, 'running'], insert=True)
query_db("INSERT INTO project_details(jid, dynamic, mutate, mutation, chains, foldx, distance, "
"chain_sequence, chain_numbering) VALUES(?,?,?,?,?,?,?,?,?)",
[jid, d['dynamic'], 1, mut, d['chains'], 1, d['distance'],
sequence, chain_numbering], insert=True)
generate_config(jid)
pid = run_job(dest_directory)
query_db("UPDATE user_queue SET pid=? WHERE jid=?", [pid, jid], insert=True)
return redirect(url_for('job_status', jid=jid))
@app.route('/_upmut', methods=['GET', 'POST'])
def up_mutation():
if request.method == 'POST':
jid = request.form.get('jid', '')
mut = ", ".join(request.form.getlist('toreplace[]'))
details = query_db("SELECT project_name, working_dir FROM user_queue WHERE \
jid=?", [jid], one=True)
proname = details['project_name'] + " [mutate: "+mut+"]"
query_db("UPDATE user_queue SET status='running', \
project_name=? WHERE jid=?", [proname, jid], insert=True)
query_db("UPDATE project_details SET mutate=?, mutation=? WHERE jid=?", [1, mut, jid], insert=True)
generate_config(jid)
pid = run_job(details['working_dir'])
query_db("UPDATE user_queue SET pid=? WHERE jid=?", [pid, jid], insert=True)
return redirect(url_for('job_status', jid=jid))
@app.route('/_upautomut', methods=['GET', 'POST'])
def up_automutation():
if request.method == 'POST':
jid = request.form.get('jid', '')
n_mutated = request.form.get('n_mutated', '')
n_cores = request.form.get('n_cores', '')
automut = "%s %s " % (n_mutated, n_cores) + " ".join(request.form.getlist('toreplace[]'))
details = query_db("SELECT project_name, working_dir FROM user_queue WHERE \
jid=?", [jid], one=True)
proname = details['project_name'] + " (automated mutations)"
query_db("UPDATE user_queue SET status='running', \
project_name=? WHERE jid=?", [proname, jid], insert=True)
try:
query_db("UPDATE project_details SET auto_mutation=? WHERE jid=?", [automut, jid], insert=True)
except sqlite3.OperationalError: # Backwards compatibility when the column didn't exist
query_db("ALTER TABLE project_details ADD COLUMN auto_mutation TEXT", insert=True)
query_db("UPDATE project_details SET auto_mutation=? WHERE jid=?", [automut, jid], insert=True)
generate_config(jid)
pid = run_job(details['working_dir'])
query_db("UPDATE user_queue SET pid=? WHERE jid=?", [pid, jid], insert=True)
return redirect(url_for('job_status', jid=jid))
@app.route('/_check_status/<jid>', methods=['GET'])
def get_job_status(jid):
response = {}
details = query_db("SELECT working_dir,status,jid FROM user_queue WHERE \
jid=?", [jid], one=True)
try:
with open(os.path.join(details['working_dir'], "Aggrescan.log"), 'r') as f:
response['log'] = f.read()
if (details['status'] != 'done' and details['status'] != 'error') and check_jobs(details['jid']):
response['reload'] = True
except IOError:
response['log'] = "Couldn't open the log for simulation at %s" % os.path.join(details['working_dir'], "Aggrescan.log")
return jsonify(**response)
@app.route('/index', methods=['GET', 'POST'])
@app.route('/', methods=['GET', 'POST'])
def index_page():
form = MyForm()
foldx_path = query_db("SELECT foldx_path FROM system_data WHERE id=1", one=True)[0]
if request.method == 'POST':
if form.validate_on_submit():
jid, work_dir = add_init_data_to_db(form)
if form.mutation.data == '1':
return redirect(url_for('mutate', jid=jid))
elif form.auto_mutation.data == '1':
return redirect(url_for("auto_mutate", jid=jid))
else:
generate_config(jid)
pid = run_job(work_dir)
query_db("UPDATE user_queue SET pid=? WHERE jid=?", [pid, jid], insert=True)
return redirect(url_for('job_status', jid=jid))
flash_errors(form)
return render_template('index.html', form=form, foldx_path=foldx_path)
########################################################################################################################
@app.route('/queue', methods=['POST', 'GET'], defaults={'page': 1})
@app.route('/queue/page/<int:page>/', methods=['POST', 'GET'])
def queue_page(page=1):
before = (page - 1) * app.config['PAGINATION']
if request.method == 'GET':
search = request.args.get('q', '')
if search != '':
flash("Searching results for %s ..." % (search), 'warning')
q = query_db("SELECT project_name, jid, status, \
started datet FROM user_queue \
WHERE status!='mut_wait' AND (project_name LIKE ? OR \
jid=?) ORDER BY started DESC LIMIT ?,?",
["%"+search+"%", search, before,
app.config['PAGINATION']])
q_all = query_db("SELECT status FROM user_queue WHERE \
status!='mut_wait' AND (project_name LIKE ? OR jid=?) \
ORDER BY started DESC", ["%"+search+"%", search])
out = parse_out(q)
if len(out) == 0:
flash("Nothing found", "error")
elif len(out) == 1:
flash("Project found!", "info")
jid = out[0]['jid']
return redirect(url_for('job_status', jid=jid))
return render_template('queue.html', queue=out, page=page,
total_rows=len(q_all))
# Get the jobs from database
qall = query_db("SELECT status FROM user_queue WHERE \
status!='mut_wait' ORDER BY started DESC", [])
q = query_db("SELECT jid, project_name, status, started datet \
FROM user_queue WHERE status != 'mut_wait' \
ORDER BY started DESC LIMIT ?,?", [before, app.config['PAGINATION']])
# Check if status has changed
check_jobs(*get_undefined_job_ids(q))
# Get updated que
q = query_db("SELECT jid, project_name, status, started datet \
FROM user_queue WHERE status != 'mut_wait' \
ORDER BY started DESC LIMIT ?,?", [before, app.config['PAGINATION']])
out = parse_out(q)
return render_template('queue.html', queue=out, total_rows=len(qall),
page=page) | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/views.py | views.py |
from a3d_gui import app
from utils import query_db
from server_plot import create_plot
import os
import tarfile
import psutil
import shutil
import sqlite3
import signal
from os.path import join, isfile, exists
from subprocess import Popen, PIPE
from glob import glob
from flask import Response, flash, url_for
"""
Module intended for job (process, db status) managing for the Aggrescan3D standalone app.
CAUTION! Some of the functions here perform file deletion as well as process killing
Should you chose to modify basic settings or job handling and db managing functions do so with care
"""
_static_file_list = set(["A3D.csv", "output.pdb"])
_dynamic_file_list = set(["CABSflex_rmsf.png", "CABSflex_rmsf.csv", "averages"])
_auto_mut_file_list = set(["A3D.csv", "output.pdb", "Mutations_summary.csv"])
_other_files = set(["Aggrescan.log", "Aggrescan.error", "input.pdb", "input.pdb.gz", "clip.webm", "models.tar.gz",
"stats.tar.gz", "config.ini", "output.pdb", "MutantEnergyDiff"])
def run_job(working_dir):
curr_dir = os.path.abspath(os.curdir) # save the working dir of server app, otherwise it loses track of the db
try:
os.chdir(working_dir)
process = Popen(["aggrescan", "-c", "config.ini"],
stdout=PIPE,
stderr=PIPE,
preexec_fn=os.setpgrp) # hopefully the prevents the job from dying with the server
return process.pid
except AttributeError: # Windows band-aid
os.chdir(working_dir)
process = Popen(["aggrescan", "-c", "config.ini"],
stdout=PIPE,
stderr=PIPE)
return process.pid
finally:
os.chdir(curr_dir) # It is crucial that python stays within its starting directory
@app.route('/_rerun_job/<jid>', methods=['GET'])
def rerun_job(jid):
working_dir = query_db("SELECT working_dir FROM user_queue WHERE jid=?", [jid])[0][0]
job_pid = query_db("SELECT pid FROM user_queue WHERE jid=?", [jid])[0][0]
if isfile(join(working_dir, "config.ini")):
if is_running(job_pid):
return Response("The job appears to still be running. Stop it first. Re-run aborted.",
status=400, content_type="plain/text")
try:
os.remove(join(working_dir, "Aggrescan.log"))
except OSError:
pass
new_pid = run_job(working_dir)
query_db("UPDATE user_queue SET status='running', pid=? WHERE jid=?", [new_pid, jid], insert=True)
return url_for('job_status', jid=jid)
else:
return Response("File config.ini not present in working directory for the job. Re-run aborted.",
status=400, content_type="plain/text")
@app.route('/_kill_job/<jid>', methods=['GET'])
def kill_job(jid):
"""Kill the aggrescan process and all its children, set status to error"""
proc_pid = query_db("SELECT pid FROM user_queue WHERE jid=?", [jid])[0][0]
try:
process = psutil.Process(proc_pid)
if process.name() == "aggrescan" and process.is_running():
kill_proc_tree(proc_pid)
query_db("UPDATE user_queue SET status='error' WHERE jid=?", [jid], insert=True)
return Response("Job killed", status="200", content_type="plain/text")
else:
return Response("Coulnd't stop the job. The pid assigned to it no "
"longer points to an active aggrescan job.",
status="400", content_type="plain/text")
except psutil.NoSuchProcess:
return Response("Coulnd't stop the job. There is no such process.",
status="400", content_type="plain/text")
except psutil.AccessDenied as e:
return Response("You dont have permissions to stop the job. %s" % str(e),
status="400", content_type="plain/text")
except psutil.TimeoutExpired as e:
return Response("Coulnd't stop the job. %s" % str(e),
status="400", content_type="plain/text")
except ValueError as e:
return Response("Can't kill this job. "
"Most likely this job was started manually and can't be stopped by this interface",
status="400", content_type="plain/text")
@app.route('/_kill_delete_job/<jid>', methods=['GET'])
def kill_delete_job(jid):
"""Terminate the aggrescan process and all its children, and delete all the aggrescan files"""
try:
kill_response = kill_job(jid)
delete_response = delete_files(jid)
if delete_response and kill_response.status_code == 200:
_silent_delete_job(jid)
flash("Files and directory deleted. The job %s has been stopped." % jid)
return url_for('index_page')
elif not delete_response and kill_response.status_code == 200:
_silent_delete_job(jid)
flash("Files deleted but directory still contains files. The job %s has been stopped." % jid)
return url_for('index_page')
elif delete_response and kill_response.status_code != 200:
_silent_delete_job(jid)
flash("Something went wrong. The files and directory were deleted but the job couldn't be stopped."
"Reason: %s" % kill_response.response)
return url_for('index_page')
else:
return Response("Something went wrong. The directory was not deleted"
"and the job couldn't be stopped."
"Reason: %s" % kill_response.response,
status="400", content_type="plain/text")
except Exception as e: # Not nice but there is no outer instance to take that to and I really don't want this crashing the app
return Response("Something went terribly wrong and your request failed in an unpredictable way ",
status="400", content_type="plain/text")
def is_running(proc_pid):
"""Find the aggrescan process based on database-stored pid"""
try:
process = psutil.Process(proc_pid)
if process.name() == "aggrescan" and process.is_running() and process.status() != "zombie":
return True
return False
except psutil.Error:
return False
except ValueError: # for negative pids on added jobs
return False
def check_jobs(*jobs):
"""
Attempt to check the job's status. Whether the job is done, missing files, an error occurred, etc
:param jobs: a list of job_ids
:return: Bool indicating if the job is done but only if one job id was provided (if more - always None)
"""
for jid in jobs:
done = False # helper to reduce the number of ifs
working_dir = query_db("SELECT working_dir FROM user_queue WHERE jid=?", [jid])[0][0]
job_pid = query_db("SELECT pid FROM user_queue WHERE jid=?", [jid])[0][0]
if isfile(join(working_dir, "Aggrescan.error")):
query_db("UPDATE user_queue SET status='error' WHERE jid=?", [jid], insert=True)
elif is_running(job_pid):
query_db("UPDATE user_queue SET status='running' WHERE jid=?", [jid], insert=True)
elif not exists(working_dir):
query_db("UPDATE user_queue SET status='missing_files' WHERE jid=?", [jid], insert=True)
else:
details = query_db("SELECT dynamic, mutate, auto_mutation FROM project_details WHERE jid=?", [jid], one=True)
files_in_dir = set([os.path.basename(i) for i in glob(join(working_dir, "*"))])
if details['dynamic']: # attempt to deduct if the job is running or the files are simply not present in the working dir
missing_files = len(_static_file_list - files_in_dir) + len(_dynamic_file_list - files_in_dir)
if missing_files == 0:
query_db("UPDATE user_queue SET status='done' WHERE jid=?", [jid], insert=True)
prepare_files(working_dir)
done = True
else:
query_db("UPDATE user_queue SET status='missing_files' WHERE jid=?", [jid], insert=True)
elif details['auto_mutation']:
if _auto_mut_file_list - files_in_dir: # "since the most important files are present we assume the job is done"
query_db("UPDATE user_queue SET status='missing_files' WHERE jid=?", [jid], insert=True)
else:
query_db("UPDATE user_queue SET status='done' WHERE jid=?", [jid], insert=True)
done = True
else:
if _static_file_list - files_in_dir: # "since two most important files are present we assume the job is done"
query_db("UPDATE user_queue SET status='missing_files' WHERE jid=?", [jid], insert=True)
else:
query_db("UPDATE user_queue SET status='done' WHERE jid=?", [jid], insert=True)
done = True
if details['mutate'] and done:
try:
with open(join(working_dir, "MutantEnergyDiff"), 'r') as f:
mut_energy_dif = f.read().split()[0].strip()
query_db("UPDATE project_details SET mutt_energy_diff=? WHERE jid=?",
[mut_energy_dif, jid], insert=True)
except IOError:
query_db("UPDATE user_queue SET status='missing_files' WHERE jid=?", [jid], insert=True)
if len(jobs) == 1:
return done
def prepare_files(working_dir):
"""Move some files around to make it easier for the pseudo server"""
curr_dir = os.path.abspath(os.curdir) # save the working dir of server app, otherwise it loses track of the db
try: # make absolutely sure it gets back to the curr_dir
os.chdir(working_dir)
with tarfile.open("models.tar.gz", 'r:gz') as tar:
tar.extractall()
os.remove("models.tar.gz") # remove the archive since the files are already outside anyway
except IOError:
pass # models are not present in the folder, this can happen shouldn't be an issue
try:
os.chdir(working_dir)
with tarfile.open("stats.tar.gz", 'r:gz') as tar:
tar.extractall()
os.remove("stats.tar.gz") # remove the archive since the files are already outside anyway
except IOError:
pass # stats are not present in the folder, this can happen shouldn't be an issue
finally:
os.chdir(curr_dir)
def delete_files(job_id):
"""
Delete all aggrescan files in the working directory. If the directory is then empty it is also removed
Warning! This will delete any files and subfolders in "tmp" folder in your working directory.
Returns True if the entire dir is deleted, False otherwise
"""
n_models = 12 # TODO customizable number of models for the gui
working_dir = query_db("SELECT working_dir FROM user_queue WHERE jid=?", [job_id])[0][0]
chains = query_db("SELECT chains FROM project_details WHERE jid=?", [job_id])[0][0]
pictures = query_db("SELECT * FROM pictures WHERE jid=?", [job_id])
if pictures is not None:
for pic in pictures:
try:
os.remove(join(app.config['PICTURES'], pic['filename']))
except OSError:
pass # the picture was likely deleted from the folder manually
files = ["%s.png" % i for i in chains]
files.extend(["%s.svg" % i for i in chains])
files.extend(["model_%d.pdb" % i for i in range(n_models)])
files.extend(["model_%d.pdb" % i for i in range(n_models)])
files_in_dir = [i for i in glob(working_dir+"/*") if isfile(i)]
shutil.rmtree(join(working_dir, "tmp"), ignore_errors=True)
for to_del in files_in_dir:
try:
os.remove(to_del)
except OSError:
flash("Couldn't delete a file, which was supposed to be here: %s" % to_del)
try:
if os.listdir(working_dir):
return False
else:
try:
os.rmdir(working_dir)
return True
except OSError:
return False # Something went in the way, shouldn't happen but if it does lets not make a mess about it
except OSError:
flash("Attempted to delete %s but it already doesn't exist." % working_dir)
return True
def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True,
timeout=3):
"""
Kill a process tree. SIGTERM is sent first, then SIGKILL.
If a process survives that a psutil.TimeoutExpired is raised
If everything goes well None is the return value
"""
if pid == os.getpid():
raise RuntimeError("I refuse to kill myself")
parent = psutil.Process(pid)
children = parent.children(recursive=True)
if include_parent:
children.append(parent)
for p in children:
try:
p.send_signal(sig)
except psutil.NoSuchProcess: # Parent likely dies on child death so just ignore that
pass
gone, alive = psutil.wait_procs(children, timeout=timeout)
if alive:
for p in alive:
p.send_signal(signal.SIGKILL)
gone, alive = psutil.wait_procs(children, timeout=timeout)
if alive:
raise psutil.TimeoutExpired("Failed to stop or kill a process")
def _silent_delete_job(jid):
"""Delete a job from current database, returns only success or failure"""
try:
query_db("DELETE FROM user_queue WHERE jid=?", [jid], insert=True)
query_db("DELETE FROM project_details WHERE jid=?", [jid], insert=True)
except sqlite3.Error:
flash("For some reason couldn't delete %s from database. "
"Perhaps it already doesn't exist?" % jid, 'alert') | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/job_handling.py | job_handling.py |
import gzip
import uuid
import re
import sqlite3
from flask import g
from a3d_gui import app
from collections import OrderedDict
from os.path import join
def gunzip(filename):
gunzipped = ".".join(filename.split(".")[:-1])
with open(gunzipped, 'w') as f_out:
with gzip.open(filename, 'rb') as f_in:
f_out.writelines(f_in)
def unique_id():
return hex(uuid.uuid4().time)[2:-1]
def regexp(expr, item):
r = re.compile(expr)
return r.match(item) is not None
def connect_db():
"""Connects to a specific database."""
try:
rv = sqlite3.connect(app.config['DATABASE'])
rv.create_function('regexp', 2, regexp)
rv.row_factory = sqlite3.Row
except sqlite3.Error:
raise
return rv
def get_db():
"""
Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
def query_db(query, args=(), one=False, insert=False):
mydb = get_db()
cur = mydb.cursor()
cur.execute(query, args)
if insert:
mydb.commit()
cur.close()
return cur.lastrowid
else:
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
def status_color(status, shorter=True):
if not status:
return '<span class="label label-danger">\
<i class="fa fa-exclamation-circle"></i> error</span>'
if not shorter:
if status == 'pending':
return '<span class="label label-warning">\
<i class="fa fa-spin fa-spinner"></i> pending \
</span>'
elif status == 'missing_files':
return '<span class="label label-info">\
<i class="fa fa-sliders"></i> Missing files</span>'
elif status == 'running':
return '<span class="label label-primary">\
<i class="fa fa-bolt"></i> running</span>'
elif status == 'error':
return '<span class="label label-danger">\
<i class="fa fa-exclamation-circle"></i> error</span>'
elif status == 'done':
return '<span class="label label-success">\
<i class="fa fa-check-circle-o"></i> done</span>'
else:
if status == 'pending':
return '<span class="label label-warning">\
<i class="fa fa-spin fa-spinner"></i> pending</span>'
elif status == 'missing_files':
return '<span class="label label-info">\
<i class="fa fa-sliders"></i> Missing files</span>'
elif status == 'running':
return '<span class="label label-primary">\
<i class="fa fa-bolt"></i> running</span>'
elif status == 'error':
return '<span class="label label-danger">\
<i class="fa fa-exclamation-circle"></i> error</span>'
elif status == 'done':
return '<span class="label label-success">\
<i class="fa fa-check-circle-o"></i> done</span>'
def sort_dict(my_dict):
new_dict = OrderedDict()
for key, value in sorted(my_dict.iteritems(), key=lambda (k, v): (v, k), reverse=True):
new_dict[key] = value
return new_dict
def aminoacids():
aa_dict = {'A': 'ALA', 'R': 'ARG', 'N': 'ASN', 'D': 'ASP', 'C': 'CYS',
'E': 'GLU', 'Q': 'GLN', 'G': 'GLY', 'H': 'HIS', 'I': 'ILE',
'L': 'LEU', 'K': 'LYS', 'M': 'MET', 'F': 'PHE', 'P': 'PRO',
'S': 'SER', 'T': 'THR', 'W': 'TRP', 'Y': 'TYR', 'V': 'VAL',
'X': 'UNK'}
aa_dict_F = {'A': 'alanine', 'R': 'arginine', 'N': 'asparagine',
'D': 'aspartic acid', 'C': 'cysteine', 'E': 'glutamic acid',
'Q': 'glutamine', 'G': 'glycine', 'H': 'histidine',
'I': 'isoleucine', 'L': 'leucine', 'K': 'lysine',
'M': 'methionine', 'F': 'phenylalanine', 'P': 'proline',
'S': 'serine', 'T': 'threonine', 'W': 'tryptophan',
'Y': 'tyrosine', 'V': 'valine', 'X': 'unknown'}
aa_t = []
for k in sorted(aa_dict, key=aa_dict.get):
if k != 'X':
aa_t.append((aa_dict[k], aa_dict_F[k], k))
return aa_t
def get_undefined_job_ids(q):
to_check = []
for i in q:
if i['status'] == 'pending' or i['status'] == 'missing_files' or i['status'] == 'running':
to_check.append(i['jid'])
return to_check
def parse_out(q):
out = []
for row in q:
if row['datet']:
dtt = row['datet']
else:
dtt = "-"
l = {'project_name': row['project_name'], 'jid': row['jid'],
'date': dtt, 'status': status_color(row['status'])}
out.append(l)
return out | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/utils.py | utils.py |
import gzip
from re import compile, sub
import json
def arraytostring(ar):
i = ["%d-%d" % e for e in ar]
return ", ".join(i)
class PdbParser:
def __init__(self, filehandler, chain=''):
self.codification = {"ALA" : 'A', "CYS" : 'C', "ASP" : 'D', "GLU" : 'E', "PHE" : 'F', "GLY" : 'G', "HIS" : 'H', "ILE" : 'I', "LYS" : 'K', "LEU" : 'L', "MET" : 'M', "MSE" : 'M', "ASN" : 'N', "PYL" : 'O', "PRO" : 'P', "GLN" : 'Q', "ARG" : 'R', "SER" : 'S', "THR" : 'T', "SEC" : 'U', "VAL" : 'V', "TRP" : 'W', "5HP" : 'E', "ABA" : 'A', "AIB" : 'A', "BMT" : 'T', "CEA" : 'C', "CGU" : 'E', "CME" : 'C', "CRO" : 'X', "CSD" : 'C', "CSO" : 'C', "CSS" : 'C', "CSW" : 'C', "CSX" : 'C', "CXM" : 'M', "DAL" : 'A', "DAR" : 'R', "DCY" : 'C', "DGL" : 'E', "DGN" : 'Q', "DHI" : 'H', "DIL" : 'I', "DIV" : 'V', "DLE" : 'L', "DLY" : 'K', "DPN" : 'F', "DPR" : 'P', "DSG" : 'N', "DSN" : 'S', "DSP" : 'D', "DTH" : 'T', "DTR" : 'X', "DTY" : 'Y', "DVA" : 'V', "FME" : 'M', "HYP" : 'P', "KCX" : 'K', "LLP" : 'K', "MLE" : 'L', "MVA" : 'V', "NLE" : 'L', "OCS" : 'C', "ORN" : 'A', "PCA" : 'E', "PTR" : 'Y', "SAR" : 'G', "SEP" : 'S', "STY" : 'Y', "TPO" : 'T', "TPQ" : 'F', "TYS" : 'Y', "TYR" : 'Y' }
keys = self.codification.keys()
self.sequences = {}
self.onlycalfa = ""
self.chain = chain
self.canumber = 0
self.allnumber = 0
seq = compile(r"^ATOM.{9}CA..(?P<seqid>.{3}).(?P<chain>.{1})(?P<resid>.{4})") # TODO zle dla alternatywnych
if chain != '':
ch = "|".join(list(chain))
seq_c = compile(r"^ATOM.{9}CA.( |A)(?P<seqid>.{3}).("+ch+")")
atm = compile(r"^ATOM.{9}(.{3})( |A)(?P<seqid>.{3}).("+ch+")(?P<resid>.{4})(?P<x>.{12})(?P<y>.{8})(?P<z>.{8})")
else:
atm = compile(r"^ATOM.{9}(.{3})( |A)(?P<seqid>.{3})..(?P<resid>.{4})(?P<x>.{12})(?P<y>.{8})(?P<z>.{8})")
seq_c = compile(r"^ATOM.{9}CA.( |A)(?P<seqid>.{3})")
ter = compile(r"^TER") # TODO nie jestem pewien
mod = compile(r"^ENDMDL") # TODO nie jestem pewien
self.trajectory = []
self.sequence = ""
self.resindexes = []
self.mutatedata = {}
f = filehandler
lines = f.readlines()
end = len(lines)-1
counter = 0
tmp = []
chains_order = []
old_chain_id = ''
chain_break = False # a band-aid to fix crashes when TER records are missing
for line in lines:
line = self._replaceExotic(line)
#line = sub(r'^HETATM(.{10}(A| ))MSE', r'ATOM \1MET',line)
data = atm.match(line)
data_seq = seq.match(line)
data_seqc = seq_c.match(line)
if data_seqc and data_seqc.group('seqid') in keys:
self.canumber += 1
if data_seq:
seqid = data_seq.group('seqid').strip()
if seqid not in self.codification.keys():
continue
chainid = data_seq.group('chain').strip()
if chainid != old_chain_id:
if old_chain_id != '':
chain_break = True
old_chain_id = chainid
if chainid not in chains_order:
chains_order.append(chainid)
resid = data_seq.group('resid').strip()
if seqid in keys:
self.sequence += self.codification[seqid]
s = self.codification[seqid]
else:
s = "X"
self.sequence += "X"
if chainid in self.sequences.keys():
self.sequences[chainid] += s
else:
self.sequences[chainid] = s
if chainid in self.mutatedata.keys():
self.mutatedata[chainid].append({'chain': chainid,
'resname': s,
'residx': resid})
else:
self.mutatedata[chainid] = [{'chain': chainid,
'resname': s,
'residx': resid}]
if chainid in self.sequences.keys():
self.sequences[chainid] += s
else:
self.sequences[chainid] = s
if data:
seqid = data.group('seqid').strip()
if seqid not in self.codification.keys():
continue
self.allnumber += 1
self.onlycalfa += line
dg = data.groups()
if dg[0].strip() == 'CA':
try:
tmp.append(int(data.group('resid')))
except ValueError:
raise ValueError("Wrong residue index number. "
"We do not support negative residue indexes which is the most likely cause for this error."
" Offending line : %s" % line)
if (ter.match(line) or counter == end) or chain_break:
self.resindexes.append(tmp)
tmp = []
chain_break = False
#self.onlycalfa += line # skip TER in output
if (mod.match(line) and len(self.onlycalfa) > 1) or counter == end:
break
counter += 1
filehandler.seek(0)
# chain numbering
o = {}
for i in range(len(chains_order)):
o[chains_order[i]] = self.resindexes[i]
self.numb = o
def _replaceExotic(self, line):
if line.startswith("HETATM") and len(line)>21:
res = line[17:20]
if res in self.nonstandard:
sf = r'^HETATM(.{10}(A| ))'+res
st = r'ATOM \1'+self.modres[res]
line = sub(sf, st, line)
return line
def isSingleChain(self):
if self.chain != '' or len(self.sequences.keys()) == 1:
return True
else:
return False
def containsOnlyCA(self):
if self.allnumber == self.canumber:
return True
else:
return False
def getMissing(self):
return self.isBroken()+len(self.sequences.keys())
def isBroken(self):
brk = []
for j in self.numb.keys():
indexes = self.numb[j]
if len(indexes) == 0: # empty chains
continue
first = indexes[0]
for i in range(1, len(indexes)):
if indexes[i] - 1 != first:
brk.append(str(first) + "-" + str(indexes[i]))
first = indexes[i]
return len(brk)
def getResIndexes(self):
return ",".join([str(i) for i in self.numb[self.chain]])
def getChains(self):
return self.sequences.keys()
def getBody(self):
t = []
# remove alt indices from pdb
for line in self.onlycalfa.split("\n"):
t.append(line[:16]+" "+line[17:])
return "\n".join(t)
def savePdbFile(self, outfilename):
with gzip.open(outfilename, "wb") as fw:
fw.write(self.getBody())
def containsChain(self, chain):
if chain in self.sequences.keys():
return True
def get_num_chains(self):
return len(self.sequences.keys())
def getSequence(self):
if self.chain != '':
o = ""
for e in list(self.chain):
if e in self.sequences.keys():
o += self.sequences[e]
return o
else:
out = ''
for k in self.sequences.keys():
out += "".join(self.sequences[k])
return out
def getChainIdxResname(self):
if self.chain == '':
return json.dumps(self.mutatedata)
else:
return json.dumps({self.chain: self.mutatedata[self.chain]})
def getChainLengths(self):
out = []
if self.chain != '':
for e in list(self.chain):
if self.containsChain(e): # This should be a given but not sure right now
out.append(len(self.sequences[e]))
else:
for k in self.sequences.keys():
out.append(len(self.sequences[k]))
return out
modres={
'0CS':'ALA', ## 0CS ALA 3-[(S)-HYDROPEROXYSULFINYL]-L-ALANINE
'1AB':'PRO', ## 1AB PRO 1,4-DIDEOXY-1,4-IMINO-D-ARABINITOL
'1LU':'LEU', ## 1LU LEU 4-METHYL-PENTANOIC ACID-2-OXYL GROUP
'1PA':'PHE', ## 1PA PHE PHENYLMETHYLACETIC ACID ALANINE
'1TQ':'TRP', ## 1TQ TRP 6-(FORMYLAMINO)-7-HYDROXY-L-TRYPTOPHAN
'1TY':'TYR', ## 1TY TYR
'23F':'PHE', ## 23F PHE (2Z)-2-AMINO-3-PHENYLACRYLIC ACID
'23S':'TRP', ## 23S TRP MODIFIED TRYPTOPHAN
'2BU':'ALA', ## 2BU ADE
'2ML':'LEU', ## 2ML LEU 2-METHYLLEUCINE
'2MR':'ARG', ## 2MR ARG N3, N4-DIMETHYLARGININE
'2MT':'PRO', ## 2MT PRO
'2OP':'ALA', ## 2OP (2S 2-HYDROXYPROPANAL
'2TY':'TYR', ## 2TY TYR
'32S':'TRP', ## 32S TRP MODIFIED TRYPTOPHAN
'32T':'TRP', ## 32T TRP MODIFIED TRYPTOPHAN
'3AH':'HIS', ## 3AH HIS
'3MD':'ASP', ## 3MD ASP 2S,3S-3-METHYLASPARTIC ACID
'3TY':'TYR', ## 3TY TYR MODIFIED TYROSINE
'4DP':'TRP', ## 4DP TRP
'4F3':'ALA', ## 4F3 ALA CYCLIZED
'4FB':'PRO', ## 4FB PRO (4S)-4-FLUORO-L-PROLINE
'4FW':'TRP', ## 4FW TRP 4-FLUOROTRYPTOPHANE
'4HT':'TRP', ## 4HT TRP 4-HYDROXYTRYPTOPHAN
'4IN':'TRP', ## 4IN TRP 4-AMINO-L-TRYPTOPHAN
'4PH':'PHE', ## 4PH PHE 4-METHYL-L-PHENYLALANINE
'5CS':'CYS', ## 5CS CYS
'6CL':'LYS', ## 6CL LYS 6-CARBOXYLYSINE
'6CW':'TRP', ## 6CW TRP 6-CHLORO-L-TRYPTOPHAN
'A0A':'ASP', ## A0A ASP ASPARTYL-FORMYL MIXED ANHYDRIDE
'AA4':'ALA', ## AA4 ALA 2-AMINO-5-HYDROXYPENTANOIC ACID
'AAR':'ARG', ## AAR ARG ARGININEAMIDE
'AB7':'GLU', ## AB7 GLU ALPHA-AMINOBUTYRIC ACID
'ABA':'ALA', ## ABA ALA ALPHA-AMINOBUTYRIC ACID
'ACB':'ASP', ## ACB ASP 3-METHYL-ASPARTIC ACID
'ACL':'ARG', ## ACL ARG DEOXY-CHLOROMETHYL-ARGININE
'ACY':'GLY', ## ACY GLY POST-TRANSLATIONAL MODIFICATION
'AEI':'THR', ## AEI THR ACYLATED THR
'AFA':'ASN', ## AFA ASN N-[7-METHYL-OCT-2,4-DIENOYL]ASPARAGINE
'AGM':'ARG', ## AGM ARG 4-METHYL-ARGININE
'AGT':'CYS', ## AGT CYS AGMATINE-CYSTEINE ADDUCT
'AHB':'ASN', ## AHB ASN BETA-HYDROXYASPARAGINE
'AHO':'ALA', ## AHO ALA N-ACETYL-N-HYDROXY-L-ORNITHINE
'AHP':'ALA', ## AHP ALA 2-AMINO-HEPTANOIC ACID
'AIB':'ALA', ## AIB ALA ALPHA-AMINOISOBUTYRIC ACID
'AKL':'ASP', ## AKL ASP 3-AMINO-5-CHLORO-4-OXOPENTANOIC ACID
'ALA':'ALA', ## ALA ALA
'ALC':'ALA', ## ALC ALA 2-AMINO-3-CYCLOHEXYL-PROPIONIC ACID
'ALG':'ARG', ## ALG ARG GUANIDINOBUTYRYL GROUP
'ALM':'ALA', ## ALM ALA 1-METHYL-ALANINAL
'ALN':'ALA', ## ALN ALA NAPHTHALEN-2-YL-3-ALANINE
'ALO':'THR', ## ALO THR ALLO-THREONINE
'ALS':'ALA', ## ALS ALA 2-AMINO-3-OXO-4-SULFO-BUTYRIC ACID
'ALT':'ALA', ## ALT ALA THIOALANINE
'ALY':'LYS', ## ALY LYS N(6)-ACETYLLYSINE
'AME':'MET', ## AME MET ACETYLATED METHIONINE
'AP7':'ALA', ## AP7 ADE
'APH':'ALA', ## APH ALA P-AMIDINOPHENYL-3-ALANINE
'API':'LYS', ## API LYS 2,6-DIAMINOPIMELIC ACID
'APK':'LYS', ## APK LYS
'AR2':'ARG', ## AR2 ARG ARGINYL-BENZOTHIAZOLE-6-CARBOXYLIC ACID
'AR4':'GLU', ## AR4 GLU
'ARG':'ARG', ## ARG ARG
'ARM':'ARG', ## ARM ARG DEOXY-METHYL-ARGININE
'ARO':'ARG', ## ARO ARG C-GAMMA-HYDROXY ARGININE
'ASA':'ASP', ## ASA ASP ASPARTIC ALDEHYDE
'ASB':'ASP', ## ASB ASP ASPARTIC ACID-4-CARBOXYETHYL ESTER
'ASI':'ASP', ## ASI ASP L-ISO-ASPARTATE
'ASK':'ASP', ## ASK ASP DEHYDROXYMETHYLASPARTIC ACID
'ASL':'ASP', ## ASL ASP ASPARTIC ACID-4-CARBOXYETHYL ESTER
'ASN':'ASN', ## ASN ASN
'ASP':'ASP', ## ASP ASP
'AYA':'ALA', ## AYA ALA N-ACETYLALANINE
'AYG':'ALA', ## AYG ALA
'AZK':'LYS', ## AZK LYS (2S)-2-AMINO-6-TRIAZANYLHEXAN-1-OL
'B2A':'ALA', ## B2A ALA ALANINE BORONIC ACID
'B2F':'PHE', ## B2F PHE PHENYLALANINE BORONIC ACID
'B2I':'ILE', ## B2I ILE ISOLEUCINE BORONIC ACID
'B2V':'VAL', ## B2V VAL VALINE BORONIC ACID
'B3A':'ALA', ## B3A ALA (3S)-3-AMINOBUTANOIC ACID
'B3D':'ASP', ## B3D ASP 3-AMINOPENTANEDIOIC ACID
'B3E':'GLU', ## B3E GLU (3S)-3-AMINOHEXANEDIOIC ACID
'B3K':'LYS', ## B3K LYS (3S)-3,7-DIAMINOHEPTANOIC ACID
'B3S':'SER', ## B3S SER (3R)-3-AMINO-4-HYDROXYBUTANOIC ACID
'B3X':'ASN', ## B3X ASN (3S)-3,5-DIAMINO-5-OXOPENTANOIC ACID
'B3Y':'TYR', ## B3Y TYR
'BAL':'ALA', ## BAL ALA BETA-ALANINE
'BBC':'CYS', ## BBC CYS
'BCS':'CYS', ## BCS CYS BENZYLCYSTEINE
'BCX':'CYS', ## BCX CYS BETA-3-CYSTEINE
'BFD':'ASP', ## BFD ASP ASPARTATE BERYLLIUM FLUORIDE
'BG1':'SER', ## BG1 SER
'BHD':'ASP', ## BHD ASP BETA-HYDROXYASPARTIC ACID
'BIF':'PHE', ## BIF PHE
'BLE':'LEU', ## BLE LEU LEUCINE BORONIC ACID
'BLY':'LYS', ## BLY LYS LYSINE BORONIC ACID
'BMT':'THR', ## BMT THR
'BNN':'ALA', ## BNN ALA ACETYL-P-AMIDINOPHENYLALANINE
'BOR':'ARG', ## BOR ARG
'BPE':'CYS', ## BPE CYS
'BTR':'TRP', ## BTR TRP 6-BROMO-TRYPTOPHAN
'BUC':'CYS', ## BUC CYS S,S-BUTYLTHIOCYSTEINE
'BUG':'LEU', ## BUG LEU TERT-LEUCYL AMINE
'C12':'ALA', ## C12 ALA
'C1X':'LYS', ## C1X LYS MODIFIED LYSINE
'C3Y':'CYS', ## C3Y CYS MODIFIED CYSTEINE
'C5C':'CYS', ## C5C CYS S-CYCLOPENTYL THIOCYSTEINE
'C6C':'CYS', ## C6C CYS S-CYCLOHEXYL THIOCYSTEINE
'C99':'ALA', ## C99 ALA
'CAB':'ALA', ## CAB ALA 4-CARBOXY-4-AMINOBUTANAL
'CAF':'CYS', ## CAF CYS S-DIMETHYLARSINOYL-CYSTEINE
'CAS':'CYS', ## CAS CYS S-(DIMETHYLARSENIC)CYSTEINE
'CCS':'CYS', ## CCS CYS CARBOXYMETHYLATED CYSTEINE
'CGU':'GLU', ## CGU GLU CARBOXYLATION OF THE CG ATOM
'CH6':'ALA', ## CH6 ALA
'CH7':'ALA', ## CH7 ALA
'CHG':'GLY', ## CHG GLY CYCLOHEXYL GLYCINE
'CHP':'GLY', ## CHP GLY 3-CHLORO-4-HYDROXYPHENYLGLYCINE
'CHS':'PHE', ## CHS PHE 4-AMINO-5-CYCLOHEXYL-3-HYDROXY-PENTANOIC AC
'CIR':'ARG', ## CIR ARG CITRULLINE
'CLB':'ALA', ## CLB ALA
'CLD':'ALA', ## CLD ALA
'CLE':'LEU', ## CLE LEU LEUCINE AMIDE
'CLG':'LYS', ## CLG LYS
'CLH':'LYS', ## CLH LYS
'CLV':'ALA', ## CLV ALA
'CME':'CYS', ## CME CYS MODIFIED CYSTEINE
'CML':'CYS', ## CML CYS
'CMT':'CYS', ## CMT CYS O-METHYLCYSTEINE
'CQR':'ALA', ## CQR ALA
'CR2':'ALA', ## CR2 ALA POST-TRANSLATIONAL MODIFICATION
'CR5':'ALA', ## CR5 ALA
'CR7':'ALA', ## CR7 ALA
'CR8':'ALA', ## CR8 ALA
'CRK':'ALA', ## CRK ALA
'CRO':'THR', ## CRO THR CYCLIZED
'CRQ':'TYR', ## CRQ TYR
'CRW':'ALA', ## CRW ALA
'CRX':'ALA', ## CRX ALA
'CS1':'CYS', ## CS1 CYS S-(2-ANILINYL-SULFANYL)-CYSTEINE
'CS3':'CYS', ## CS3 CYS
'CS4':'CYS', ## CS4 CYS
'CSA':'CYS', ## CSA CYS S-ACETONYLCYSTEIN
'CSB':'CYS', ## CSB CYS CYS BOUND TO LEAD ION
'CSD':'CYS', ## CSD CYS 3-SULFINOALANINE
'CSE':'CYS', ## CSE CYS SELENOCYSTEINE
'CSI':'ALA', ## CSI ALA
'CSO':'CYS', ## CSO CYS INE S-HYDROXYCYSTEINE
'CSR':'CYS', ## CSR CYS S-ARSONOCYSTEINE
'CSS':'CYS', ## CSS CYS 1,3-THIAZOLE-4-CARBOXYLIC ACID
'CSU':'CYS', ## CSU CYS CYSTEINE-S-SULFONIC ACID
'CSW':'CYS', ## CSW CYS CYSTEINE-S-DIOXIDE
'CSX':'CYS', ## CSX CYS OXOCYSTEINE
'CSY':'ALA', ## CSY ALA MODIFIED TYROSINE COMPLEX
'CSZ':'CYS', ## CSZ CYS S-SELANYL CYSTEINE
'CTH':'THR', ## CTH THR 4-CHLOROTHREONINE
'CWR':'ALA', ## CWR ALA
'CXM':'MET', ## CXM MET N-CARBOXYMETHIONINE
'CY0':'CYS', ## CY0 CYS MODIFIED CYSTEINE
'CY1':'CYS', ## CY1 CYS ACETAMIDOMETHYLCYSTEINE
'CY3':'CYS', ## CY3 CYS 2-AMINO-3-MERCAPTO-PROPIONAMIDE
'CY4':'CYS', ## CY4 CYS S-BUTYRYL-CYSTEIN
'CY7':'CYS', ## CY7 CYS MODIFIED CYSTEINE
'CYD':'CYS', ## CYD CYS
'CYF':'CYS', ## CYF CYS FLUORESCEIN LABELLED CYS380 (P14)
'CYG':'CYS', ## CYG CYS
'CYJ':'LYS', ## CYJ LYS MODIFIED LYSINE
'CYQ':'CYS', ## CYQ CYS
'CYR':'CYS', ## CYR CYS
'CYS':'CYS', ## CYS CYS
'CZ2':'CYS', ## CZ2 CYS S-(DIHYDROXYARSINO)CYSTEINE
'CZZ':'CYS', ## CZZ CYS THIARSAHYDROXY-CYSTEINE
'DA2':'ARG', ## DA2 ARG MODIFIED ARGININE
'DAB':'ALA', ## DAB ALA 2,4-DIAMINOBUTYRIC ACID
'DAH':'PHE', ## DAH PHE 3,4-DIHYDROXYDAHNYLALANINE
'DAL':'ALA', ## DAL ALA D-ALANINE
'DAM':'ALA', ## DAM ALA N-METHYL-ALPHA-BETA-DEHYDROALANINE
'DAR':'ARG', ## DAR ARG D-ARGININE
'DAS':'ASP', ## DAS ASP D-ASPARTIC ACID
'DBU':'ALA', ## DBU ALA (2E)-2-AMINOBUT-2-ENOIC ACID
'DBY':'TYR', ## DBY TYR 3,5 DIBROMOTYROSINE
'DBZ':'ALA', ## DBZ ALA 3-(BENZOYLAMINO)-L-ALANINE
'DCL':'LEU', ## DCL LEU 2-AMINO-4-METHYL-PENTANYL GROUP
'DCY':'CYS', ## DCY CYS D-CYSTEINE
'DDE':'HIS', ## DDE HIS
'DGL':'GLU', ## DGL GLU D-GLU
'DGN':'GLN', ## DGN GLN D-GLUTAMINE
'DHA':'ALA', ## DHA ALA 2-AMINO-ACRYLIC ACID
'DHI':'HIS', ## DHI HIS D-HISTIDINE
'DHL':'SER', ## DHL SER POST-TRANSLATIONAL MODIFICATION
'DIL':'ILE', ## DIL ILE D-ISOLEUCINE
'DIV':'VAL', ## DIV VAL D-ISOVALINE
'DLE':'LEU', ## DLE LEU D-LEUCINE
'DLS':'LYS', ## DLS LYS DI-ACETYL-LYSINE
'DLY':'LYS', ## DLY LYS D-LYSINE
'DMH':'ASN', ## DMH ASN N4,N4-DIMETHYL-ASPARAGINE
'DMK':'ASP', ## DMK ASP DIMETHYL ASPARTIC ACID
'DNE':'LEU', ## DNE LEU D-NORLEUCINE
'DNG':'LEU', ## DNG LEU N-FORMYL-D-NORLEUCINE
'DNL':'LYS', ## DNL LYS 6-AMINO-HEXANAL
'DNM':'LEU', ## DNM LEU D-N-METHYL NORLEUCINE
'DPH':'PHE', ## DPH PHE DEAMINO-METHYL-PHENYLALANINE
'DPL':'PRO', ## DPL PRO 4-OXOPROLINE
'DPN':'PHE', ## DPN PHE D-CONFIGURATION
'DPP':'ALA', ## DPP ALA DIAMMINOPROPANOIC ACID
'DPQ':'TYR', ## DPQ TYR TYROSINE DERIVATIVE
'DPR':'PRO', ## DPR PRO D-PROLINE
'DSE':'SER', ## DSE SER D-SERINE N-METHYLATED
'DSG':'ASN', ## DSG ASN D-ASPARAGINE
'DSN':'SER', ## DSN SER D-SERINE
'DTH':'THR', ## DTH THR D-THREONINE
'DTR':'TRP', ## DTR TRP D-TRYPTOPHAN
'DTY':'TYR', ## DTY TYR D-TYROSINE
'DVA':'VAL', ## DVA VAL D-VALINE
'DYG':'ALA', ## DYG ALA
'DYS':'CYS', ## DYS CYS
'EFC':'CYS', ## EFC CYS S,S-(2-FLUOROETHYL)THIOCYSTEINE
'ESB':'TYR', ## ESB TYR
'ESC':'MET', ## ESC MET 2-AMINO-4-ETHYL SULFANYL BUTYRIC ACID
'FCL':'PHE', ## FCL PHE 3-CHLORO-L-PHENYLALANINE
'FGL':'ALA', ## FGL ALA 2-AMINOPROPANEDIOIC ACID
'FGP':'SER', ## FGP SER
'FHL':'LYS', ## FHL LYS MODIFIED LYSINE
'FLE':'LEU', ## FLE LEU FUROYL-LEUCINE
'FLT':'TYR', ## FLT TYR FLUOROMALONYL TYROSINE
'FME':'MET', ## FME MET FORMYL-METHIONINE
'FOE':'CYS', ## FOE CYS
'FOG':'PHE', ## FOG PHE PHENYLALANINOYL-[1-HYDROXY]-2-PROPYLENE
'FOR':'MET', ## FOR MET
'FRF':'PHE', ## FRF PHE PHE FOLLOWED BY REDUCED PHE
'FTR':'TRP', ## FTR TRP FLUOROTRYPTOPHANE
'FTY':'TYR', ## FTY TYR DEOXY-DIFLUOROMETHELENE-PHOSPHOTYROSINE
'GHG':'GLN', ## GHG GLN GAMMA-HYDROXY-GLUTAMINE
'GHP':'GLY', ## GHP GLY 4-HYDROXYPHENYLGLYCINE
'GL3':'GLY', ## GL3 GLY POST-TRANSLATIONAL MODIFICATION
'GLH':'GLN', ## GLH GLN
'GLN':'GLN', ## GLN GLN
'GLU':'GLU', ## GLU GLU
'GLY':'GLY', ## GLY GLY
'GLZ':'GLY', ## GLZ GLY AMINO-ACETALDEHYDE
'GMA':'GLU', ## GMA GLU 1-AMIDO-GLUTAMIC ACID
'GMU':'ALA', ## GMU 5MU
'GPL':'LYS', ## GPL LYS LYSINE GUANOSINE-5'-MONOPHOSPHATE
'GT9':'CYS', ## GT9 CYS SG ALKYLATED
'GVL':'SER', ## GVL SER SERINE MODIFED WITH PHOSPHOPANTETHEINE
'GYC':'CYS', ## GYC CYS
'GYS':'GLY', ## GYS GLY
'H5M':'PRO', ## H5M PRO TRANS-3-HYDROXY-5-METHYLPROLINE
'HHK':'ALA', ## HHK ALA (2S)-2,8-DIAMINOOCTANOIC ACID
'HIA':'HIS', ## HIA HIS L-HISTIDINE AMIDE
'HIC':'HIS', ## HIC HIS 4-METHYL-HISTIDINE
'HIP':'HIS', ## HIP HIS ND1-PHOSPHONOHISTIDINE
'HIQ':'HIS', ## HIQ HIS MODIFIED HISTIDINE
'HIS':'HIS', ## HIS HIS
'HLU':'LEU', ## HLU LEU BETA-HYDROXYLEUCINE
'HMF':'ALA', ## HMF ALA 2-AMINO-4-PHENYL-BUTYRIC ACID
'HMR':'ARG', ## HMR ARG BETA-HOMOARGININE
'HPE':'PHE', ## HPE PHE HOMOPHENYLALANINE
'HPH':'PHE', ## HPH PHE PHENYLALANINOL GROUP
'HPQ':'PHE', ## HPQ PHE HOMOPHENYLALANINYLMETHANE
'HRG':'ARG', ## HRG ARG L-HOMOARGININE
'HSE':'SER', ## HSE SER L-HOMOSERINE
'HSL':'SER', ## HSL SER HOMOSERINE LACTONE
'HSO':'HIS', ## HSO HIS HISTIDINOL
'HTI':'CYS', ## HTI CYS
'HTR':'TRP', ## HTR TRP BETA-HYDROXYTRYPTOPHANE
'HY3':'PRO', ## HY3 PRO 3-HYDROXYPROLINE
'HYP':'PRO', ## HYP PRO 4-HYDROXYPROLINE
'IAM':'ALA', ## IAM ALA 4-[(ISOPROPYLAMINO)METHYL]PHENYLALANINE
'IAS':'ASP', ## IAS ASP ASPARTYL GROUP
'IGL':'ALA', ## IGL ALA ALPHA-AMINO-2-INDANACETIC ACID
'IIL':'ILE', ## IIL ILE ISO-ISOLEUCINE
'ILE':'ILE', ## ILE ILE
'ILG':'GLU', ## ILG GLU GLU LINKED TO NEXT RESIDUE VIA CG
'ILX':'ILE', ## ILX ILE 4,5-DIHYDROXYISOLEUCINE
'IML':'ILE', ## IML ILE N-METHYLATED
'IPG':'GLY', ## IPG GLY N-ISOPROPYL GLYCINE
'IT1':'LYS', ## IT1 LYS
'IYR':'TYR', ## IYR TYR 3-IODO-TYROSINE
'KCX':'LYS', ## KCX LYS CARBAMOYLATED LYSINE
'KGC':'LYS', ## KGC LYS
'KOR':'CYS', ## KOR CYS MODIFIED CYSTEINE
'KST':'LYS', ## KST LYS N~6~-(5-CARBOXY-3-THIENYL)-L-LYSINE
'KYN':'ALA', ## KYN ALA KYNURENINE
'LA2':'LYS', ## LA2 LYS
'LAL':'ALA', ## LAL ALA N,N-DIMETHYL-L-ALANINE
'LCK':'LYS', ## LCK LYS
'LCX':'LYS', ## LCX LYS CARBAMYLATED LYSINE
'LDH':'LYS', ## LDH LYS N~6~-ETHYL-L-LYSINE
'LED':'LEU', ## LED LEU POST-TRANSLATIONAL MODIFICATION
'LEF':'LEU', ## LEF LEU 2-5-FLUOROLEUCINE
'LET':'LYS', ## LET LYS ODIFIED LYSINE
'LEU':'LEU', ## LEU LEU
'LLP':'LYS', ## LLP LYS
'LLY':'LYS', ## LLY LYS NZ-(DICARBOXYMETHYL)LYSINE
'LME':'GLU', ## LME GLU (3R)-3-METHYL-L-GLUTAMIC ACID
'LNT':'LEU', ## LNT LEU
'LPD':'PRO', ## LPD PRO L-PROLINAMIDE
'LSO':'LYS', ## LSO LYS MODIFIED LYSINE
'LYM':'LYS', ## LYM LYS DEOXY-METHYL-LYSINE
'LYN':'LYS', ## LYN LYS 2,6-DIAMINO-HEXANOIC ACID AMIDE
'LYP':'LYS', ## LYP LYS N~6~-METHYL-N~6~-PROPYL-L-LYSINE
'LYR':'LYS', ## LYR LYS MODIFIED LYSINE
'LYS':'LYS', ## LYS LYS
'LYX':'LYS', ## LYX LYS N''-(2-COENZYME A)-PROPANOYL-LYSINE
'LYZ':'LYS', ## LYZ LYS 5-HYDROXYLYSINE
'M0H':'CYS', ## M0H CYS S-(HYDROXYMETHYL)-L-CYSTEINE
'M2L':'LYS', ## M2L LYS
'M3L':'LYS', ## M3L LYS N-TRIMETHYLLYSINE
'MAA':'ALA', ## MAA ALA N-METHYLALANINE
'MAI':'ARG', ## MAI ARG DEOXO-METHYLARGININE
'MBQ':'TYR', ## MBQ TYR
'MC1':'SER', ## MC1 SER METHICILLIN ACYL-SERINE
'MCL':'LYS', ## MCL LYS NZ-(1-CARBOXYETHYL)-LYSINE
'MCS':'CYS', ## MCS CYS MALONYLCYSTEINE
'MDO':'ALA', ## MDO ALA
'MEA':'PHE', ## MEA PHE N-METHYLPHENYLALANINE
'MEG':'GLU', ## MEG GLU (2S,3R)-3-METHYL-GLUTAMIC ACID
'MEN':'ASN', ## MEN ASN GAMMA METHYL ASPARAGINE
'MET':'MET', ## MET MET
'MEU':'GLY', ## MEU GLY O-METHYL-GLYCINE
'MFC':'ALA', ## MFC ALA CYCLIZED
'MGG':'ARG', ## MGG ARG MODIFIED D-ARGININE
'MGN':'GLN', ## MGN GLN 2-METHYL-GLUTAMINE
'MHL':'LEU', ## MHL LEU N-METHYLATED, HYDROXY
'MHO':'MET', ## MHO MET POST-TRANSLATIONAL MODIFICATION
'MHS':'HIS', ## MHS HIS 1-N-METHYLHISTIDINE
'MIS':'SER', ## MIS SER MODIFIED SERINE
'MLE':'LEU', ## MLE LEU N-METHYLATED
'MLL':'LEU', ## MLL LEU METHYL L-LEUCINATE
'MLY':'LYS', ## MLY LYS METHYLATED LYSINE
'MLZ':'LYS', ## MLZ LYS N-METHYL-LYSINE
'MME':'MET', ## MME MET N-METHYL METHIONINE
'MNL':'LEU', ## MNL LEU 4,N-DIMETHYLNORLEUCINE
'MNV':'VAL', ## MNV VAL N-METHYL-C-AMINO VALINE
'MPQ':'GLY', ## MPQ GLY N-METHYL-ALPHA-PHENYL-GLYCINE
'MSA':'GLY', ## MSA GLY (2-S-METHYL) SARCOSINE
'MSE':'MET', ## MSE MET ELENOMETHIONINE
'MSO':'MET', ## MSO MET METHIONINE SULFOXIDE
'MTY':'PHE', ## MTY PHE 3-HYDROXYPHENYLALANINE
'MVA':'VAL', ## MVA VAL N-METHYLATED
'N10':'SER', ## N10 SER O-[(HEXYLAMINO)CARBONYL]-L-SERINE
'NAL':'ALA', ## NAL ALA BETA-(2-NAPHTHYL)-ALANINE
'NAM':'ALA', ## NAM ALA NAM NAPTHYLAMINOALANINE
'NBQ':'TYR', ## NBQ TYR
'NC1':'SER', ## NC1 SER NITROCEFIN ACYL-SERINE
'NCB':'ALA', ## NCB ALA CHEMICAL MODIFICATION
'NEP':'HIS', ## NEP HIS N1-PHOSPHONOHISTIDINE
'NFA':'PHE', ## NFA PHE MODIFIED PHENYLALANINE
'NIY':'TYR', ## NIY TYR META-NITRO-TYROSINE
'NLE':'LEU', ## NLE LEU NORLEUCINE
'NLN':'LEU', ## NLN LEU NORLEUCINE AMIDE
'NLO':'LEU', ## NLO LEU O-METHYL-L-NORLEUCINE
'NMC':'GLY', ## NMC GLY N-CYCLOPROPYLMETHYL GLYCINE
'NMM':'ARG', ## NMM ARG MODIFIED ARGININE
'NPH':'CYS', ## NPH CYS
'NRQ':'ALA', ## NRQ ALA
'NVA':'VAL', ## NVA VAL NORVALINE
'NYC':'ALA', ## NYC ALA
'NYS':'CYS', ## NYS CYS
'NZH':'HIS', ## NZH HIS
'OAS':'SER', ## OAS SER O-ACETYLSERINE
'OBS':'LYS', ## OBS LYS MODIFIED LYSINE
'OCS':'CYS', ## OCS CYS CYSTEINE SULFONIC ACID
'OCY':'CYS', ## OCY CYS HYDROXYETHYLCYSTEINE
'OHI':'HIS', ## OHI HIS 3-(2-OXO-2H-IMIDAZOL-4-YL)-L-ALANINE
'OHS':'ASP', ## OHS ASP O-(CARBOXYSULFANYL)-4-OXO-L-HOMOSERINE
'OLT':'THR', ## OLT THR O-METHYL-L-THREONINE
'OMT':'MET', ## OMT MET METHIONINE SULFONE
'OPR':'ARG', ## OPR ARG C-(3-OXOPROPYL)ARGININE
'ORN':'ALA', ## ORN ALA ORNITHINE
'ORQ':'ARG', ## ORQ ARG N~5~-ACETYL-L-ORNITHINE
'OSE':'SER', ## OSE SER O-SULFO-L-SERINE
'OTY':'TYR', ## OTY TYR
'OXX':'ASP', ## OXX ASP OXALYL-ASPARTYL ANHYDRIDE
'P1L':'CYS', ## P1L CYS S-PALMITOYL CYSTEINE
'P2Y':'PRO', ## P2Y PRO (2S)-PYRROLIDIN-2-YLMETHYLAMINE
'PAQ':'TYR', ## PAQ TYR SEE REMARK 999
'PAT':'TRP', ## PAT TRP ALPHA-PHOSPHONO-TRYPTOPHAN
'PBB':'CYS', ## PBB CYS S-(4-BROMOBENZYL)CYSTEINE
'PBF':'PHE', ## PBF PHE PARA-(BENZOYL)-PHENYLALANINE
'PCA':'PRO', ## PCA PRO 5-OXOPROLINE
'PCS':'PHE', ## PCS PHE PHENYLALANYLMETHYLCHLORIDE
'PEC':'CYS', ## PEC CYS S,S-PENTYLTHIOCYSTEINE
'PF5':'PHE', ## PF5 PHE 2,3,4,5,6-PENTAFLUORO-L-PHENYLALANINE
'PFF':'PHE', ## PFF PHE 4-FLUORO-L-PHENYLALANINE
'PG1':'SER', ## PG1 SER BENZYLPENICILLOYL-ACYLATED SERINE
'PG9':'GLY', ## PG9 GLY D-PHENYLGLYCINE
'PHA':'PHE', ## PHA PHE PHENYLALANINAL
'PHD':'ASP', ## PHD ASP 2-AMINO-4-OXO-4-PHOSPHONOOXY-BUTYRIC ACID
'PHE':'PHE', ## PHE PHE
'PHI':'PHE', ## PHI PHE IODO-PHENYLALANINE
'PHL':'PHE', ## PHL PHE L-PHENYLALANINOL
'PHM':'PHE', ## PHM PHE PHENYLALANYLMETHANE
'PIA':'ALA', ## PIA ALA FUSION OF ALA 65, TYR 66, GLY 67
'PLE':'LEU', ## PLE LEU LEUCINE PHOSPHINIC ACID
'PM3':'PHE', ## PM3 PHE
'POM':'PRO', ## POM PRO CIS-5-METHYL-4-OXOPROLINE
'PPH':'LEU', ## PPH LEU PHENYLALANINE PHOSPHINIC ACID
'PPN':'PHE', ## PPN PHE THE LIGAND IS A PARA-NITRO-PHENYLALANINE
'PR3':'CYS', ## PR3 CYS INE DTT-CYSTEINE
'PRO':'PRO', ## PRO PRO
'PRQ':'PHE', ## PRQ PHE PHENYLALANINE
'PRR':'ALA', ## PRR ALA 3-(METHYL-PYRIDINIUM)ALANINE
'PRS':'PRO', ## PRS PRO THIOPROLINE
'PSA':'PHE', ## PSA PHE
'PSH':'HIS', ## PSH HIS 1-THIOPHOSPHONO-L-HISTIDINE
'PTH':'TYR', ## PTH TYR METHYLENE-HYDROXY-PHOSPHOTYROSINE
'PTM':'TYR', ## PTM TYR ALPHA-METHYL-O-PHOSPHOTYROSINE
'PTR':'TYR', ## PTR TYR O-PHOSPHOTYROSINE
'PYA':'ALA', ## PYA ALA 3-(1,10-PHENANTHROL-2-YL)-L-ALANINE
'PYC':'ALA', ## PYC ALA PYRROLE-2-CARBOXYLATE
'PYR':'SER', ## PYR SER CHEMICALLY MODIFIED
'PYT':'ALA', ## PYT ALA MODIFIED ALANINE
'PYX':'CYS', ## PYX CYS S-[S-THIOPYRIDOXAMINYL]CYSTEINE
'R1A':'CYS', ## R1A CYS
'R1B':'CYS', ## R1B CYS
'R1F':'CYS', ## R1F CYS
'R7A':'CYS', ## R7A CYS
'RC7':'ALA', ## RC7 ALA
'RCY':'CYS', ## RCY CYS
'S1H':'SER', ## S1H SER 1-HEXADECANOSULFONYL-O-L-SERINE
'SAC':'SER', ## SAC SER N-ACETYL-SERINE
'SAH':'CYS', ## SAH CYS S-ADENOSYL-L-HOMOCYSTEINE
'SAR':'GLY', ## SAR GLY SARCOSINE
'SBD':'SER', ## SBD SER
'SBG':'SER', ## SBG SER MODIFIED SERINE
'SBL':'SER', ## SBL SER
'SC2':'CYS', ## SC2 CYS N-ACETYL-L-CYSTEINE
'SCH':'CYS', ## SCH CYS S-METHYL THIOCYSTEINE GROUP
'SCS':'CYS', ## SCS CYS MODIFIED CYSTEINE
'SCY':'CYS', ## SCY CYS CETYLATED CYSTEINE
'SDP':'SER', ## SDP SER
'SEB':'SER', ## SEB SER O-BENZYLSULFONYL-SERINE
'SEC':'ALA', ## SEC ALA 2-AMINO-3-SELENINO-PROPIONIC ACID
'SEL':'SER', ## SEL SER 2-AMINO-1,3-PROPANEDIOL
'SEP':'SER', ## SEP SER E PHOSPHOSERINE
'SER':'SER', ## SER SER
'SET':'SER', ## SET SER AMINOSERINE
'SGB':'SER', ## SGB SER MODIFIED SERINE
'SGR':'SER', ## SGR SER MODIFIED SERINE
'SHC':'CYS', ## SHC CYS S-HEXYLCYSTEINE
'SHP':'GLY', ## SHP GLY (4-HYDROXYMALTOSEPHENYL)GLYCINE
'SIC':'ALA', ## SIC ALA
'SLZ':'LYS', ## SLZ LYS L-THIALYSINE
'SMC':'CYS', ## SMC CYS POST-TRANSLATIONAL MODIFICATION
'SME':'MET', ## SME MET METHIONINE SULFOXIDE
'SMF':'PHE', ## SMF PHE 4-SULFOMETHYL-L-PHENYLALANINE
'SNC':'CYS', ## SNC CYS S-NITROSO CYSTEINE
'SNN':'ASP', ## SNN ASP POST-TRANSLATIONAL MODIFICATION
'SOC':'CYS', ## SOC CYS DIOXYSELENOCYSTEINE
'SOY':'SER', ## SOY SER OXACILLOYL-ACYLATED SERINE
'SUI':'ALA', ## SUI ALA
'SUN':'SER', ## SUN SER TABUN CONJUGATED SERINE
'SVA':'SER', ## SVA SER SERINE VANADATE
'SVV':'SER', ## SVV SER MODIFIED SERINE
'SVX':'SER', ## SVX SER MODIFIED SERINE
'SVY':'SER', ## SVY SER MODIFIED SERINE
'SVZ':'SER', ## SVZ SER MODIFIED SERINE
'SXE':'SER', ## SXE SER MODIFIED SERINE
'TBG':'GLY', ## TBG GLY T-BUTYL GLYCINE
'TBM':'THR', ## TBM THR
'TCQ':'TYR', ## TCQ TYR MODIFIED TYROSINE
'TEE':'CYS', ## TEE CYS POST-TRANSLATIONAL MODIFICATION
'TH5':'THR', ## TH5 THR O-ACETYL-L-THREONINE
'THC':'THR', ## THC THR N-METHYLCARBONYLTHREONINE
'THR':'THR', ## THR THR
'TIH':'ALA', ## TIH ALA BETA(2-THIENYL)ALANINE
'TMD':'THR', ## TMD THR N-METHYLATED, EPSILON C ALKYLATED
'TNB':'CYS', ## TNB CYS S-(2,3,6-TRINITROPHENYL)CYSTEINE
'TOX':'TRP', ## TOX TRP
'TPL':'TRP', ## TPL TRP TRYTOPHANOL
'TPO':'THR', ## TPO THR HOSPHOTHREONINE
'TPQ':'ALA', ## TPQ ALA 2,4,5-TRIHYDROXYPHENYLALANINE
'TQQ':'TRP', ## TQQ TRP
'TRF':'TRP', ## TRF TRP N1-FORMYL-TRYPTOPHAN
'TRN':'TRP', ## TRN TRP AZA-TRYPTOPHAN
'TRO':'TRP', ## TRO TRP 2-HYDROXY-TRYPTOPHAN
'TRP':'TRP', ## TRP TRP
'TRQ':'TRP', ## TRQ TRP
'TRW':'TRP', ## TRW TRP
'TRX':'TRP', ## TRX TRP 6-HYDROXYTRYPTOPHAN
'TTQ':'TRP', ## TTQ TRP 6-AMINO-7-HYDROXY-L-TRYPTOPHAN
'TTS':'TYR', ## TTS TYR
'TY2':'TYR', ## TY2 TYR 3-AMINO-L-TYROSINE
'TY3':'TYR', ## TY3 TYR 3-HYDROXY-L-TYROSINE
'TYB':'TYR', ## TYB TYR TYROSINAL
'TYC':'TYR', ## TYC TYR L-TYROSINAMIDE
'TYI':'TYR', ## TYI TYR 3,5-DIIODOTYROSINE
'TYN':'TYR', ## TYN TYR ADDUCT AT HYDROXY GROUP
'TYO':'TYR', ## TYO TYR
'TYQ':'TYR', ## TYQ TYR AMINOQUINOL FORM OF TOPA QUINONONE
'TYR':'TYR', ## TYR TYR
'TYS':'TYR', ## TYS TYR INE SULPHONATED TYROSINE
'TYT':'TYR', ## TYT TYR
'TYX':'CYS', ## TYX CYS S-(2-ANILINO-2-OXOETHYL)-L-CYSTEINE
'TYY':'TYR', ## TYY TYR IMINOQUINONE FORM OF TOPA QUINONONE
'TYZ':'ARG', ## TYZ ARG PARA ACETAMIDO BENZOIC ACID
'UMA':'ALA', ## UMA ALA
'VAD':'VAL', ## VAD VAL DEAMINOHYDROXYVALINE
'VAF':'VAL', ## VAF VAL METHYLVALINE
'VAL':'VAL', ## VAL VAL
'VDL':'VAL', ## VDL VAL (2R,3R)-2,3-DIAMINOBUTANOIC ACID
'VLL':'VAL', ## VLL VAL (2S)-2,3-DIAMINOBUTANOIC ACID
'HSD':'HIS', ## up his
'VME':'VAL', ## VME VAL O- METHYLVALINE
'X9Q':'ALA', ## X9Q ALA
'XX1':'LYS', ## XX1 LYS N~6~-7H-PURIN-6-YL-L-LYSINE
'XXY':'ALA', ## XXY ALA
'XYG':'ALA', ## XYG ALA
'YCM':'CYS', ## YCM CYS S-(2-AMINO-2-OXOETHYL)-L-CYSTEINE
'YOF':'TYR' } ## YOF TYR 3-FLUOROTYROSINE
nonstandard = modres.keys() | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/parsePDB.py | parsePDB.py |
from a3d_gui import app
from flask import render_template, g, request, Response, send_from_directory, abort, jsonify, url_for
import os
from utils import query_db
from db_manager import get_filepath
from server_plot import create_plot, create_mut_plot
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
@app.errorhandler(404)
def page_not_found(error):
app.logger.warning('Page not found (IP: '+request.remote_addr+') '+request.url)
return render_template('page_not_found.html', code="404"), 404
@app.errorhandler(500)
def page_error(error):
app.logger.warning('Page not found (IP: '+request.remote_addr+') '+request.url)
return render_template('page_not_found.html', code="500"), 500
# This function fixes a mismatch between new csv format and interactive js plotting
# Its here becouse I dont want to mess with js
@app.route('/compute_static/<jobid>/a3d.csv')
def compute_static_a3dtable(jobid):
o = ""
with open(get_filepath(jobid, "A3D.csv")) as fw:
for line in fw:
line = line.replace("chain", "ch")
line = line.replace("residue_name", "resn")
line = line.replace("residue", "resi")
o += line.replace("protein,", "").replace("folded,", "")
return Response(o, status=200, mimetype='text/csv')
@app.route('/compute_static/<jobid>/<folder>/<filename>')
def ustatic_folder(jobid, folder, filename):
data_dir = query_db("SELECT working_dir FROM user_queue WHERE \
jid=?", [jobid], one=True)[0]
d = os.path.abspath(os.path.join(data_dir, folder))
s = os.path.join(d, filename)
if os.path.exists(s):
return send_from_directory(d, filename)
else:
abort(404)
@app.route('/compute_static/<jobid>/<filename>')
def ustatic(jobid, filename):
data_dir = query_db("SELECT working_dir FROM user_queue WHERE \
jid=?", [jobid], one=True)[0]
s = os.path.join(data_dir, filename)
if os.path.exists(s):
return send_from_directory(data_dir, filename)
else:
abort(404)
@app.route('/save_picture/<jobid>', methods=['POST'])
def save_uri(jobid):
try:
picture = request.json['file_content'].split(',')[1]
filename = request.json['filename']
pic_type = request.json['type']
model = request.json['model']
while os.path.isfile(os.path.join(app.config['PICTURES'], filename)):
# TODO this will be bad if more dots, fix maybe
filename = filename.split(".")[0] + "_1" + "." + filename.split(".")[-1] # Prevent overwriting
try:
with open(os.path.join(app.root_path, 'pictures', filename), 'wb') as f:
f.write(picture.decode('base64'))
except IOError:
os.makedirs(os.path.join(app.root_path, 'pictures'))
with open(os.path.join(app.root_path, 'pictures', filename), 'wb') as f:
f.write(picture.decode('base64'))
query_db("INSERT INTO pictures (jid, filename, type, model) \
VALUES(?,?,?,?)",
[jobid, filename, pic_type, model], insert=True)
return Response("%s : %s" % (url_for("serve_pic", filename=filename), filename),
status=200, mimetype='text/csv')
except Exception as e:
return Response("Something went wrong! Python error: %s" % str(e), status=400, mimetype='text/csv')
@app.route('/serve_picture/<filename>', methods=['GET'])
def serve_pic(filename):
path = os.path.join(app.root_path, 'pictures', filename)
if os.path.exists(path):
return send_from_directory(os.path.join(app.root_path, 'pictures'), filename)
else:
return Response("Requested file %s does not exist in pictures folder" % filename,
status=400, mimetype="text/plain")
@app.route('/delete_picture', methods=['POST'])
def delete_pic():
filename = request.json['filename']
path = os.path.join(app.root_path, 'pictures', filename)
if os.path.exists(path):
try:
os.remove(path)
query_db("DELETE FROM pictures WHERE filename=? ", [filename], insert=True)
return Response("Success!", status=200, mimetype="text/plain")
except OSError:
return Response("Failed to delete the file. Perhaps you don't have necessary permissions?" % filename,
status=400, mimetype="text/plain")
else:
return Response("Requested file %s does not exist in pictures folder" % filename,
status=400, mimetype="text/plain")
@app.route('/get_pictures_links/<jobid>', methods=['GET'])
def get_pics(jobid):
query = query_db("SELECT * FROM pictures WHERE jid=?", [jobid])
if query is None:
return jsonify([])
results = []
for row in query:
results.append({'path': url_for("serve_pic", filename=row['filename']),
'model': row['model'], 'type': row['type'], 'filename': row['filename']})
return jsonify(results)
@app.route('/get_plot/<jobid>', methods=['POST'])
def get_plot(jobid):
model = request.json['model']
data_dir = query_db("SELECT working_dir FROM user_queue WHERE \
jid=?", [jobid], one=True)[0]
filepath = os.path.join(data_dir, model + ".csv")
script, div = create_plot(filepath, model)
results = {'script': script, 'div': div}
return jsonify(results)
@app.route('/get_mut_plot/<jobid>', methods=['POST'])
def get_mut_plot(jobid):
data_dir = query_db("SELECT working_dir FROM user_queue WHERE \
jid=?", [jobid], one=True)[0]
try:
script, div = create_mut_plot(data_dir)
results = {'script': script, 'div': div}
return jsonify(results)
except IOError: # The plot is requested from a project that misses files
return Response("No plots were generated as the Mutations.csv file is missing",
status=400, mimetype="text/plain")
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static', 'img'),
'favicon.png', mimetype='image/png')
@app.route('/contact')
def index_contact():
return render_template('contact.html')
@app.route('/learn_more')
def learn_more():
return render_template('_learn_more.html')
@app.route('/tutorial_txt')
def tutorial_txt():
return render_template('tutorial_text.html')
@app.route('/tutorial')
def tutorial():
return render_template('_tutorial.html') | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/viewsutils.py | viewsutils.py |
import sqlite3
import os
from wtforms.validators import ValidationError
from flask import Response, request, flash, redirect, url_for
from a3d_gui import app
from utils import query_db, unique_id
from job_handling import delete_files, check_jobs
from create_config import reverse_config
from os.path import join, abspath, isfile
from parsePDB import PdbParser
"""
Module intended for simple database operations for the Aggrescan3D standalone app
CAUTION! Some of the functions here perform file deletion as well as process killing
Should you chose to modify basic settings or job handling and db managing functions do so with care
"""
def create_new_database(new_database):
"""Create an empty database that follows this apps schema"""
try:
conn = sqlite3.connect(new_database)
c = conn.cursor()
c.execute('''CREATE TABLE user_queue (id INTEGER PRIMARY KEY, jid TEXT,
status TEXT DEFAULT 'pending', project_name TEXT, working_dir TEXT,
started DATETIME DEFAULT CURRENT_TIMESTAMP, pid INTEGER)''')
c.execute('''CREATE TABLE project_details (jid TEXT, chains TEXT,
chain_sequence TEXT, chain_numbering TEXT, dynamic INTEGER, mutate INTEGER,
distance INTEGER, mutation TEXT, foldx INTEGER, mutt_energy_diff REAL,
auto_mutation TEXT)''')
c.execute('''CREATE TABLE pictures (jid TEXT, filename TEXT, type TEXT, model TEXT)''')
c.execute('''CREATE TABLE system_data (id INTEGER PRIMARY KEY, foldx_path TEXT)''')
foldx_loc = raw_input("Please provide a location for your FoldX installation if you have one "
"(or just press Enter this can be done later on)\n")
conn.commit()
# If the db didn't exist maybe the user wants to input the foldx location?
try:
if os.path.isdir(foldx_loc):
if os.path.isfile(os.path.join(foldx_loc, 'rotabase.txt')):
c.execute("INSERT INTO system_data(foldx_path) VALUES(?)", [foldx_loc])
else:
c.execute("INSERT INTO system_data(foldx_path) VALUES(?)", ["Not specified"])
print "%s Is not a valid FoldX directory (missing rotabase.txt file). " \
"Use the gui to specify a valid location" % foldx_loc
else:
c.execute("INSERT INTO system_data(foldx_path) VALUES(?)", ["/home/FoldX"]) # Default value for Docker Image usage
print "%s is not a directory. If you wish to use foldX in the " \
"gui specify a valid address when starting the job" % foldx_loc
except EOFError:
c.execute("INSERT INTO system_data(foldx_path) VALUES(?)",
["/home/FoldX"]) # Default value for Docker Image usage
finally:
conn.commit()
conn.close()
except sqlite3.Error as e:
raise ValidationError("An error occurred while trying to create a database: %s" % e)
finally:
conn.close()
@app.route('/_delete_job/<jid>', methods=['GET'])
def delete_job(jid):
"""Delete a job from current database"""
try:
query_db("DELETE FROM user_queue WHERE jid=?", [jid], insert=True)
query_db("DELETE FROM project_details WHERE jid=?", [jid], insert=True)
query_db("DELETE FROM pictures WHERE jid=?", [jid], insert=True)
flash("Job %s deleted." % jid, "info")
return url_for('index_page')
except sqlite3.Error as e:
return Response("The database couldn't process this request. Error: %s" % str(e),
status=400, content_type="text/plain")
@app.route('/_hard_delete_job/<jid>', methods=['GET'])
def hard_delete_job(jid):
"""Delete a job from current database as well as the files from the computer"""
try:
folder_gone = delete_files(jid)
query_db("DELETE FROM user_queue WHERE jid=?", [jid], insert=True)
query_db("DELETE FROM project_details WHERE jid=?", [jid], insert=True)
query_db("DELETE FROM pictures WHERE jid=?", [jid], insert=True)
if folder_gone:
flash("Job %s deleted. All files and the working directory were deleted." % jid, "info")
else:
flash("Job %s deleted. Aggrescan files were most likely deleted"
" but the directory still contains files." % jid, "info")
return url_for('index_page')
except sqlite3.Error as e:
return Response("The database couldn't process this request. Error: %s" % str(e),
status=400, content_type="text/plain")
@app.route('/_add_job/', methods=['POST'])
def add_job_to_db():
"""Using a config file add a job to active database"""
config_file = request.files['file']
for line in config_file.stream.readlines():
if "work_dir :" in line:
project_work_dir = line.split(":")[1].strip()
try:
options, mutation = reverse_config(join(project_work_dir, "config.ini")) # relies on A3D automatic saving of parsed config
except UnboundLocalError:
return Response("This file doesn't contain a working dir field which is necessary. "
"Please select a valid config.ini file.",
status=400, content_type="text/plain")
jid = unique_id()
if not isfile(join(project_work_dir, "input.pdb")) and not isfile(join(project_work_dir, "tmp", "input.pdb")):
return Response("This project has probably just started and some important files (input.pdb) "
"are not yet created. Or have been deleted since. If its the former try again in a second.",
status=400, content_type="text/plain")
project_name = request.form['text'] or "Custom project"
mutate = 1 if mutation else 0
dynamic = 1 if options['dynamic'] else 0
foldx = 1 if options['foldx'] else 0
auto_mutation = options['auto_mutation']
query_db("INSERT INTO user_queue (jid, project_name, working_dir, pid)\
VALUES(?,?,?,?)",
[jid, project_name, project_work_dir, -100], insert=True) # -100 should never be a valid pid
query_db("INSERT INTO project_details (jid, dynamic, mutate, distance, foldx, auto_mutation) \
VALUES(?,?,?,?,?,?)",
[jid, dynamic, mutate, options['distance'], foldx, auto_mutation], insert=True)
try:
with open(get_filepath(jid, "input.pdb"), 'r') as f:
p = PdbParser(f, options['chain'])
except IOError:
with open(join(project_work_dir, "tmp", "input.pdb"), 'r') as f:
p = PdbParser(f, options['chain'])
input_seq = p.getSequence()
chain_numbering = p.getChainIdxResname()
if not options['chain']:
chains = p.getChains()
query_db("UPDATE project_details SET chains=?, chain_sequence=?, chain_numbering=? WHERE jid=?",
["".join(chains), input_seq, chain_numbering, jid], insert=True)
check_jobs(jid)
return url_for('job_status', jid=jid)
@app.route('/change_foldx_path', methods=['POST'])
def change_foldx_path():
new_path = request.form['text']
if not new_path:
return Response("Empty path provided, not taking any action.", status=400, content_type="text/plain")
if not isfile(join(new_path, "rotabase.txt")):
return Response("%s Is not a valid FoldX directory (missing rotabase.txt file)." % new_path,
status=400, content_type="text/plain")
query_db("UPDATE system_data SET foldx_path=? WHERE id=?", [new_path, 1], insert=True)
return Response(new_path, status=200, content_type="text/plain")
@app.route('/_change_status/<jid>', methods=['POST'])
def change_job_status(jid):
"""Manually update a job status in case user wishes to do so"""
new_status = request.data
try:
query_db("UPDATE user_queue SET status=? WHERE jid=?", [new_status, jid], insert=True)
return Response("Query OK. Status changed to %s" % new_status, status=200, content_type="text/plain")
except sqlite3.Error as e:
return Response("Query failed! Error: %s" % str(e), status=400, content_type="text/plain")
def get_filepath(jid, filename):
data_dir = query_db("SELECT working_dir FROM user_queue WHERE \
jid=?", [jid], one=True)[0]
return join(data_dir, filename) | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/db_manager.py | db_manager.py |
from bokeh.plotting import figure, output_file, ColumnDataSource, save, show
from bokeh.models import HoverTool, FactorRange, Legend
from bokeh.models.glyphs import Line
from bokeh.resources import INLINE
from bokeh.util.string import encode_utf8
import bokeh.palettes
from bokeh.embed import components
from os.path import join
aa_dict_F = {'A': 'alanine', 'R': 'arginine', 'N': 'asparagine',
'D': 'aspartic acid', 'C': 'cysteine', 'E': 'glutamic acid',
'Q': 'glutamine', 'G': 'glycine', 'H': 'histidine',
'I': 'isoleucine', 'L': 'leucine', 'K': 'lysine',
'M': 'methionine', 'F': 'phenylalanine', 'P': 'proline',
'S': 'serine', 'T': 'threonine', 'W': 'tryptophan',
'Y': 'tyrosine', 'V': 'valine', 'X': 'unknown'}
def create_mut_plot(data_dir, save_plot=False):
# This will read a mutant list that is already available to the calling jscript, dunno if its worth to pass it tho
mutants = [""] # The first is a fake - it will read the base simulation result and name it Base
max_mutants, counter = 12, 0 # This is also used somewhere else so maybe should unify it
p = [] # To create the figure object in a loop
with open(join(data_dir, "Mutations_summary.csv"), "r") as f:
f.readline()
for line in f:
mutants.append(line.split(",")[0])
counter += 1
if counter >= max_mutants:
break
counter = 0
colors = bokeh.palettes.Category10[10] # This is not enough colors need 13 for 12 mutants and its only 10
colors.append('#1E1717') # almost black
colors.append('#f3ff00') # strong, flashy yellow
colors.append('#ce6778') # kinda pinkish I guess
legend_items = []
for mutant in mutants:
x, y, chain, name, index, status = [], [], [], [], [], []
mutant = mutant if mutant else "A3D" # It's a band aid considering file locations and names have changed
# (Base csv is named A3D.csv)
with open(join(data_dir, mutant + ".csv"), 'r') as f:
if mutant == "A3D": # Following the weird convention to get the Base case first with the name Base
mutant = "Wild type"
f.readline() # skip the initial line with labels
for line in f:
a = line.strip().split(',')
# a goes as follows: model name, chain, index, one letter code, aggrescan score
x.append(("Chain %s" % a[1], a[2]+a[1]))
y.append(float(a[-1]))
name.append(aa_dict_F[a[-2]])
index.append(a[2])
chain.append(a[1])
status.append('Soluble' if float(a[-1]) <= 0 else 'Aggregation prone')
if not p:
p = figure(plot_width=1150, plot_height=600, tools=['box_zoom,pan,reset,save'],
title="Score breakdown for mutants. "
"Click on the legend to hide/show the line. Mouse over a point to see details.",
x_range=FactorRange(*x), toolbar_location="below")
p.xaxis.major_tick_line_color = None # turn off x-axis major ticks
p.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks
p.yaxis.minor_tick_line_color = None # turn off x-axis minor ticks
p.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels, it keeps the chain names though
p.xgrid.grid_line_color = None # turn off the grid
p.ygrid.grid_line_color = None
mut_names = [mutant for i in range(len(x))]
source = ColumnDataSource(data=dict(
x=x,
y=y,
line_y=[0 for i in range(len(x))],
name=name,
index=index,
status=status,
chain=chain,
mut_name=mut_names
))
# @ means they will get assigned in order from the data defined above, names means it will only display there
hover = HoverTool(tooltips=[
("Chain", "@chain"),
("Residue name", "@name"),
("Residue index", "@index"),
("Prediction", "@status"),
("Mutant", "@mut_name")],
mode='vline',
names=[mutant])
the_line = p.line('x', 'y', source=source, name=mutant,color=colors[counter], line_width=2.5,
line_alpha=1.0) # the main plot
legend_items.append((mutant, [the_line]))
if counter not in [0, 1]:
the_line.visible = False
p.add_tools(hover)
counter += 1
legend = Legend(items=legend_items, click_policy="hide")
p.add_layout(legend, "left")
script, div = components(p)
if save_plot: # Will not be used for now, could be used by the main program but importing this would be bad
# (Due to how the server is started, it would start it on import # TODO provide download button
save(p, filename="Automated_mutations", title="Mutation analysis")
else:
return script, div
def create_plot(csv_address, model):
x, y, chain, name, index, status = [], [], [], [], [], []
with open(csv_address, 'r') as f:
f.readline() # skip the initial line with labels
for line in f:
a = line.strip().split(',')
# a goes as follows: model name, chain, index, one letter code, aggrescan score
x.append(("Chain %s" % a[1], a[2]+a[1]))
y.append(float(a[-1]))
name.append(aa_dict_F[a[-2]])
index.append(a[2])
chain.append(a[1])
status.append('Soluble' if float(a[-1]) <= 0 else 'Aggregation prone')
source = ColumnDataSource(data=dict(
x=x,
y=y,
line_y=[0 for i in range(len(x))],
name=name,
index=index,
status=status,
chain=chain
))
# @ means they will get assigned in order from the data defined above, names means it will only display there
hover = HoverTool(tooltips=[
("Chain", "@chain"),
("Residue name", "@name"),
("Residue index", "@index"),
("Prediction", "@status")],
mode='vline',
names=["line"])
# TODO maybe get the underlying DOM in job_info and adjust the size to that, rather than keeping it static but it wouldnt be perfect either
# Creeates the plot, adds the tools, and creates the x axis with major tick names, and then chain names below
p = figure(plot_width=1150, plot_height=600, tools=[hover, 'box_zoom,pan,reset,save'],
title="Aggrescan3D score based on residue for %s. Mouse over the plot to see residue's details" % model,
x_range=FactorRange(*x), toolbar_location="below")
p.xaxis.major_tick_line_color = None # turn off x-axis major ticks
p.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks
p.yaxis.minor_tick_line_color = None # turn off x-axis minor ticks
p.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels, it keeps the chain names though
p.xgrid.grid_line_color = None # turn off the grid
p.ygrid.grid_line_color = None
p.line('x', 'y', source=source, name="line") # the main plot
glyph = Line(x="x", y="line_y", line_color="#f46d43", line_width=2, line_alpha=0.3) # small line to help find aggregation prone residues
p.add_glyph(source, glyph) # actually draw the line on the figure
script, div = components(p)
return script, div | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/server_plot.py | server_plot.py |
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.0",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.0",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active"));a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus","focus"==b.type)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.0",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c="prev"==a?-1:1,d=this.getItemIndex(b),e=(d+c)%this.$items.length;return this.$items.eq(e)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i="next"==b?"first":"last",j=this;if(!f.length){if(!this.options.wrap)return;f=this.$element.find(".item")[i]()}if(f.hasClass("active"))return this.sliding=!1;var k=f[0],l=a.Event("slide.bs.carousel",{relatedTarget:k,direction:h});if(this.$element.trigger(l),!l.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var m=a(this.$indicators.children()[this.getItemIndex(f)]);m&&m.addClass("active")}var n=a.Event("slid.bs.carousel",{relatedTarget:k,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),j.sliding=!1,setTimeout(function(){j.$element.trigger(n)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(n)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&"show"==b&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a(this.options.trigger).filter('[href="#'+b.id+'"], [data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.0",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0,trigger:'[data-toggle="collapse"]'},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.find("> .panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":a.extend({},e.data(),{trigger:this});c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=c(d),f={relatedTarget:this};e.hasClass("open")&&(e.trigger(b=a.Event("hide.bs.dropdown",f)),b.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f)))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.0",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27|32)/.test(b.which)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g&&27!=b.which||g&&27==b.which)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.divider):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(b.target);38==b.which&&j>0&&j--,40==b.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="menu"]',g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$backdrop=this.isShown=null,this.scrollbarWidth=0,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.0",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.$body.addClass("modal-open"),this.setScrollbar(),this.escape(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),e&&d.$element[0].offsetWidth,d.$element.addClass("in").attr("aria-hidden",!1),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$element.find(".modal-dialog").one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a('<div class="modal-backdrop '+e+'" />').prependTo(this.$element).on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.checkScrollbar=function(){this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.scrollbarWidth&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right","")},c.prototype.measureScrollbar=function(){if(document.body.clientWidth>=window.innerWidth)return 0;var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b,g=f&&f.selector;(e||"destroy"!=b)&&(g?(e||d.data("bs.tooltip",e={}),e[g]||(e[g]=new c(this,f))):e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.3.0",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c&&c.$tip&&c.$tip.is(":visible")?void(c.hoverState="in"):(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.options.container?a(this.options.container):this.$element.parent(),p=this.getPosition(o);h="bottom"==h&&k.bottom+m>p.bottom?"top":"top"==h&&k.top-m<p.top?"bottom":"right"==h&&k.right+l>p.width?"left":"left"==h&&k.left-l<p.left?"right":h,f.removeClass(n).addClass(h)}var q=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(q,h);var r=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",r).emulateTransitionEnd(c.TRANSITION_DURATION):r()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=this.tip(),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type)})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b,g=f&&f.selector;(e||"destroy"!=b)&&(g?(e||d.data("bs.popover",e={}),e[g]||(e[g]=new c(this,f))):e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.0",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},c.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){var e=a.proxy(this.process,this);this.$body=a("body"),this.$scrollElement=a(a(c).is("body")?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",e),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.0",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b="offset",c=0;a.isWindow(this.$scrollElement[0])||(b="position",c=this.$scrollElement.scrollTop()),this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight();var d=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+c,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){d.offsets.push(this[0]),d.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.0",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)
}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.0",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=i?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=a("body").height();"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/static/js/bootstrap.min.js | bootstrap.min.js |
if("undefined"==typeof jQuery)throw new Error("Jasny Bootstrap's JavaScript requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}void 0===a.support.transition&&(a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()}))}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.state=null,this.placement=null,this.options.recalc&&(this.calcClone(),a(window).on("resize",a.proxy(this.recalc,this))),this.options.autohide&&a(document).on("click",a.proxy(this.autohide,this)),this.options.toggle&&this.toggle(),this.options.disablescrolling&&(this.options.disableScrolling=this.options.disablescrolling,delete this.options.disablescrolling)};b.DEFAULTS={toggle:!0,placement:"auto",autohide:!0,recalc:!0,disableScrolling:!0},b.prototype.offset=function(){switch(this.placement){case"left":case"right":return this.$element.outerWidth();case"top":case"bottom":return this.$element.outerHeight()}},b.prototype.calcPlacement=function(){function b(a,b){if("auto"===e.css(b))return a;if("auto"===e.css(a))return b;var c=parseInt(e.css(a),10),d=parseInt(e.css(b),10);return c>d?b:a}if("auto"!==this.options.placement)return void(this.placement=this.options.placement);this.$element.hasClass("in")||this.$element.css("visiblity","hidden !important").addClass("in");var c=a(window).width()/this.$element.width(),d=a(window).height()/this.$element.height(),e=this.$element;this.placement=c>=d?b("left","right"):b("top","bottom"),"hidden !important"===this.$element.css("visibility")&&this.$element.removeClass("in").css("visiblity","")},b.prototype.opposite=function(a){switch(a){case"top":return"bottom";case"left":return"right";case"bottom":return"top";case"right":return"left"}},b.prototype.getCanvasElements=function(){var b=this.options.canvas?a(this.options.canvas):this.$element,c=b.find("*").filter(function(){return"fixed"===a(this).css("position")}).not(this.options.exclude);return b.add(c)},b.prototype.slide=function(b,c,d){if(!a.support.transition){var e={};return e[this.placement]="+="+c,b.animate(e,350,d)}var f=this.placement,g=this.opposite(f);b.each(function(){"auto"!==a(this).css(f)&&a(this).css(f,(parseInt(a(this).css(f),10)||0)+c),"auto"!==a(this).css(g)&&a(this).css(g,(parseInt(a(this).css(g),10)||0)-c)}),this.$element.one(a.support.transition.end,d).emulateTransitionEnd(350)},b.prototype.disableScrolling=function(){var b=a("body").width(),c="padding-"+this.opposite(this.placement);if(void 0===a("body").data("offcanvas-style")&&a("body").data("offcanvas-style",a("body").attr("style")||""),a("body").css("overflow","hidden"),a("body").width()>b){var d=parseInt(a("body").css(c),10)+a("body").width()-b;setTimeout(function(){a("body").css(c,d)},1)}},b.prototype.show=function(){if(!this.state){var b=a.Event("show.bs.offcanvas");if(this.$element.trigger(b),!b.isDefaultPrevented()){this.state="slide-in",this.calcPlacement();var c=this.getCanvasElements(),d=this.placement,e=this.opposite(d),f=this.offset();-1!==c.index(this.$element)&&(a(this.$element).data("offcanvas-style",a(this.$element).attr("style")||""),this.$element.css(d,-1*f),this.$element.css(d)),c.addClass("canvas-sliding").each(function(){void 0===a(this).data("offcanvas-style")&&a(this).data("offcanvas-style",a(this).attr("style")||""),"static"===a(this).css("position")&&a(this).css("position","relative"),"auto"!==a(this).css(d)&&"0px"!==a(this).css(d)||"auto"!==a(this).css(e)&&"0px"!==a(this).css(e)||a(this).css(d,0)}),this.options.disableScrolling&&this.disableScrolling();var g=function(){"slide-in"==this.state&&(this.state="slid",c.removeClass("canvas-sliding").addClass("canvas-slid"),this.$element.trigger("shown.bs.offcanvas"))};setTimeout(a.proxy(function(){this.$element.addClass("in"),this.slide(c,f,a.proxy(g,this))},this),1)}}},b.prototype.hide=function(){if("slid"===this.state){var b=a.Event("hide.bs.offcanvas");if(this.$element.trigger(b),!b.isDefaultPrevented()){this.state="slide-out";var c=a(".canvas-slid"),d=(this.placement,-1*this.offset()),e=function(){"slide-out"==this.state&&(this.state=null,this.placement=null,this.$element.removeClass("in"),c.removeClass("canvas-sliding"),c.add(this.$element).add("body").each(function(){a(this).attr("style",a(this).data("offcanvas-style")).removeData("offcanvas-style")}),this.$element.trigger("hidden.bs.offcanvas"))};c.removeClass("canvas-slid").addClass("canvas-sliding"),setTimeout(a.proxy(function(){this.slide(c,d,a.proxy(e,this))},this),1)}}},b.prototype.toggle=function(){"slide-in"!==this.state&&"slide-out"!==this.state&&this["slid"===this.state?"hide":"show"]()},b.prototype.calcClone=function(){this.$calcClone=this.$element.clone().html("").addClass("offcanvas-clone").removeClass("in").appendTo(a("body"))},b.prototype.recalc=function(){if("none"!==this.$calcClone.css("display")&&("slid"===this.state||"slide-in"===this.state)){this.state=null,this.placement=null;var b=this.getCanvasElements();this.$element.removeClass("in"),b.removeClass("canvas-slid"),b.add(this.$element).add("body").each(function(){a(this).attr("style",a(this).data("offcanvas-style")).removeData("offcanvas-style")})}},b.prototype.autohide=function(b){0===a(b.target).closest(this.$element).length&&this.hide()};var c=a.fn.offcanvas;a.fn.offcanvas=function(c){return this.each(function(){var d=a(this),e=d.data("bs.offcanvas"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c);e||d.data("bs.offcanvas",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.offcanvas.Constructor=b,a.fn.offcanvas.noConflict=function(){return a.fn.offcanvas=c,this},a(document).on("click.bs.offcanvas.data-api","[data-toggle=offcanvas]",function(b){var c,d=a(this),e=d.attr("data-target")||b.preventDefault()||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.offcanvas"),h=g?"toggle":d.data();b.stopPropagation(),g?g.toggle():f.offcanvas(h)})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.$element.on("click.bs.rowlink","td:not(.rowlink-skip)",a.proxy(this.click,this))};b.DEFAULTS={target:"a"},b.prototype.click=function(b){var c=a(b.currentTarget).closest("tr").find(this.options.target)[0];if(a(b.target)[0]!==c)if(b.preventDefault(),c.click)c.click();else if(document.createEvent){var d=document.createEvent("MouseEvents");d.initMouseEvent("click",!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,null),c.dispatchEvent(d)}};var c=a.fn.rowlink;a.fn.rowlink=function(c){return this.each(function(){var d=a(this),e=d.data("bs.rowlink");e||d.data("bs.rowlink",e=new b(this,c))})},a.fn.rowlink.Constructor=b,a.fn.rowlink.noConflict=function(){return a.fn.rowlink=c,this},a(document).on("click.bs.rowlink.data-api",'[data-link="row"]',function(b){if(0===a(b.target).closest(".rowlink-skip").length){var c=a(this);c.data("bs.rowlink")||(c.rowlink(c.data()),a(b.target).trigger("click.bs.rowlink"))}})}(window.jQuery),+function(a){"use strict";var b=void 0!==window.orientation,c=navigator.userAgent.toLowerCase().indexOf("android")>-1,d="Microsoft Internet Explorer"==window.navigator.appName,e=function(b,d){c||(this.$element=a(b),this.options=a.extend({},e.DEFAULTS,d),this.mask=String(this.options.mask),this.init(),this.listen(),this.checkVal())};e.DEFAULTS={mask:"",placeholder:"_",definitions:{9:"[0-9]",a:"[A-Za-z]",w:"[A-Za-z0-9]","*":"."}},e.prototype.init=function(){var b=this.options.definitions,c=this.mask.length;this.tests=[],this.partialPosition=this.mask.length,this.firstNonMaskPos=null,a.each(this.mask.split(""),a.proxy(function(a,d){"?"==d?(c--,this.partialPosition=a):b[d]?(this.tests.push(new RegExp(b[d])),null===this.firstNonMaskPos&&(this.firstNonMaskPos=this.tests.length-1)):this.tests.push(null)},this)),this.buffer=a.map(this.mask.split(""),a.proxy(function(a){return"?"!=a?b[a]?this.options.placeholder:a:void 0},this)),this.focusText=this.$element.val(),this.$element.data("rawMaskFn",a.proxy(function(){return a.map(this.buffer,function(a,b){return this.tests[b]&&a!=this.options.placeholder?a:null}).join("")},this))},e.prototype.listen=function(){if(!this.$element.attr("readonly")){var b=(d?"paste":"input")+".mask";this.$element.on("unmask.bs.inputmask",a.proxy(this.unmask,this)).on("focus.bs.inputmask",a.proxy(this.focusEvent,this)).on("blur.bs.inputmask",a.proxy(this.blurEvent,this)).on("keydown.bs.inputmask",a.proxy(this.keydownEvent,this)).on("keypress.bs.inputmask",a.proxy(this.keypressEvent,this)).on(b,a.proxy(this.pasteEvent,this))}},e.prototype.caret=function(a,b){if(0!==this.$element.length){if("number"==typeof a)return b="number"==typeof b?b:a,this.$element.each(function(){if(this.setSelectionRange)this.setSelectionRange(a,b);else if(this.createTextRange){var c=this.createTextRange();c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select()}});if(this.$element[0].setSelectionRange)a=this.$element[0].selectionStart,b=this.$element[0].selectionEnd;else if(document.selection&&document.selection.createRange){var c=document.selection.createRange();a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length}return{begin:a,end:b}}},e.prototype.seekNext=function(a){for(var b=this.mask.length;++a<=b&&!this.tests[a];);return a},e.prototype.seekPrev=function(a){for(;--a>=0&&!this.tests[a];);return a},e.prototype.shiftL=function(a,b){var c=this.mask.length;if(!(0>a)){for(var d=a,e=this.seekNext(b);c>d;d++)if(this.tests[d]){if(!(c>e&&this.tests[d].test(this.buffer[e])))break;this.buffer[d]=this.buffer[e],this.buffer[e]=this.options.placeholder,e=this.seekNext(e)}this.writeBuffer(),this.caret(Math.max(this.firstNonMaskPos,a))}},e.prototype.shiftR=function(a){for(var b=this.mask.length,c=a,d=this.options.placeholder;b>c;c++)if(this.tests[c]){var e=this.seekNext(c),f=this.buffer[c];if(this.buffer[c]=d,!(b>e&&this.tests[e].test(f)))break;d=f}},e.prototype.unmask=function(){this.$element.unbind(".mask").removeData("inputmask")},e.prototype.focusEvent=function(){this.focusText=this.$element.val();var a=this.mask.length,b=this.checkVal();this.writeBuffer();var c=this,d=function(){b==a?c.caret(0,b):c.caret(b)};d(),setTimeout(d,50)},e.prototype.blurEvent=function(){this.checkVal(),this.$element.val()!==this.focusText&&this.$element.trigger("change")},e.prototype.keydownEvent=function(a){var c=a.which;if(8==c||46==c||b&&127==c){var d=this.caret(),e=d.begin,f=d.end;return f-e===0&&(e=46!=c?this.seekPrev(e):f=this.seekNext(e-1),f=46==c?this.seekNext(f):f),this.clearBuffer(e,f),this.shiftL(e,f-1),!1}return 27==c?(this.$element.val(this.focusText),this.caret(0,this.checkVal()),!1):void 0},e.prototype.keypressEvent=function(a){var b=this.mask.length,c=a.which,d=this.caret();if(a.ctrlKey||a.altKey||a.metaKey||32>c)return!0;if(c){d.end-d.begin!==0&&(this.clearBuffer(d.begin,d.end),this.shiftL(d.begin,d.end-1));var e=this.seekNext(d.begin-1);if(b>e){var f=String.fromCharCode(c);if(this.tests[e].test(f)){this.shiftR(e),this.buffer[e]=f,this.writeBuffer();var g=this.seekNext(e);this.caret(g)}}return!1}},e.prototype.pasteEvent=function(){var a=this;setTimeout(function(){a.caret(a.checkVal(!0))},0)},e.prototype.clearBuffer=function(a,b){for(var c=this.mask.length,d=a;b>d&&c>d;d++)this.tests[d]&&(this.buffer[d]=this.options.placeholder)},e.prototype.writeBuffer=function(){return this.$element.val(this.buffer.join("")).val()},e.prototype.checkVal=function(a){for(var b=this.mask.length,c=this.$element.val(),d=-1,e=0,f=0;b>e;e++)if(this.tests[e]){for(this.buffer[e]=this.options.placeholder;f++<c.length;){var g=c.charAt(f-1);if(this.tests[e].test(g)){this.buffer[e]=g,d=e;break}}if(f>c.length)break}else this.buffer[e]==c.charAt(f)&&e!=this.partialPosition&&(f++,d=e);return!a&&d+1<this.partialPosition?(this.$element.val(""),this.clearBuffer(0,b)):(a||d+1>=this.partialPosition)&&(this.writeBuffer(),a||this.$element.val(this.$element.val().substring(0,d+1))),this.partialPosition?e:this.firstNonMaskPos};var f=a.fn.inputmask;a.fn.inputmask=function(b){return this.each(function(){var c=a(this),d=c.data("bs.inputmask");d||c.data("bs.inputmask",d=new e(this,b))})},a.fn.inputmask.Constructor=e,a.fn.inputmask.noConflict=function(){return a.fn.inputmask=f,this},a(document).on("focus.bs.inputmask.data-api","[data-mask]",function(){var b=a(this);b.data("bs.inputmask")||b.inputmask(b.data())})}(window.jQuery),+function(a){"use strict";var b="Microsoft Internet Explorer"==window.navigator.appName,c=function(b,c){if(this.$element=a(b),this.$input=this.$element.find(":file"),0!==this.$input.length){this.name=this.$input.attr("name")||c.name,this.$hidden=this.$element.find('input[type=hidden][name="'+this.name+'"]'),0===this.$hidden.length&&(this.$hidden=a('<input type="hidden">').insertBefore(this.$input)),this.$preview=this.$element.find(".fileinput-preview");var d=this.$preview.css("height");"inline"!==this.$preview.css("display")&&"0px"!==d&&"none"!==d&&this.$preview.css("line-height",d),this.original={exists:this.$element.hasClass("fileinput-exists"),preview:this.$preview.html(),hiddenVal:this.$hidden.val()},this.listen()}};c.prototype.listen=function(){this.$input.on("change.bs.fileinput",a.proxy(this.change,this)),a(this.$input[0].form).on("reset.bs.fileinput",a.proxy(this.reset,this)),this.$element.find('[data-trigger="fileinput"]').on("click.bs.fileinput",a.proxy(this.trigger,this)),this.$element.find('[data-dismiss="fileinput"]').on("click.bs.fileinput",a.proxy(this.clear,this))},c.prototype.change=function(b){var c=void 0===b.target.files?b.target&&b.target.value?[{name:b.target.value.replace(/^.+\\/,"")}]:[]:b.target.files;if(b.stopPropagation(),0===c.length)return void this.clear();this.$hidden.val(""),this.$hidden.attr("name",""),this.$input.attr("name",this.name);var d=c[0];if(this.$preview.length>0&&("undefined"!=typeof d.type?d.type.match(/^image\/(gif|png|jpeg)$/):d.name.match(/\.(gif|png|jpe?g)$/i))&&"undefined"!=typeof FileReader){var e=new FileReader,f=this.$preview,g=this.$element;e.onload=function(b){var e=a("<img>");e[0].src=b.target.result,c[0].result=b.target.result,g.find(".fileinput-filename").text(d.name),"none"!=f.css("max-height")&&e.css("max-height",parseInt(f.css("max-height"),10)-parseInt(f.css("padding-top"),10)-parseInt(f.css("padding-bottom"),10)-parseInt(f.css("border-top"),10)-parseInt(f.css("border-bottom"),10)),f.html(e),g.addClass("fileinput-exists").removeClass("fileinput-new"),g.trigger("change.bs.fileinput",c)},e.readAsDataURL(d)}else this.$element.find(".fileinput-filename").text(d.name),this.$preview.text(d.name),this.$element.addClass("fileinput-exists").removeClass("fileinput-new"),this.$element.trigger("change.bs.fileinput")},c.prototype.clear=function(a){if(a&&a.preventDefault(),this.$hidden.val(""),this.$hidden.attr("name",this.name),this.$input.attr("name",""),b){var c=this.$input.clone(!0);this.$input.after(c),this.$input.remove(),this.$input=c}else this.$input.val("");this.$preview.html(""),this.$element.find(".fileinput-filename").text(""),this.$element.addClass("fileinput-new").removeClass("fileinput-exists"),void 0!==a&&(this.$input.trigger("change"),this.$element.trigger("clear.bs.fileinput"))},c.prototype.reset=function(){this.clear(),this.$hidden.val(this.original.hiddenVal),this.$preview.html(this.original.preview),this.$element.find(".fileinput-filename").text(""),this.original.exists?this.$element.addClass("fileinput-exists").removeClass("fileinput-new"):this.$element.addClass("fileinput-new").removeClass("fileinput-exists"),this.$element.trigger("reset.bs.fileinput")},c.prototype.trigger=function(a){this.$input.trigger("click"),a.preventDefault()};var d=a.fn.fileinput;a.fn.fileinput=function(b){return this.each(function(){var d=a(this),e=d.data("bs.fileinput");e||d.data("bs.fileinput",e=new c(this,b)),"string"==typeof b&&e[b]()})},a.fn.fileinput.Constructor=c,a.fn.fileinput.noConflict=function(){return a.fn.fileinput=d,this},a(document).on("click.fileinput.data-api",'[data-provides="fileinput"]',function(b){var c=a(this);if(!c.data("bs.fileinput")){c.fileinput(c.data());var d=a(b.target).closest('[data-dismiss="fileinput"],[data-trigger="fileinput"]');d.length>0&&(b.preventDefault(),d.trigger("click.bs.fileinput"))}})}(window.jQuery); | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/static/js/jasny-bootstrap.min.js | jasny-bootstrap.min.js |
var Hyphenator=(function(window){'use strict';var contextWindow=window,supportedLangs=(function(){var r={},o=function(code,file,script,prompt){r[code]={'file':file,'script':script,'prompt':prompt};};o('be','be.js',1,'Мова гэтага сайта не можа быць вызначаны аўтаматычна. Калі ласка пакажыце мову:');o('ca','ca.js',0,'');o('cs','cs.js',0,'Jazyk této internetové stránky nebyl automaticky rozpoznán. Určete prosím její jazyk:');o('da','da.js',0,'Denne websides sprog kunne ikke bestemmes. Angiv venligst sprog:');o('bn','bn.js',4,'');o('de','de.js',0,'Die Sprache dieser Webseite konnte nicht automatisch bestimmt werden. Bitte Sprache angeben:');o('el','el-monoton.js',6,'');o('el-monoton','el-monoton.js',6,'');o('el-polyton','el-polyton.js',6,'');o('en','en-us.js',0,'The language of this website could not be determined automatically. Please indicate the main language:');o('en-gb','en-gb.js',0,'The language of this website could not be determined automatically. Please indicate the main language:');o('en-us','en-us.js',0,'The language of this website could not be determined automatically. Please indicate the main language:');o('eo','eo.js',0,'La lingvo de ĉi tiu retpaĝo ne rekoneblas aŭtomate. Bonvolu indiki ĝian ĉeflingvon:');o('es','es.js',0,'El idioma del sitio no pudo determinarse autom%E1ticamente. Por favor, indique el idioma principal:');o('et','et.js',0,'Veebilehe keele tuvastamine ebaõnnestus, palun valige kasutatud keel:');o('fi','fi.js',0,'Sivun kielt%E4 ei tunnistettu automaattisesti. M%E4%E4rit%E4 sivun p%E4%E4kieli:');o('fr','fr.js',0,'La langue de ce site n%u2019a pas pu %EAtre d%E9termin%E9e automatiquement. Veuillez indiquer une langue, s.v.p.%A0:');o('grc','grc.js',6,'');o('gu','gu.js',7,'');o('hi','hi.js',5,'');o('hu','hu.js',0,'A weboldal nyelvét nem sikerült automatikusan megállapítani. Kérem adja meg a nyelvet:');o('hy','hy.js',3,'Չհաջողվեց հայտնաբերել այս կայքի լեզուն։ Խնդրում ենք նշեք հիմնական լեզուն՝');o('it','it.js',0,'Lingua del sito sconosciuta. Indicare una lingua, per favore:');o('kn','kn.js',8,'ಜಾಲ ತಾಣದ ಭಾಷೆಯನ್ನು ನಿರ್ಧರಿಸಲು ಸಾಧ್ಯವಾಗುತ್ತಿಲ್ಲ. ದಯವಿಟ್ಟು ಮುಖ್ಯ ಭಾಷೆಯನ್ನು ಸೂಚಿಸಿ:');o('la','la.js',0,'');o('lt','lt.js',0,'Nepavyko automatiškai nustatyti šios svetainės kalbos. Prašome įvesti kalbą:');o('lv','lv.js',0,'Šīs lapas valodu nevarēja noteikt automātiski. Lūdzu norādiet pamata valodu:');o('ml','ml.js',10,'ഈ വെ%u0D2C%u0D4D%u200Cസൈറ്റിന്റെ ഭാഷ കണ്ടുപിടിയ്ക്കാ%u0D28%u0D4D%u200D കഴിഞ്ഞില്ല. ഭാഷ ഏതാണെന്നു തിരഞ്ഞെടുക്കുക:');o('nb','nb-no.js',0,'Nettstedets språk kunne ikke finnes automatisk. Vennligst oppgi språk:');o('no','nb-no.js',0,'Nettstedets språk kunne ikke finnes automatisk. Vennligst oppgi språk:');o('nb-no','nb-no.js',0,'Nettstedets språk kunne ikke finnes automatisk. Vennligst oppgi språk:');o('nl','nl.js',0,'De taal van deze website kan niet automatisch worden bepaald. Geef de hoofdtaal op:');o('or','or.js',11,'');o('pa','pa.js',13,'');o('pl','pl.js',0,'Języka tej strony nie można ustalić automatycznie. Proszę wskazać język:');o('pt','pt.js',0,'A língua deste site não pôde ser determinada automaticamente. Por favor indique a língua principal:');o('ru','ru.js',1,'Язык этого сайта не может быть определен автоматически. Пожалуйста укажите язык:');o('sk','sk.js',0,'');o('sl','sl.js',0,'Jezika te spletne strani ni bilo mogoče samodejno določiti. Prosim navedite jezik:');o('sr-cyrl','sr-cyrl.js',1,'Језик овог сајта није детектован аутоматски. Молим вас наведите језик:');o('sr-latn','sr-latn.js',0,'Jezika te spletne strani ni bilo mogoče samodejno določiti. Prosim navedite jezik:');o('sv','sv.js',0,'Spr%E5ket p%E5 den h%E4r webbplatsen kunde inte avg%F6ras automatiskt. V%E4nligen ange:');o('ta','ta.js',14,'');o('te','te.js',15,'');o('tr','tr.js',0,'Bu web sitesinin dili otomatik olarak tespit edilememiştir. Lütfen dökümanın dilini seçiniz%A0:');o('uk','uk.js',1,'Мова цього веб-сайту не може бути визначена автоматично. Будь ласка, вкажіть головну мову:');o('ro','ro.js',0,'Limba acestui sit nu a putut fi determinată automat. Alege limba principală:');return r;}()),basePath=(function(){var s=contextWindow.document.getElementsByTagName('script'),i=0,p,src,t=s[i],r='';while(!!t){if(!!t.src){src=t.src;p=src.indexOf('Hyphenator.js');if(p!==-1){r=src.substring(0,p);}}i+=1;t=s[i];}return!!r?r:'//hyphenator.googlecode.com/svn/trunk/';}()),isLocal=(function(){var re=false;if(window.location.href.indexOf(basePath)!==-1){re=true;}return re;}()),documentLoaded=false,persistentConfig=false,doFrames=false,dontHyphenate={'video':true,'audio':true,'script':true,'code':true,'pre':true,'img':true,'br':true,'samp':true,'kbd':true,'var':true,'abbr':true,'acronym':true,'sub':true,'sup':true,'button':true,'option':true,'label':true,'textarea':true,'input':true,'math':true,'svg':true,'style':true},enableCache=true,storageType='local',storage,enableReducedPatternSet=false,enableRemoteLoading=true,displayToggleBox=false,onError=function(e){window.alert("Hyphenator.js says:\n\nAn Error occurred:\n"+e.message);},onWarning=function(e){window.console.log(e.message);},createElem=function(tagname,context){context=context||contextWindow;var el;if(window.document.createElementNS){el=context.document.createElementNS('http://www.w3.org/1999/xhtml',tagname);}else if(window.document.createElement){el=context.document.createElement(tagname);}return el;},css3=false,css3_h9n,css3_gethsupport=function(){var s,createLangSupportChecker=function(prefix){var testStrings=['aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz','абвгдеёжзийклмнопрстуфхцчшщъыьэюя','أبتثجحخدذرزسشصضطظعغفقكلمنهوي','աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆ','ঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়ৠৡৢৣ','ँंःअआइईउऊऋऌएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलळवशषसहऽािीुूृॄेैोौ्॒॑ॠॡॢॣ','αβγδεζηθικλμνξοπρσςτυφχψω','બહઅઆઇઈઉઊઋૠએઐઓઔાિીુૂૃૄૢૣેૈોૌકખગઘઙચછજઝઞટઠડઢણતથદધનપફસભમયરલળવશષ','ಂಃಅಆಇಈಉಊಋಌಎಏಐಒಓಔಕಖಗಘಙಚಛಜಝಞಟಠಡಢಣತಥದಧನಪಫಬಭಮಯರಱಲಳವಶಷಸಹಽಾಿೀುೂೃೄೆೇೈೊೋೌ್ೕೖೞೠೡ','ກຂຄງຈຊຍດຕຖທນບປຜຝພຟມຢຣລວສຫອຮະັາິີຶືຸູົຼເແໂໃໄ່້໊໋ໜໝ','ംഃഅആഇഈഉഊഋഌഎഏഐഒഓഔകഖഗഘങചഛജഝഞടഠഡഢണതഥദധനപഫബഭമയരറലളഴവശഷസഹാിീുൂൃെേൈൊോൌ്ൗൠൡൺൻർൽൾൿ','ଁଂଃଅଆଇଈଉଊଋଌଏଐଓଔକଖଗଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଳଵଶଷସହାିୀୁୂୃେୈୋୌ୍ୗୠୡ','أبتثجحخدذرزسشصضطظعغفقكلمنهوي','ਁਂਃਅਆਇਈਉਊਏਐਓਔਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਲ਼ਵਸ਼ਸਹਾਿੀੁੂੇੈੋੌ੍ੰੱ','ஃஅஆஇஈஉஊஎஏஐஒஓஔகஙசஜஞடணதநனபமயரறலளழவஷஸஹாிீுூெேைொோௌ்ௗ','ఁంఃఅఆఇఈఉఊఋఌఎఏఐఒఓఔకఖగఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరఱలళవశషసహాిీుూృౄెేైొోౌ్ౕౖౠౡ'],f=function(lang){var shadow,computedHeight,bdy,r=false;if(this.supportedBrowserLangs.hasOwnProperty(lang)){r=this.supportedBrowserLangs[lang];}else if(supportedLangs.hasOwnProperty(lang)){bdy=window.document.getElementsByTagName('body')[0];shadow=createElem('div',window);shadow.id='Hyphenator_LanguageChecker';shadow.style.width='5em';shadow.style[prefix]='auto';shadow.style.hyphens='auto';shadow.style.fontSize='12px';shadow.style.lineHeight='12px';shadow.style.visibility='hidden';shadow.lang=lang;shadow.style['-webkit-locale']="'"+lang+"'";shadow.innerHTML=testStrings[supportedLangs[lang].script];bdy.appendChild(shadow);computedHeight=shadow.offsetHeight;bdy.removeChild(shadow);r=(computedHeight>12)?true:false;this.supportedBrowserLangs[lang]=r;}else{r=false;}return r;};return f;},r={support:false,supportedBrowserLangs:{},property:'',checkLangSupport:{}};if(window.getComputedStyle){s=window.getComputedStyle(window.document.getElementsByTagName('body')[0],null);}else{css3_h9n=r;return;}if(s.hyphens!==undefined){r.support=true;r.property='hyphens';r.checkLangSupport=createLangSupportChecker('hyphens');}else if(s['-webkit-hyphens']!==undefined){r.support=true;r.property='-webkit-hyphens';r.checkLangSupport=createLangSupportChecker('-webkit-hyphens');}else if(s.MozHyphens!==undefined){r.support=true;r.property='-moz-hyphens';r.checkLangSupport=createLangSupportChecker('MozHyphens');}else if(s['-ms-hyphens']!==undefined){r.support=true;r.property='-ms-hyphens';r.checkLangSupport=createLangSupportChecker('-ms-hyphens');}css3_h9n=r;},hyphenateClass='hyphenate',urlHyphenateClass='urlhyphenate',classPrefix='Hyphenator'+Math.round(Math.random()*1000),hideClass=classPrefix+'hide',hideClassRegExp=new RegExp("\\s?\\b"+hideClass+"\\b","g"),unhideClass=classPrefix+'unhide',unhideClassRegExp=new RegExp("\\s?\\b"+unhideClass+"\\b","g"),css3hyphenateClass=classPrefix+'css3hyphenate',css3hyphenateClassHandle,dontHyphenateClass='donthyphenate',min=6,orphanControl=1,isBookmarklet=(function(){var loc=null,re=false,scripts=contextWindow.document.getElementsByTagName('script'),i=0,l=scripts.length;while(!re&&i<l){loc=scripts[i].getAttribute('src');if(!!loc&&loc.indexOf('Hyphenator.js?bm=true')!==-1){re=true;}i+=1;}return re;}()),mainLanguage=null,defaultLanguage='',elements=(function(){var Element=function(element){this.element=element;this.hyphenated=false;this.treated=false;},ElementCollection=function(){this.count=0;this.hyCount=0;this.list={};};ElementCollection.prototype={add:function(el,lang){var elo=new Element(el);if(!this.list.hasOwnProperty(lang)){this.list[lang]=[];}this.list[lang].push(elo);this.count+=1;return elo;},remove:function(el){var lang,i,e,l;for(lang in this.list){if(this.list.hasOwnProperty(lang)){for(i=0;i<this.list[lang].length;i+=1){if(this.list[lang][i].element===el){e=i;l=lang;break;}}}}this.list[l].splice(e,1);this.count-=1;this.hyCount-=1;},each:function(fn){var k;for(k in this.list){if(this.list.hasOwnProperty(k)){if(fn.length===2){fn(k,this.list[k]);}else{fn(this.list[k]);}}}}};return new ElementCollection();}()),exceptions={},docLanguages={},url='(\\w*:\/\/)?((\\w*:)?(\\w*)@)?((([\\d]{1,3}\\.){3}([\\d]{1,3}))|((www\\.|[a-zA-Z]\\.)?[a-zA-Z0-9\\-\\.]+\\.([a-z]{2,4})))(:\\d*)?(\/[\\w#!:\\.?\\+=&%@!\\-]*)*',mail='[\\w-\\.]+@[\\w\\.]+',urlOrMailRE=new RegExp('('+url+')|('+mail+')','i'),zeroWidthSpace=(function(){var zws,ua=window.navigator.userAgent.toLowerCase();zws=String.fromCharCode(8203);if(ua.indexOf('msie 6')!==-1){zws='';}if(ua.indexOf('opera')!==-1&&ua.indexOf('version/10.00')!==-1){zws='';}return zws;}()),onBeforeWordHyphenation=function(word){return word;},onAfterWordHyphenation=function(word){return word;},onHyphenationDone=function(context){return context;},selectorFunction=false,mySelectorFunction=function(hyphenateClass){var tmp,el=[],i,l;if(window.document.getElementsByClassName){el=contextWindow.document.getElementsByClassName(hyphenateClass);}else if(window.document.querySelectorAll){el=contextWindow.document.querySelectorAll('.'+hyphenateClass);}else{tmp=contextWindow.document.getElementsByTagName('*');l=tmp.length;for(i=0;i<l;i+=1){if(tmp[i].className.indexOf(hyphenateClass)!==-1&&tmp[i].className.indexOf(dontHyphenateClass)===-1){el.push(tmp[i]);}}}return el;},selectElements=function(){var elems;if(selectorFunction){elems=selectorFunction();}else{elems=mySelectorFunction(hyphenateClass);}return elems;},intermediateState='hidden',unhide='wait',CSSEditors=[],CSSEdit=function(w){w=w||window;var doc=w.document,sheet=(function(){var i,l=doc.styleSheets.length,s,element,r=false;for(i=0;i<l;i+=1){s=doc.styleSheets[i];try{if(!!s.cssRules){r=s;break;}}catch(ignore){}}r=false;if(r===false){element=doc.createElement('style');element.type='text/css';doc.getElementsByTagName('head')[0].appendChild(element);r=doc.styleSheets[doc.styleSheets.length-1];}return r;}()),changes=[],findRule=function(sel){var s,rule,sheets=w.document.styleSheets,rules,i,j,r=false;for(i=0;i<sheets.length;i+=1){s=sheets[i];try{if(!!s.cssRules){rules=s.cssRules;}else if(!!s.rules){rules=s.rules;}}catch(ignore){}if(!!rules&&!!rules.length){for(j=0;j<rules.length;j+=1){rule=rules[j];if(rule.selectorText===sel){r={index:j,rule:rule};}}}}return r;},addRule=function(sel,rulesStr){var i,r;if(!!sheet.insertRule){if(!!sheet.cssRules){i=sheet.cssRules.length;}else{i=0;}r=sheet.insertRule(sel+'{'+rulesStr+'}',i);}else if(!!sheet.addRule){if(!!sheet.rules){i=sheet.rules.length;}else{i=0;}sheet.addRule(sel,rulesStr,i);r=i;}return r;},removeRule=function(sheet,index){if(sheet.deleteRule){sheet.deleteRule(index);}else{sheet.removeRule(index);}};return{setRule:function(sel,rulesString){var i,existingRule,cssText;existingRule=findRule(sel);if(!!existingRule){if(!!existingRule.rule.cssText){cssText=existingRule.rule.cssText;}else{cssText=existingRule.rule.style.cssText.toLowerCase();}if(cssText==='.'+hyphenateClass+' { visibility: hidden; }'){changes.push({sheet:existingRule.rule.parentStyleSheet,index:existingRule.index});}else if(cssText.indexOf('visibility: hidden')!==-1){i=addRule(sel,rulesString);changes.push({sheet:sheet,index:i});existingRule.rule.style.visibility='';}else{i=addRule(sel,rulesString);changes.push({sheet:sheet,index:i});}}else{i=addRule(sel,rulesString);changes.push({sheet:sheet,index:i});}},clearChanges:function(){var change=changes.pop();while(!!change){removeRule(change.sheet,change.index);change=changes.pop();}}};},hyphen=String.fromCharCode(173),urlhyphen=zeroWidthSpace,hyphenateURL=function(url){var tmp=url.replace(/([:\/\.\?#&\-_,;!@]+)/gi,'$&'+urlhyphen),parts=tmp.split(urlhyphen),i;for(i=0;i<parts.length;i+=1){if(parts[i].length>(2*min)){parts[i]=parts[i].replace(/(\w{3})(\w)/gi,"$1"+urlhyphen+"$2");}}if(parts[parts.length-1]===""){parts.pop();}return parts.join(urlhyphen);},safeCopy=true,hyphRunFor={},runWhenLoaded=function(w,f){var toplevel,add=window.document.addEventListener?'addEventListener':'attachEvent',rem=window.document.addEventListener?'removeEventListener':'detachEvent',pre=window.document.addEventListener?'':'on',init=function(context){if(hyphRunFor[context.location.href]){onWarning(new Error("Warning: multiple execution of Hyphenator.run() – This may slow down the script!"));}contextWindow=context||window;f();hyphRunFor[contextWindow.location.href]=true;},doScrollCheck=function(){try{w.document.documentElement.doScroll("left");}catch(error){window.setTimeout(doScrollCheck,1);return;}if(!hyphRunFor[w.location.href]){documentLoaded=true;init(w);}},doOnEvent=function(e){var i,fl,haveAccess;if(!!e&&e.type==='readystatechange'&&w.document.readyState!=='interactive'&&w.document.readyState!=='complete'){return;}w.document[rem](pre+'DOMContentLoaded',doOnEvent,false);w.document[rem](pre+'readystatechange',doOnEvent,false);fl=w.frames.length;if(fl===0||!doFrames){w[rem](pre+'load',doOnEvent,false);documentLoaded=true;init(w);}else if(doFrames&&fl>0){if(!!e&&e.type==='load'){w[rem](pre+'load',doOnEvent,false);for(i=0;i<fl;i+=1){haveAccess=undefined;try{haveAccess=window.frames[i].document.toString();}catch(err){haveAccess=undefined;}if(!!haveAccess){runWhenLoaded(w.frames[i],f);}}init(w);}}};if(documentLoaded||w.document.readyState==='complete'){documentLoaded=true;doOnEvent({type:'load'});}else{w.document[add](pre+'DOMContentLoaded',doOnEvent,false);w.document[add](pre+'readystatechange',doOnEvent,false);w[add](pre+'load',doOnEvent,false);toplevel=false;try{toplevel=!window.frameElement;}catch(ignore){}if(toplevel&&w.document.documentElement.doScroll){doScrollCheck();}}},getLang=function(el,fallback){try{return!!el.getAttribute('lang')?el.getAttribute('lang').toLowerCase():!!el.getAttribute('xml:lang')?el.getAttribute('xml:lang').toLowerCase():el.tagName.toLowerCase()!=='html'?getLang(el.parentNode,fallback):fallback?mainLanguage:null;}catch(ignore){}},autoSetMainLanguage=function(w){w=w||contextWindow;var el=w.document.getElementsByTagName('html')[0],m=w.document.getElementsByTagName('meta'),i,getLangFromUser=function(){var ml,text='',dH=300,dW=450,dX=Math.floor((w.outerWidth-dW)/2)+window.screenX,dY=Math.floor((w.outerHeight-dH)/2)+window.screenY,ul='',languageHint;if(!!window.showModalDialog&&(w.location.href.indexOf(basePath)!==-1)){ml=window.showModalDialog(basePath+'modalLangDialog.html',supportedLangs,"dialogWidth: "+dW+"px; dialogHeight: "+dH+"px; dialogtop: "+dY+"; dialogleft: "+dX+"; center: on; resizable: off; scroll: off;");}else{languageHint=(function(){var k,r='';for(k in supportedLangs){if(supportedLangs.hasOwnProperty(k)){r+=k+', ';}}r=r.substring(0,r.length-2);return r;}());ul=window.navigator.language||window.navigator.userLanguage;ul=ul.substring(0,2);if(!!supportedLangs[ul]&&supportedLangs[ul].prompt!==''){text=supportedLangs[ul].prompt;}else{text=supportedLangs.en.prompt;}text+=' (ISO 639-1)\n\n'+languageHint;ml=window.prompt(window.unescape(text),ul).toLowerCase();}return ml;};mainLanguage=getLang(el,false);if(!mainLanguage){for(i=0;i<m.length;i+=1){if(!!m[i].getAttribute('http-equiv')&&(m[i].getAttribute('http-equiv').toLowerCase()==='content-language')){mainLanguage=m[i].getAttribute('content').toLowerCase();}if(!!m[i].getAttribute('name')&&(m[i].getAttribute('name').toLowerCase()==='dc.language')){mainLanguage=m[i].getAttribute('content').toLowerCase();}if(!!m[i].getAttribute('name')&&(m[i].getAttribute('name').toLowerCase()==='language')){mainLanguage=m[i].getAttribute('content').toLowerCase();}}}if(!mainLanguage&&doFrames&&(!!contextWindow.frameElement)){autoSetMainLanguage(window.parent);}if(!mainLanguage&&defaultLanguage!==''){mainLanguage=defaultLanguage;}if(!mainLanguage){mainLanguage=getLangFromUser();}el.lang=mainLanguage;},gatherDocumentInfos=function(){var elToProcess,urlhyphenEls,tmp,i=0,process=function(el,pLang,isChild){isChild=isChild||false;var n,j=0,hyphenate=true,eLang,useCSS3=function(){css3hyphenateClassHandle=new CSSEdit(contextWindow);css3hyphenateClassHandle.setRule('.'+css3hyphenateClass,css3_h9n.property+': auto;');css3hyphenateClassHandle.setRule('.'+dontHyphenateClass,css3_h9n.property+': manual;');if((eLang!==pLang)&&css3_h9n.property.indexOf('webkit')!==-1){css3hyphenateClassHandle.setRule('.'+css3hyphenateClass,'-webkit-locale : '+eLang+';');}el.className=el.className+' '+css3hyphenateClass;},useHyphenator=function(){if(isBookmarklet&&eLang!==mainLanguage){return;}if(supportedLangs.hasOwnProperty(eLang)){docLanguages[eLang]=true;}else{if(supportedLangs.hasOwnProperty(eLang.split('-')[0])){eLang=eLang.split('-')[0];docLanguages[eLang]=true;}else if(!isBookmarklet){hyphenate=false;onError(new Error('Language "'+eLang+'" is not yet supported.'));}}if(hyphenate){if(intermediateState==='hidden'){el.className=el.className+' '+hideClass;}elements.add(el,eLang);}};if(el.lang&&typeof(el.lang)==='string'){eLang=el.lang.toLowerCase();}else if(!!pLang&&pLang!==''){eLang=pLang.toLowerCase();}else{eLang=getLang(el,true);}if(!isChild){if(css3&&css3_h9n.support&&!!css3_h9n.checkLangSupport(eLang)){useCSS3();}else{useHyphenator();}}else{if(eLang!==pLang){if(css3&&css3_h9n.support&&!!css3_h9n.checkLangSupport(eLang)){useCSS3();}else{useHyphenator();}}else{if(!css3||!css3_h9n.support||!css3_h9n.checkLangSupport(eLang)){useHyphenator();}}}n=el.childNodes[j];while(!!n){if(n.nodeType===1&&!dontHyphenate[n.nodeName.toLowerCase()]&&n.className.indexOf(dontHyphenateClass)===-1&&n.className.indexOf(urlHyphenateClass)===-1&&!elToProcess[n]){process(n,eLang,true);}j+=1;n=el.childNodes[j];}},processUrlStyled=function(el){var n,j=0;n=el.childNodes[j];while(!!n){if(n.nodeType===1&&!dontHyphenate[n.nodeName.toLowerCase()]&&n.className.indexOf(dontHyphenateClass)===-1&&n.className.indexOf(hyphenateClass)===-1&&!urlhyphenEls[n]){processUrlStyled(n);}else if(n.nodeType===3){n.data=hyphenateURL(n.data);}j+=1;n=el.childNodes[j];}};if(css3){css3_gethsupport();}if(isBookmarklet){elToProcess=contextWindow.document.getElementsByTagName('body')[0];process(elToProcess,mainLanguage,false);}else{if(!css3&&intermediateState==='hidden'){CSSEditors.push(new CSSEdit(contextWindow));CSSEditors[CSSEditors.length-1].setRule('.'+hyphenateClass,'visibility: hidden;');CSSEditors[CSSEditors.length-1].setRule('.'+hideClass,'visibility: hidden;');CSSEditors[CSSEditors.length-1].setRule('.'+unhideClass,'visibility: visible;');}elToProcess=selectElements();tmp=elToProcess[i];while(!!tmp){process(tmp,'',false);i+=1;tmp=elToProcess[i];}urlhyphenEls=mySelectorFunction(urlHyphenateClass);i=0;tmp=urlhyphenEls[i];while(!!tmp){processUrlStyled(tmp);i+=1;tmp=urlhyphenEls[i];}}if(elements.count===0){for(i=0;i<CSSEditors.length;i+=1){CSSEditors[i].clearChanges();}onHyphenationDone(contextWindow.location.href);}},convertPatterns=function(lo){var size,tree={},convert=function(psize,patterns){var i=0,t=tree,cc=0,points=[],ppos=0,lastwasp=false,len=0;while(i<patterns.length){if(len<psize){cc=patterns.charCodeAt(i);if(cc>=49&&cc<=57){points[ppos]=cc-48;ppos+=1;lastwasp=true;}else{if(!t[cc]){t[cc]={};}t=t[cc];if(!lastwasp){points[ppos]=0;ppos+=1;}lastwasp=false;}len+=1;i+=1;}if(len===psize){if(!lastwasp){points[ppos]=0;}t.tpoints=points;t=tree;points=[];ppos=0;lastwasp=false;len=0;}}};for(size in lo.patterns){if(lo.patterns.hasOwnProperty(size)){convert(parseInt(size,10),lo.patterns[size]);}}lo.patterns=tree;},recreatePattern=function(pattern,nodePoints){var r=[],c=pattern.split(''),i;for(i=0;i<nodePoints.length;i+=1){if(nodePoints[i]!==0){r.push(nodePoints[i]);}if(c[i]){r.push(c[i]);}}return r.join('');},convertExceptionsToObject=function(exc){var w=exc.split(', '),r={},i,l,key;for(i=0,l=w.length;i<l;i+=1){key=w[i].replace(/-/g,'');if(!r.hasOwnProperty(key)){r[key]=w[i];}}return r;},loadPatterns=function(lang){var location,xhr,head,script;if(supportedLangs.hasOwnProperty(lang)&&!Hyphenator.languages[lang]){location=basePath+'patterns/'+supportedLangs[lang].file;}else{return;}if(isLocal&&!isBookmarklet){xhr=null;try{xhr=new window.XMLHttpRequest();}catch(e){try{xhr=new window.ActiveXObject("Microsoft.XMLHTTP");}catch(e2){try{xhr=new window.ActiveXObject("Msxml2.XMLHTTP");}catch(e3){xhr=null;}}}if(xhr){xhr.open('HEAD',location,true);xhr.setRequestHeader('Cache-Control','no-cache');xhr.onreadystatechange=function(){if(xhr.readyState===4){if(xhr.status===404){onError(new Error('Could not load\n'+location));delete docLanguages[lang];return;}}};xhr.send(null);}}if(createElem){head=window.document.getElementsByTagName('head').item(0);script=createElem('script',window);script.src=location;script.type='text/javascript';script.charset='utf8';head.appendChild(script);}},prepareLanguagesObj=function(lang){var lo=Hyphenator.languages[lang],wrd;if(!lo.prepared){if(enableCache){lo.cache={};}if(enableReducedPatternSet){lo.redPatSet={};}if(lo.hasOwnProperty('exceptions')){Hyphenator.addExceptions(lang,lo.exceptions);delete lo.exceptions;}if(exceptions.hasOwnProperty('global')){if(exceptions.hasOwnProperty(lang)){exceptions[lang]+=', '+exceptions.global;}else{exceptions[lang]=exceptions.global;}}if(exceptions.hasOwnProperty(lang)){lo.exceptions=convertExceptionsToObject(exceptions[lang]);delete exceptions[lang];}else{lo.exceptions={};}convertPatterns(lo);wrd='[\\w'+lo.specialChars+'@'+String.fromCharCode(173)+String.fromCharCode(8204)+'-]{'+min+',}';lo.genRegExp=new RegExp('('+url+')|('+mail+')|('+wrd+')','gi');lo.prepared=true;}if(!!storage){storage.setItem(lang,window.JSON.stringify(lo));}},prepare=function(callback){var lang,interval,tmp1,tmp2,languagesLoaded=function(){var finishedLoading=true,l;for(l in docLanguages){if(docLanguages.hasOwnProperty(l)){finishedLoading=false;if(!!Hyphenator.languages[l]){delete docLanguages[l];prepareLanguagesObj(l);callback(l);}}}return finishedLoading;};if(!enableRemoteLoading){for(lang in Hyphenator.languages){if(Hyphenator.languages.hasOwnProperty(lang)){prepareLanguagesObj(lang);}}callback('*');return;}for(lang in docLanguages){if(docLanguages.hasOwnProperty(lang)){if(!!storage&&storage.test(lang)){Hyphenator.languages[lang]=window.JSON.parse(storage.getItem(lang));if(exceptions.hasOwnProperty('global')){tmp1=convertExceptionsToObject(exceptions.global);for(tmp2 in tmp1){if(tmp1.hasOwnProperty(tmp2)){Hyphenator.languages[lang].exceptions[tmp2]=tmp1[tmp2];}}}if(exceptions.hasOwnProperty(lang)){tmp1=convertExceptionsToObject(exceptions[lang]);for(tmp2 in tmp1){if(tmp1.hasOwnProperty(tmp2)){Hyphenator.languages[lang].exceptions[tmp2]=tmp1[tmp2];}}delete exceptions[lang];}tmp1='[\\w'+Hyphenator.languages[lang].specialChars+'@'+String.fromCharCode(173)+String.fromCharCode(8204)+'-]{'+min+',}';Hyphenator.languages[lang].genRegExp=new RegExp('('+url+')|('+mail+')|('+tmp1+')','gi');delete docLanguages[lang];callback(lang);}else{loadPatterns(lang);}}}if(!languagesLoaded()){interval=window.setInterval(function(){var loadingDone=languagesLoaded();if(loadingDone){window.clearInterval(interval);}},100);}},toggleBox=function(){var bdy,myTextNode,text=(Hyphenator.doHyphenation?'Hy-phen-a-tion':'Hyphenation'),myBox=contextWindow.document.getElementById('HyphenatorToggleBox');if(!!myBox){myBox.firstChild.data=text;}else{bdy=contextWindow.document.getElementsByTagName('body')[0];myBox=createElem('div',contextWindow);myBox.setAttribute('id','HyphenatorToggleBox');myBox.setAttribute('class',dontHyphenateClass);myTextNode=contextWindow.document.createTextNode(text);myBox.appendChild(myTextNode);myBox.onclick=Hyphenator.toggleHyphenation;myBox.style.position='absolute';myBox.style.top='0px';myBox.style.right='0px';myBox.style.margin='0';myBox.style.backgroundColor='#AAAAAA';myBox.style.color='#FFFFFF';myBox.style.font='6pt Arial';myBox.style.letterSpacing='0.2em';myBox.style.padding='3px';myBox.style.cursor='pointer';myBox.style.WebkitBorderBottomLeftRadius='4px';myBox.style.MozBorderRadiusBottomleft='4px';myBox.style.borderBottomLeftRadius='4px';bdy.appendChild(myBox);}},hyphenateWord=function(lo,lang,word){var parts,i,pattern,ww,wwlen,wwhp=[],pstart,plen,trie=lo.patterns,node,nodePoints,hp,wordLength=word.length,hw='',doCharSubst=function(w){var subst,r;for(subst in lo.charSubstitution){if(lo.charSubstitution.hasOwnProperty(subst)){r=w.replace(new RegExp(subst,'g'),lo.charSubstitution[subst]);}}return r;};word=onBeforeWordHyphenation(word,lang);if(word===''){hw='';}else if(enableCache&&lo.cache.hasOwnProperty(word)){hw=lo.cache[word];}else if(word.indexOf(hyphen)!==-1){hw=word;}else if(lo.exceptions.hasOwnProperty(word)){hw=lo.exceptions[word].replace(/-/g,hyphen);}else if(word.indexOf('-')!==-1){parts=word.split('-');for(i=0;i<parts.length;i+=1){parts[i]=hyphenateWord(lo,lang,parts[i]);}hw=parts.join('-');}else{ww=word.toLowerCase();if(!!lo.charSubstitution){ww=doCharSubst(ww);}if(word.indexOf("'")!==-1){ww=ww.replace("'","’");}ww='_'+ww+'_';wwlen=ww.length;for(hp=0;hp<wwlen+1;hp+=1){wwhp[hp]=0;}for(pstart=0;pstart<wwlen;pstart+=1){node=trie;pattern='';for(plen=pstart;plen<wwlen;plen+=1){node=node[ww.charCodeAt(plen)];if(node){if(enableReducedPatternSet){pattern+=ww.charAt(plen);}nodePoints=node.tpoints;if(nodePoints){if(enableReducedPatternSet){if(!lo.redPatSet){lo.redPatSet={};}lo.redPatSet[pattern]=recreatePattern(pattern,nodePoints);}for(hp=0;hp<nodePoints.length;hp+=1){wwhp[pstart+hp]=Math.max(wwhp[pstart+hp],nodePoints[hp]);}}}else{break;}}}for(hp=0;hp<wordLength;hp+=1){if(hp>=lo.leftmin&&hp<=(wordLength-lo.rightmin)&&(wwhp[hp+1]%2)!==0){hw+=hyphen+word.charAt(hp);}else{hw+=word.charAt(hp);}}}hw=onAfterWordHyphenation(hw,lang);if(enableCache){lo.cache[word]=hw;}return hw;},removeHyphenationFromElement=function(el){var h,u,i=0,n;switch(hyphen){case'|':h='\\|';break;case'+':h='\\+';break;case'*':h='\\*';break;default:h=hyphen;}switch(urlhyphen){case'|':u='\\|';break;case'+':u='\\+';break;case'*':u='\\*';break;default:u=urlhyphen;}n=el.childNodes[i];while(!!n){if(n.nodeType===3){n.data=n.data.replace(new RegExp(h,'g'),'');n.data=n.data.replace(new RegExp(u,'g'),'');}else if(n.nodeType===1){removeHyphenationFromElement(n);}i+=1;n=el.childNodes[i];}},copy=(function(){var Copy=function(){this.oncopyHandler=function(e){e=e||window.event;var shadow,selection,range,rangeShadow,restore,target=e.target||e.srcElement,currDoc=target.ownerDocument,bdy=currDoc.getElementsByTagName('body')[0],targetWindow=currDoc.defaultView||currDoc.parentWindow;if(target.tagName&&dontHyphenate[target.tagName.toLowerCase()]){return;}shadow=currDoc.createElement('div');shadow.style.color=window.getComputedStyle?targetWindow.getComputedStyle(bdy,null).backgroundColor:'#FFFFFF';shadow.style.fontSize='0px';bdy.appendChild(shadow);if(!!window.getSelection){e.stopPropagation();selection=targetWindow.getSelection();range=selection.getRangeAt(0);shadow.appendChild(range.cloneContents());removeHyphenationFromElement(shadow);selection.selectAllChildren(shadow);restore=function(){shadow.parentNode.removeChild(shadow);selection.removeAllRanges();selection.addRange(range);};}else{e.cancelBubble=true;selection=targetWindow.document.selection;range=selection.createRange();shadow.innerHTML=range.htmlText;removeHyphenationFromElement(shadow);rangeShadow=bdy.createTextRange();rangeShadow.moveToElementText(shadow);rangeShadow.select();restore=function(){shadow.parentNode.removeChild(shadow);if(range.text!==""){range.select();}};}window.setTimeout(restore,0);};this.removeOnCopy=function(el){var body=el.ownerDocument.getElementsByTagName('body')[0];if(!body){return;}el=el||body;if(window.removeEventListener){el.removeEventListener("copy",this.oncopyHandler,true);}else{el.detachEvent("oncopy",this.oncopyHandler);}};this.registerOnCopy=function(el){var body=el.ownerDocument.getElementsByTagName('body')[0];if(!body){return;}el=el||body;if(window.addEventListener){el.addEventListener("copy",this.oncopyHandler,true);}else{el.attachEvent("oncopy",this.oncopyHandler);}};};return(safeCopy?new Copy():false);}()),checkIfAllDone=function(){var allDone=true,i,doclist={},doc;elements.each(function(ellist){var j,l=ellist.length;for(j=0;j<l;j+=1){allDone=allDone&&ellist[j].hyphenated;if(!doclist.hasOwnProperty(ellist[j].element.baseURI)){doclist[ellist[j].element.ownerDocument.location.href]=true;}doclist[ellist[j].element.ownerDocument.location.href]=doclist[ellist[j].element.ownerDocument.location.href]&&ellist[j].hyphenated;}});if(allDone){if(intermediateState==='hidden'&&unhide==='progressive'){elements.each(function(ellist){var j,l=ellist.length,el;for(j=0;j<l;j+=1){el=ellist[j].element;el.className=el.className.replace(unhideClassRegExp,'');if(el.className===''){el.removeAttribute('class');}}});}for(i=0;i<CSSEditors.length;i+=1){CSSEditors[i].clearChanges();}for(doc in doclist){if(doclist.hasOwnProperty(doc)){onHyphenationDone(doc);}}}},hyphenateElement=function(lang,elo){var el=elo.element,hyphenate,n,i,lo,controlOrphans=function(part){var h,r;switch(hyphen){case'|':h='\\|';break;case'+':h='\\+';break;case'*':h='\\*';break;default:h=hyphen;}part=part.replace(/[\s]*$/,'');if(orphanControl>=2){r=part.split(' ');r[1]=r[1].replace(new RegExp(h,'g'),'');r[1]=r[1].replace(new RegExp(zeroWidthSpace,'g'),'');r=r.join(' ');}if(orphanControl===3){r=r.replace(/[ ]+/g,String.fromCharCode(160));}return r;};if(Hyphenator.languages.hasOwnProperty(lang)){lo=Hyphenator.languages[lang];hyphenate=function(word){var r;if(!Hyphenator.doHyphenation){r=word;}else if(urlOrMailRE.test(word)){r=hyphenateURL(word);}else{r=hyphenateWord(lo,lang,word);}return r;};if(safeCopy&&(el.tagName.toLowerCase()!=='body')){copy.registerOnCopy(el);}i=0;n=el.childNodes[i];while(!!n){if(n.nodeType===3&&n.data.length>=min){n.data=n.data.replace(lo.genRegExp,hyphenate);if(orphanControl!==1){n.data=n.data.replace(/[\S]+ [\S]+[\s]*$/,controlOrphans);}}i+=1;n=el.childNodes[i];}}if(intermediateState==='hidden'&&unhide==='wait'){el.className=el.className.replace(hideClassRegExp,'');if(el.className===''){el.removeAttribute('class');}}if(intermediateState==='hidden'&&unhide==='progressive'){el.className=el.className.replace(hideClassRegExp,' '+unhideClass);}elo.hyphenated=true;elements.hyCount+=1;if(elements.count<=elements.hyCount){checkIfAllDone();}},hyphenateLanguageElements=function(lang){function bind(fun,arg1,arg2){return function(){return fun(arg1,arg2);};}var i,l;if(lang==='*'){elements.each(function(lang,ellist){var j,le=ellist.length;for(j=0;j<le;j+=1){window.setTimeout(bind(hyphenateElement,lang,ellist[j]),0);}});}else{if(elements.list.hasOwnProperty(lang)){l=elements.list[lang].length;for(i=0;i<l;i+=1){window.setTimeout(bind(hyphenateElement,lang,elements.list[lang][i]),0);}}}},removeHyphenationFromDocument=function(){elements.each(function(ellist){var i,l=ellist.length;for(i=0;i<l;i+=1){removeHyphenationFromElement(ellist[i].element);if(safeCopy){copy.removeOnCopy(ellist[i].element);}ellist[i].hyphenated=false;}});},createStorage=function(){var s;try{if(storageType!=='none'&&window.localStorage!==undefined&&window.sessionStorage!==undefined&&window.JSON.stringify!==undefined&&window.JSON.parse!==undefined){switch(storageType){case'session':s=window.sessionStorage;break;case'local':s=window.localStorage;break;default:s=undefined;break;}s.setItem('storageTest','1');s.removeItem('storageTest');}}catch(e){s=undefined;}if(s){storage={prefix:'Hyphenator_'+Hyphenator.version+'_',store:s,test:function(name){var val=this.store.getItem(this.prefix+name);return(!!val)?true:false;},getItem:function(name){return this.store.getItem(this.prefix+name);},setItem:function(name,value){try{this.store.setItem(this.prefix+name,value);}catch(e){onError(e);}}};}else{storage=undefined;}},storeConfiguration=function(){if(!storage){return;}var settings={'STORED':true,'classname':hyphenateClass,'urlclassname':urlHyphenateClass,'donthyphenateclassname':dontHyphenateClass,'minwordlength':min,'hyphenchar':hyphen,'urlhyphenchar':urlhyphen,'togglebox':toggleBox,'displaytogglebox':displayToggleBox,'remoteloading':enableRemoteLoading,'enablecache':enableCache,'enablereducedpatternset':enableReducedPatternSet,'onhyphenationdonecallback':onHyphenationDone,'onerrorhandler':onError,'onwarninghandler':onWarning,'intermediatestate':intermediateState,'selectorfunction':selectorFunction||mySelectorFunction,'safecopy':safeCopy,'doframes':doFrames,'storagetype':storageType,'orphancontrol':orphanControl,'dohyphenation':Hyphenator.doHyphenation,'persistentconfig':persistentConfig,'defaultlanguage':defaultLanguage,'useCSS3hyphenation':css3,'unhide':unhide,'onbeforewordhyphenation':onBeforeWordHyphenation,'onafterwordhyphenation':onAfterWordHyphenation};storage.setItem('config',window.JSON.stringify(settings));},restoreConfiguration=function(){var settings;if(storage.test('config')){settings=window.JSON.parse(storage.getItem('config'));Hyphenator.config(settings);}};return{version:'4.3.0',doHyphenation:true,languages:{},config:function(obj){var assert=function(name,type){var r,t;t=typeof obj[name];if(t===type){r=true;}else{onError(new Error('Config onError: '+name+' must be of type '+type));r=false;}return r;},key;if(obj.hasOwnProperty('storagetype')){if(assert('storagetype','string')){storageType=obj.storagetype;}if(!storage){createStorage();}}if(!obj.hasOwnProperty('STORED')&&storage&&obj.hasOwnProperty('persistentconfig')&&obj.persistentconfig===true){restoreConfiguration();}for(key in obj){if(obj.hasOwnProperty(key)){switch(key){case'STORED':break;case'classname':if(assert('classname','string')){hyphenateClass=obj[key];}break;case'urlclassname':if(assert('urlclassname','string')){urlHyphenateClass=obj[key];}break;case'donthyphenateclassname':if(assert('donthyphenateclassname','string')){dontHyphenateClass=obj[key];}break;case'minwordlength':if(assert('minwordlength','number')){min=obj[key];}break;case'hyphenchar':if(assert('hyphenchar','string')){if(obj.hyphenchar==='­'){obj.hyphenchar=String.fromCharCode(173);}hyphen=obj[key];}break;case'urlhyphenchar':if(obj.hasOwnProperty('urlhyphenchar')){if(assert('urlhyphenchar','string')){urlhyphen=obj[key];}}break;case'togglebox':if(assert('togglebox','function')){toggleBox=obj[key];}break;case'displaytogglebox':if(assert('displaytogglebox','boolean')){displayToggleBox=obj[key];}break;case'remoteloading':if(assert('remoteloading','boolean')){enableRemoteLoading=obj[key];}break;case'enablecache':if(assert('enablecache','boolean')){enableCache=obj[key];}break;case'enablereducedpatternset':if(assert('enablereducedpatternset','boolean')){enableReducedPatternSet=obj[key];}break;case'onhyphenationdonecallback':if(assert('onhyphenationdonecallback','function')){onHyphenationDone=obj[key];}break;case'onerrorhandler':if(assert('onerrorhandler','function')){onError=obj[key];}break;case'onwarninghandler':if(assert('onwarninghandler','function')){onWarning=obj[key];}break;case'intermediatestate':if(assert('intermediatestate','string')){intermediateState=obj[key];}break;case'selectorfunction':if(assert('selectorfunction','function')){selectorFunction=obj[key];}break;case'safecopy':if(assert('safecopy','boolean')){safeCopy=obj[key];}break;case'doframes':if(assert('doframes','boolean')){doFrames=obj[key];}break;case'storagetype':if(assert('storagetype','string')){storageType=obj[key];}break;case'orphancontrol':if(assert('orphancontrol','number')){orphanControl=obj[key];}break;case'dohyphenation':if(assert('dohyphenation','boolean')){Hyphenator.doHyphenation=obj[key];}break;case'persistentconfig':if(assert('persistentconfig','boolean')){persistentConfig=obj[key];}break;case'defaultlanguage':if(assert('defaultlanguage','string')){defaultLanguage=obj[key];}break;case'useCSS3hyphenation':if(assert('useCSS3hyphenation','boolean')){css3=obj[key];}break;case'unhide':if(assert('unhide','string')){unhide=obj[key];}break;case'onbeforewordhyphenation':if(assert('onbeforewordhyphenation','function')){onBeforeWordHyphenation=obj[key];}break;case'onafterwordhyphenation':if(assert('onafterwordhyphenation','function')){onAfterWordHyphenation=obj[key];}break;default:onError(new Error('Hyphenator.config: property '+key+' not known.'));}}}if(storage&&persistentConfig){storeConfiguration();}},run:function(){var process=function(){try{if(contextWindow.document.getElementsByTagName('frameset').length>0){return;}autoSetMainLanguage(undefined);gatherDocumentInfos();prepare(hyphenateLanguageElements);if(displayToggleBox){toggleBox();}}catch(e){onError(e);}};if(!storage){createStorage();}runWhenLoaded(window,process);},addExceptions:function(lang,words){if(lang===''){lang='global';}if(exceptions.hasOwnProperty(lang)){exceptions[lang]+=", "+words;}else{exceptions[lang]=words;}},hyphenate:function(target,lang){var hyphenate,n,i,lo;lo=Hyphenator.languages[lang];if(Hyphenator.languages.hasOwnProperty(lang)){if(!lo.prepared){prepareLanguagesObj(lang);}hyphenate=function(word){var r;if(urlOrMailRE.test(word)){r=hyphenateURL(word);}else{r=hyphenateWord(lo,lang,word);}return r;};if(typeof target==='object'&&!(typeof target==='string'||target.constructor===String)){i=0;n=target.childNodes[i];while(!!n){if(n.nodeType===3&&n.data.length>=min){n.data=n.data.replace(lo.genRegExp,hyphenate);}else if(n.nodeType===1){if(n.lang!==''){Hyphenator.hyphenate(n,n.lang);}else{Hyphenator.hyphenate(n,lang);}}i+=1;n=target.childNodes[i];}}else if(typeof target==='string'||target.constructor===String){return target.replace(lo.genRegExp,hyphenate);}}else{onError(new Error('Language "'+lang+'" is not loaded.'));}},getRedPatternSet:function(lang){return Hyphenator.languages[lang].redPatSet;},isBookmarklet:function(){return isBookmarklet;},getConfigFromURI:function(){var loc=null,re={},jsArray=contextWindow.document.getElementsByTagName('script'),i,j,l,s,gp,option;for(i=0,l=jsArray.length;i<l;i+=1){if(!!jsArray[i].getAttribute('src')){loc=jsArray[i].getAttribute('src');}if(loc&&(loc.indexOf('Hyphenator.js?')!==-1)){s=loc.indexOf('Hyphenator.js?');gp=loc.substring(s+14).split('&');for(j=0;j<gp.length;j+=1){option=gp[j].split('=');if(option[0]!=='bm'){if(option[1]==='true'){option[1]=true;}else if(option[1]==='false'){option[1]=false;}else if(isFinite(option[1])){option[1]=parseInt(option[1],10);}if(option[0]==='togglebox'||option[0]==='onhyphenationdonecallback'||option[0]==='onerrorhandler'||option[0]==='selectorfunction'||option[0]==='onbeforewordhyphenation'||option[0]==='onafterwordhyphenation'){option[1]=new Function('',option[1]);}re[option[0]]=option[1];}}break;}}return re;},toggleHyphenation:function(){if(Hyphenator.doHyphenation){if(!!css3hyphenateClassHandle){css3hyphenateClassHandle.setRule('.'+css3hyphenateClass,css3_h9n.property+': none;');}removeHyphenationFromDocument();Hyphenator.doHyphenation=false;storeConfiguration();toggleBox();}else{if(!!css3hyphenateClassHandle){css3hyphenateClassHandle.setRule('.'+css3hyphenateClass,css3_h9n.property+': auto;');}hyphenateLanguageElements('*');Hyphenator.doHyphenation=true;storeConfiguration();toggleBox();}}};}(window));if(Hyphenator.isBookmarklet()){Hyphenator.config({displaytogglebox:true,intermediatestate:'visible',storagetype:'local',doframes:true,useCSS3hyphenation:true});Hyphenator.config(Hyphenator.getConfigFromURI());Hyphenator.run();}Hyphenator.languages['en-gb']={leftmin:2,rightmin:3,specialChars:"",patterns:{3:"sw2s2ym1p2chck1cl2cn2st24sss1rzz21moc1qcr2m5q2ct2byb1vcz2z5sd3bs1jbr4m3rs2hd2gbo2t3gd1jb1j1dosc2d1pdr2dt4m1v1dum3w2myd1vea2r2zr1we1bb2e2edn1az1irt2e1fe1j4aya4xr1q2av2tlzd4r2kr1jer1m1frh2r1fr2er1bqu44qft3ptr22ffy3wyv4y3ufl21fo1po2pn2ft3fut1wg1ba2ra4q2gh4ucm2ep5gp1fm5d2ap2aom1cg3p2gyuf2ha2h1bh1ch1d4nda2nhe22oz2oyo4xh1fh5h4hl2ot2hrun1h1wh2y2yp2aki2d2upie22ah2oo2igu4r2ii2omo1j2oiyn1lz42ip2iq2ir1aba4a2ocn3fuu4uv22ix1iz1jay1iy1h2lylx4l3wn5w2ji4jr4ng4jsy1gk1ck1fkk4y5fk1mkn21vok1pvr44vsk1t4vyk5vk1wl2aw5cn2ul3bw5fwh2wi2w1m1wowt4wy2wz4x1an1in1rn1ql3hxe4x1hx1ill24lsn3mlm2n1jx1ox3plr4x5wxx4",4:"d3gr_fi2xy3ty1a2x5usy5acx1urxu4on2ielph2xti4ni2gx4thn2ilx1t2x1s25niql3rix4osxo4n1logn2ivx5om1locl3ro2lo_l3nel1n4_hi2l5rul1mexi4pl1max3io_ex1l1lu_ig3ll5tll3sll3p_in14n2kl1loll3mn3le_ew4n1n4nne4l1lixi4cll3fn3nil1lal5skls4p_eu14no_l4ivx3erx3enl1itx1eml1isx5eg3lirli1qxe2d3lik5lihx1ec1lig4y1bn1oun4ow4li_x3c4yb2il1g2l2fox2as1leyn3p42lev1letx2ag4ni_l1te_es1nhy2yc1l4n1sw3tow5tenho4ns2cwra42lerle5qn2si3womwol4l1try1d4lek42ledwl1in3suw3la4le_l3don1teldi2nth2lce4yda4l1c2l1tu4lu_l4by_od4lbe4lu1a4laz_oi4l4awnt2iwes4l4aul4asn2tjla4p_or1n1tr5wein1tun2tyn1h2w4ednu1awe4b5nuc_os13nudl4all4af_ov4w3drl4aey3eenu3iw1b45nukl4ac5laa4la_4lue3kyllu1in1gu4wabn1go_ph2v5vikur5_en12vv2ks4ty3enk3slv5rov5ri4k1sk3rung1n2vowy1erkol4ko5a4vonk2novo2l2vo_5lupn2gingh4k3lok3lik3lak2l2ng2aki4wvi2tkis4k1inki2l5kihk3holu1vke4g3kee4kedkdo4_sa2k5d2_eg4k1b4kav4kap4vim4ka3ovi4lk4ann3v2nve2vic2ka4lju1v4vi_ju5ljui4_sh2ygi2nfo4_st44jo_3jo2jil43jigl4vi2vel3veive3gjew3jeu42ve_4jesjeo2y3gljal43jac2ja__th44ly_2izz_ti22izo_do2i5yeix3oy3in2i1wn2x4i2vov4ad2ny25nyc5vacn1z24va_nzy4uy4aux2o2oa2o3ag2ivauve2u4vayle2i3um2ittly1c4obau3tu2itrob2i4obo_up12ithob5tuts2lym2ut2o_ve2oc2ait1a2isyo1clo1crut2ioct2is1pis1lo1cy4usto2doo2du4isblyp2n4ew2ab_2abai4saoe3a2abbus1pir2sir4qoe4do5eeir1ioep5o5eqo3er2usco1etir1a3lyr3lywipy43oeuo3evi3poab1ro3ex4ofo2o1gur1uo2ga2abyac2a3lyzi5oxo3gii3oti1orioe4ur2so2gui1od2io22acio1h2ur1o2inuo3hao3heohy44ma_oi4cins24inqoig4ac1r2ino2inn4inl4inkur1ioi4our2f4oisoi4t2iniynd4ok3lok5u2ind2inco1loyn2eo1mai2moom1iur2ca2doim1iil3v4iluon1co2nead1ril3f4onh2ik24iju4adyae5aija4i5in4aed2mahae5gihy4ae5pur1aae4s2i1h4igions2i1geyng42ont4af_4afe5maka4fui3fyu2pri3foon2zn1eru4po4agli2fe2i1foo1iu1ph4ieua2groo4moo2pyn4yi1er4iemie5ia1heah4n4iec2ai24ai_ai3aa1icne2p4idraig2oo2tu1peo1paop1iy1o2u1ouu3os4oplid1ayo3d2icuop1uor1a2ick4ich2a1ja4ju2mam4iceak5u4ibuunu44iboib1i2oreiav4i3aui3atun5ror1iun5o2alei5aii3ah2unniaf4i5ae2ormhy4thyr4hy3ohyn4hy2m2orthy2l1man2nedhuz4un2ihu4gh1th4alko1sch4skhsi42mapu1mu2h1shry4hri4hre41mar4h1pum2ph2ou4osp4osuy2ph4oth4ho_u1mi2h1mh1leh3la2ne_h4irhi2pu1mao4u2oub2h1in2a2mhi4l4oueu1lu2ulsoug4h1ic2hi_u1loul3mnde24ulln2daheu2ul2iou3mam1ihet12ounhep1ow1iows4ow5yyp1nox3ih4eiox5oypo1oy5aoys4u1la4ul_am2pu2izmav4h2ea4he_y2prhdu42m1ban2ao1zo_ch4mb4dy5pu4pa_ha4m1paru2ic5pau2ui2h4ac4ha_u4gon1cug5z2uft43gynu4fou3fl3ufa5gymmb2iue4tgy2b4anhnc1t2g1w5paw3gun2p1bu4edueb4p1c42guep5d2an1og5to2pe_gs4tgs4c2g1san2s2ped3grug4rou2dog4reud4g1gr2n1crgov12gou3gosud4e3goop4ee3goe5god3goc5goa2go_pe2fg2nog1niuc3lg1na2gn2an2y2pes3gluyr4r3pet5aowyr4s4ap_4apa3glo4pexyr5uu4ch2gl24y2s5gip2me_3gioap1i2ph_gi4g3gib4gi_uba41g2igh2tg3hoa2prphe44aps2medg2gegg4ame2g2g1gy3shu1alua5hu2ag2g1f3get2ua2ph2lge4o1pho2tz23gen4phs1gel1typ4gef2ge_g5d4me2m1phug1at4pi_p2iety4a4ty_p2ilt3wopim23gait2wi3gagn3b44ga_5piqar3har1i1tutfu4c4fu_1menp2l23tunna2vfs4p2f3s1pla1fr2tu1ifo3v4tufp4ly2p1myso53foo2arrme4par2stu1afo2n4tu_4po_t2tytt5s3pod2aru4poffo2e3foc4fo_ar5zas1ays1t3flu2asc3flo3flan2asas2et3ti2fin5poypph44f5hf3fr1pr2f1fif1fena5o3feufe4t4pry2ps22asotta4p3sh5fei3fecass2p1sits2its4ht2sc2fe_4t1s2f5d4f5b5faw5farp1st2pt2as1u2fa_1f2aeyl44ey_1expe1wre3whe1waevu4p4trp1tupub1puc4p4uneus44eumeuk5eue4p4uset5zyzy4z1a14p1wet2t2p4y4tovpy3e3pyg3pylpy5t2za__av44ra_r2adras2et2ae1su1namr2bat1orr2berb2ir1c2r2clrct4nak24re_rea4e2sc4es_2erza2to5tok2erurei4erk44erj1tog3toere1qre1vza2irf4lr1g2r2gez4as4ri_2ereto1b2erd2to_2erc4m3hri3ori5reph14mi_2au24au_m1ic4auc4t3me1paeo3mt1lieo2leof2eo3b4enur1lar1leaun2r1loen2sen1ot1laen3kzeb4r1mur2n24ene2end3tiurn5nrnt4ze4d4ro_r2od4roiroo4r2opelv4e1lur4owti4q1tip4roxrpe2r2ph1tior3puaw1i5nahaw5y4mijr3ri_as12eleay3mayn4ays2r5rurry5ek4l2az2m2ilaze4e2ize2iv4eis2ba_t1ineig24eifeid45bahba4ir2seehy21timeh5se5hoe1h2e2gr2efuef4lna2ceep1ee2mee1iee5gee2fr3su2na_rt3ced4g1basede23mytr1turu3ar2udr4ufe1clru2le1ceru2pb1c2ec2a2b1deb2te2bre4bl3myi4be_3beaeb2iebe4eb2b2bedzib5r1v2r2veeau3t1icmy3e5bee3bef2r2yry2tz2ie1bel2sa_2sabeap25saebe3meak1ea4gsa4g3sai4ti_5sak4beobe3q4eabmy4dd3zo3dyndyl25dyksa2l2d2y2d1wsa4mbe3w2b1fbfa44b1hb4ha2bi_1biazi5mdu3udu2ps3apb4ie3ducbif42ths2du_z4isb1ilmi3od4swds3m4bimd5sl1saumi3pz3li3dox4s3bd4osd2or3doosby3bip4bi5qbir44zo_s1cab2iss1cedo4jd4ob4do_5zoa2d1mmtu4d5lu2bl2d1losch2d1la2dl4tha42th_m5si4m1ss2co2t3f1diu2se_se2a4bly2b1m3texbmi44b1nm4ry4bo_3boa2sed5bobdil4bo5h3sei1didse2p1dia4di_d4hu3bon4d1hxys4dg4ami2t2d5f1boo3dexs2es1set3sev3sex3sey2s1fsfi4_an1d3eqde1ps4idsif4bow2si4g2sin5boyzo5p3sipde3gs1it3dec2de_d3di2tep3miute2od1d4d3c4zot23davs2k24sk_d1atske2d3ap4sksd1agb3sc2sl44da_5zumb5sicy4tbso2te2ltei4cys4cy4m2b1tcyl34bu_5bubte2g1cyc2cy_bun2cu5v5cuu1cuss2le1curt4edc4ufc1tyc1tu4te_c1trs1n2s2na2so_t1ca5mix4b3w4zy_4by_3byibys45byt2ca_2tc23soes2olc1te5cafsos45cai5cakc1al3sou4t3bt4axc2ta4m1lcry2sph2s1plc2res2pos4pym3pum3pocoz4cov14mo_sre22moc5cao1caps1sa3cooss3mcon11cars4sns1sos1su1takss3wmod13coe4st_1tai3tah3coc3coa4co_taf4c3nim2pist3cc1atste2mo1mc4kem4ons1th2cim3cau2tab2ta_3cayc1c44stl3cilc3ch3syn4cigci3f4ce_4ci_3chrs1tu1cho2ced4chm1sylch5k4stw4cefce5gs4tysy4d4su_sug3sy1c3sui4ch_m3pa2cem4sy_cew4ce2t1cepsu5zm4op2swo2s3vzzo3",5:"n5tau2cenn3centsves45swee5cencsu5sus4urg1cen2sur3csu5pe3cerasun4a3cerdsum3i5cern5cesss4u2m1s2ulce4mo3cemi4celysy4bi4chab3chae3chaisui5ccelo45cellchec44ched3chee3chemsuf3fch1ersu3etsud4asuct44chessubt2ch5eusu4b13chewch5ex5chi_3chiasu5ansy4ce1styl3ceiv3chio5chip3cedi3cedestu4m5cedace4cicho3a5choc4chois4tud3chor3ceas2st3sstre43chots2tou3stonchow5cean3chur43chut5chyd3chyl3chym1c2i24ceab4ciaccia4mci3ca4cids4cie_ci3ers4toeci5etccle3cifi4ccip4ci3gast3lisyn5esyr5icat4ucim3aci3mes5tizs4thu4cinds4thac4atss4tec4cintci3olci5omci4pocisi4cit3rt2abockar5cka5tt5adeck5ifck4scc2atcs4teb3clasc2le22cle_c5lecc4at_clev3cli1mtad4icli2qclo4q4stakclue4clyp55clystad2rtae5n1c2o2case5car4vco5ba3tagrco3cico5custab23tail4cody2tairco5etco3grcar5mt4ais4col_col3atal2css5poco5lyta3lyco4met4anecomp4cap3uta4pass5liss1ins1sifs1siccon3scon3ts3siacapt4coop4co3orcop4eco3phco5plco3pocop4t2corassev3s5seus1sel1tard3corn4corotar3n5cort3cos_sre4ssreg5co5ta3tarr5cotytas3it3asmco3vacow5a5tassco5zic4anotas4t5craftat4rc4ran5spomcam4is4plysple2ca3maca3lys2pins2pids3phacal4m4speocri3lcron4so3vi4crousov5et5awacrym3cryo34c5s4csim5tawn43calcc3tacc4alaso5thct1an4soseca3gos3orycad4rc4teasor3os2o2ps4onect5esct5etct2ics2onaso3mo1so2mc3timsol3acaco3c4acesody4sod3oc5tio2s3odc3tittcas4tch5u4t1d4smo4dsmi3gc1tomc3tons3mensmas4b3utec2tres3man3bustc2tumte3cr2s1m4buss2s5lucslov5c2ulislo3cs3lits5leycu4mi5cunacun4e5cuni5cuolcu5pacu3pic3upl4tedds3lets5leabur3ebunt4cus5a3slauc3utr4tedobun4a4teeicy4bib4ulit3egoteg1rcy5noteg3us1latbsin41tellbsen4d4abr1d2acdach43tels3dact4b1s2sky3ld4aled4alg4bry_dam5a3damed3amida5mu3dangs5keybrum4d3ard5darms3ketbros4tem3as5kardat4ub4roa4teme4tenet5enm4tenob2ridteo5l4bre_5sivad3dlid3dyite3pe4s1ivde5awde4bisi4teb2ranbram44sismde1cr4dectded3i4sishs1is24bralde4gude3iosi4prtep5i4sio_1sio45sinkde5lo1d4emsin3is2ine4boxy1silibow3ssif5f4demybous4den4d4dened3enh4sidssi4de4sid_3bourde3oddeo3ldeon2si4cu5terd3sicc4s1ibde2pu5botishys44shu4d4eres3hon5shipsh3io1derider3k3dermsh5etsh1er4shab1teri2s1g4der3s5deru4des_de3sa5descbor4nter5k3terrdes4isexo23borides1psewo4de3sq2t2es5seum1de1t4tes_de5thde2tise5sh4ses_bor3d3septsep3atesi4t3esqdfol4tes4tteti4dgel4d4genbon4ebon4cdhot4bol4tbol3itet1rdi2ad3diarbol4e4d1ibd1ic_3sensdi4cedi3chd5iclsen5g1dictsem4osem2i5self4sele4boke5selasei3gd4ifo2boid3seedbod5i5dilldilo4di3luse4dabo5amdi1mi2d1indin4ese2cosec4a3di1odio4csea3wdip5t3diredi3riseas4di4s1d4iscs4eamb3lis3dissbli2q2s1d22s1cud3itos4coi2ditybli3oscof44blikscid5dix4i3bler4the_b3lan5dlefblag43dlewdlin45blac4b5k4bi5ve4d1n24bity4thea4thed4sceidog4abis4od4ol_s4ced5bismscav3sca2pd4ols5dom_1thei3theobi3ousbe4sdo5mos4bei4donybio5mbio3l4dor_dor4mdort41bi2ot4hersavi2dot1asaur52dousd4own4thi_th5lo2thm25binad3ral3dramdran4d4rassat1u3dreldres4sa2tedri4ed4rifs2a1td4romsas3s3sas_4d1s2th4mi3thotds4mi1th2rb2iledt5hobigu3bi5gadu1at5thurduch5sar5sdu4cosap3rbid5idu5en2santdu5indul3cd3uledul4lsan3adun4asamp43b2iddu3pl5durod5usesam5o5thymbi4b1dver2be3trsa3lube3sl3sale2bes_be1s2dy5ar5dy4e3thyrber5sdyll35dymi5berrdys3pberl4thys42beree1actbe5nuea5cue5addbe1neead1i1ti2ati3abben4deal3abel4tsad5osad5is3actean5i2t3ibsac4qe3appear3a5sacks3abl2belebe3labe3gube5grryp5arym4bry4goeas4t5rygmry5erbe3gobe4durvi4tr3veyr3vetr3vene4atube4doeav5ibed2it3ic_eaz5ibe3daebar43becube3caru3tirus4pe2beneb5et4bease5bile4bine4bisbdi4ve4bosrur4ibde4beb1rat2icie4bucru3putic1ut3id_run4trun4ge5camrun2eec3atr4umib3blir4umeech3ie4cibeci4ft4ida2b1b2ru3in3tidirue4lt5idsru4cerub3rr4ube1tif2ec1ror4tusti3fert5sirto5lr1t4oec1ulrt3li4tiffr2tize2dat3tigie4dede5dehrt3ivr2tinrth2ir5teue3deve5dew5barsr5tetr1ted4tigmr3tarrta4grt3abed1itedi2v5tigued3liedor4e4doxed1ror4suse2dulbar4nrs5liee4cers3ivee4doti4kabar4d5barbr4sitba4p1r3sioeem3ib4ansee4par4sileesi4ee3tot4illr5sieefal4rs3ibr3shir3sha5bangr3setb4anee4fugrsel4egel3egi5ae4gibe3glaeg3leeg4mir3secr3seat4ilte5gurban4abam4abal5utim1abal3abag4a5eidobaen43backr4sare4in_e3ince2inee1ingein5ir2sanei4p4eir3oazz4leis3ir2saleith4azyg4r4sagaz5eeaz3ar2r1s2ek3enek5isayth4e4lace5ladr3rymelam4r3ryi3tinnay5sirro4trrog5rrob3ay5larric4ax2idrrhe3rre2lele3orrap4el1ere1lesrra4h4r1r44tinst4intrpre4el5exrp5ise1lierph5ee3limav1isti3ocrp3atav3ige3livavas3r4oute3loae3locroul35rouero3tue2logro1te4rossr4osa4roreel3soror5dav5arelu4melus42t1ise5lyi3elytr4opr4rop_emar4tis4c5root1roomem5bie1me4e4meee4mele3mem3tissro1noro3murom4pe4miee2migro3lyro3laroid3e3mioro3ictis2te4miuro3gnro1fero3doava4ge2moge4moiro3cuem5om4emon5roccro5bre2morro4beav4abr5nute5mozrnuc4au3thr5nogr3noc3titlem3ume5muten3ace4nalrn3izrni5vr1nisrn3inr3nicrn5ibr5niaenct42t1ivr3neyr3netr3nelaus5pene5den3eern5are5nepe2nerr5nadr3nacrn3abt3iveen1et4aus_rmol4e3newen3gien3icr3mocrmil5en5inr5migaur4o5tleben3oieno2mrm4ieenov3aun3dr2micen3sprme2arm4asr2malr5madr3mac3tlefen2tor4litau3marlat33tlem5tlenen3uaen3ufen3uren5ut5enwa5tlewe4oche4odaaul4taul3ir3keyr3ketrk1ere5olutlin4eon4ae3onteop4te1or1r5kaseor3eeor5oeo1s2eo4toauc3oep4alaub5iepa4t4a2tyr2i4vr2ispris4cep5extmet2eph4ie2pige5pla2t3n2ri5orri4oprio4gatu4mrin4sr4inorin4e4rimse1p4u4rimmr4imbri2ma4rim_at1ulr4ileri2esera4gera4lri3erri5elrid4e2ricur4icl2riceri3boer3be2r2ib2a2tuer3cher3cltoas4ri5apri3am4toccat1ri4ered3r2hyrhos4tod4irgu5frg5lier3enr3gerr3geor5geee3reqer3erere4sa4trergal4r4gagat3rarfu4meret42a2tra5tozatos4ere4ver3exreur4er3glre3unre3tur3esq2res_er2ider3ierere4rer4aer3into5dore5phre1pe3reos3reogre3oce3river5iza3too4atoner3mer4enirene2rena4r3empr5em_re1le4ero_re1lam5ordreit3re3isre1inre3if2atolre2fe3reerree3mre1drre1de2r4ed4atogeru4beru5dre3cure3ce3reavr5eautol4ltolu5es5ames5an4atiure3agre3afr4ea_to5lye3seatom4be5seeat1itese4lr4dolrd3lie1shie5shurdi3ord2inr5digr4dier4desr2dares3imes3inr5dame4sitrc5titon4er5clor4clees4od3tonnrcis2rcil4eso3pe1sorr2cesrca4ston3ses4plr4bumr2bosrbit1r2binrbic4top4er4beses2sor3belrbe5ca4timrbar3e2stirb1anr4baga2tif4toreest4rrawn4tor5pra3sor4asktor4qr2aseras3cati2crare2eta3p4rarcran2tet4asra3mur5amnet5ayra3lyra3grra4de3tos_eter2r2acurac4aetex4e2th1r2abo2etia5rabera3bae5timet3inath5re3tir5quireti4u1quet2que_e2ton4quar5quaktos4ttot5uath3ipyr3etou4fet1ri5tourt3ousath3aet1ro4a2that5etetud4pu3tre4tumet4wetra5q3tray4ater4tre_4trede3urgeur5itren4pur3cpur5beut3ipu3pipun2tpun3i3puncev3atpun4aeve4n4trewpum4op4u4mpu5ere4vese1viapuch4e2vict2rieevid3ev5igpu5be2trilt2rit4trixe4viuevoc3p5tomp3tilata3st4rode4wage5wayew1erata3pew5ieew1inp5tiee3witatam4ex5icpt4ictro5ft2rotey4as2a2taey3s2p5tetp1tedez5ieas5uras4unfab4ip2tarfact2p4tan2f3agp4tad5falopt3abtro1v3psyc3troypso3mt4rucfar3itru3i2t4rytrys42asta3feast4silfeb5ras3ph2fed1as5orfe1lifem3i2t1t4p3sacf5enias4loas4la3feropro1l4pro_3ferrfer3v2fes_priv24priopren3aski43prempre1dfet4ot3tabpreb3as5iva3sit4pre_f5feta5siof5fiaf3ficf5fieffil3prar4ff4lepra5dffoc3prac1as3int5tanppi4ct5tast3tedfib5u4fic_ppet33fici4ficsppar34p1p2fiel4asep4p5oxi1fi2l4asedfin2apo1tefind3fin2ef1ing3p4os3portpor3pf3itapo4paas2crt3tlifle2s2ponyflin4t5toip4o2nasan2pom4eas4afa5ryta3ryot5torar3umt3tospo3caar2thar3soar2rhar4pupnos4tu5bufor5bar3oxtu5en5formplu2m2plesaro4ntu4is3plen3plegfrar44ple_fre4sar3odfruc42tum_3tumi4tumsf1tedtun4aft5es2p3k2p2itutu4netur4dtur4npis2sfug4ap4iscfun2gp4is_fur3npir4tfus5oar3guar5ghpi4pegadi4pip4at3wa4ar3en3gale3pi1op4innpin4e3galot3wit5pilo3piletwon4pig3n5tychpict4g5arcg4arepi4crpi3co4picagar5p5garr1ga4sgas5igas3o3piarar4bl3phyltyl5ig4at_2phy_phu5ity5mig4attgat5ugaud5ga5zaar3baara3va3rau5geal3gean2ge4d3gedi5gednar1at3type4gelege4li1tyr13phrage4lu2gelygem3i5gemoara3mph3ou3phorgen3oa3rajt5ziat5zie4gereph1is2ges_5gessphi4nua3ciget3aara2ga5quia5punua5lu1philg3ger4phic3phibg3gligglu3g5glyph3etg4grouan4og5haiuar3auar2dg4hosuar3iap5lia5pirph2angi4atu1b2igi5coap3in4phaeub5loub3ragi4orgi4otaph3igi5pag4i4s5gis_gi2t15gituu1c2aa5peug3laru5chrglec43glerap3alpe4wag4leypet3rpe2tia1pacaol3iglom34glopa5nyian5yap4ery3glyp2g1m4a5nuta3nurg4nabper3vp4eri4pere5percpe5ongn5eegn3eru4comg4niapen5upel5v4pelean3uluco5tgno4suc2trant4ruc3ubuc5ulu5cumgo4etgo4geu5dacg5oidgo3isgo2me5gonnpe2duud1algoph44gor_5gorg4gorsg4oryud5epgos4t1anth3pedsg1ousan2teu4derudev4grab43gram3pedigra2pudi3ogril43pedeu5doigro4gg5rongrop4ud5onan3scgru5ipe4coan5otan2osanor3g4stiu5doran2oeg4u2agu5ab5guan4annyg5uatan5no5gueu4aniuuen4ogu2magu4mi4anigpawk4uer3agur4ngur4u4gurypau3pani3fan3icues4san3euan4eagyn5ouga4cug2niug3uluhem3ui3alp5atohae3opas1t1p4ashag5uha5ichais4par3luid5ouil4apa3pypap3uhan2gpa3pepa4pahan4tpan3iha4pehap3lhar1ahar5bhar4dpan1ep4alspa3lohar3opain2paes4pad4rhat5ouil4to3zygozo5ihav5oana5kuin4san3aeuint4amyl5am3ului5pruis4t1head3hearui3vou4laba3mon4ulacu5lathe3doheek4ul4bohe3isul3caul4ch4uleaow5slow5shu5leehem1aow5in3amidow5hahem4pow1elhe3orulet4h1er_owd3lher2bowd4io5wayow3anow3ago1vish5erho5varouv5ah1erlouss42ouseh1ersoun2dul4evami2cul2fahet3ioul4tul4iaheum3ou5gihe4v4hev5ihex5oa3men3ambuu5lomhi4aram1atou5gaul4poh4iclh5ie_h1ierou3eth1iesama4gh3ifyhig4ohi5kaa5madoud5iou5coou5caa5lynhin4dou5brul1v45ou3aalv5uh2ins4o1trh4ioral1vahip3lum3amhir4ro4touhit4ahiv5aumar4u5masalu3bh3leth1l2ihli4aum2bio1t2oot4iv2h1n2o5tiaal3phho3anho4cou4micho5duho5epo4tedhold1o3taxo3tapot3ama5lowh2o4nos1uru4mos4ostaos4saos1pihon1o1hoodhoo5rh4opea4louo5sono5skeh4orno4sisos1inos5ifhosi4o3siaalos4os5eual1ora3looo2seta3lomoser4hr5erhres4um4paos5eohrim4h5rith3rodose5ga5loeo3secumpt4un5abun4aeht5aght5eeo4scio2schos4ceos4caht5eoht5esun2ce4aliuosar5un3doos3alosa5iory5phun4chunk4hun4thur3ior4unu1nicun4ie4or1uun3inal1in5aligal3ifal1iduni5por4schy1pehy3phuni1vor1ouun3iz2i1a2ia4blo5rooorm1ii2achiac3oa2letork5a5origa1leoun3kni2ag4ia3gnor3ifia3graleg4a3lec4ori_al3chor5gn4ialnor4fria5lyi5ambia3me5orexi3anti5apeia3phi2ardore4va5lavor3eiore3giat4uore3fal3atun3s4un5shun2tiibio4or4duib5lia1laei4bonibor4or4chi5bouib1riun3usoram4ic3acor5ali4calic1an2icariccu4akel4i5ceoa5ismich4io5raiora4g4icini5cioais1iic4lo2i2coico3cair3sair5pi5copop2ta2i1cri4crii4crui4cry1op1top5soopre4air5aop2plic3umopon4i5cut2i1cyuo3deain5oi5dayide4mo4poiain3iu1pato1phyid3ifi5digi5dili3dimo4pheo1phaidir4op1ero5peco4pabidi4vid3liid3olail3oai5guid3owu5peeid5riid3ulaid4aa5hoo2ieg2ie3gauper3i5ellahar22i1enien2da1h2aoo4sei2erio3opt4iernier2oi4erti3escagru5oon3iag3ri2i1eti4et_oo4leag5otook3iiev3au5pidiev3o4ag1nagli4if4fau5pola5giao5nuson5urifi4difi4n4i2fla5gheifoc5ont4rupre4af5tai3gadaev3a3igaraeth4i3geraet4aono3saes3ton5oionk4si3gonig1orig3oto1nioo5nigon3ifig1urae5siae3on4ura_aeco34uraead3umura2gik5anike4bi2l3aila4gon4id4a2duil4axil5dril4dui3lenon4guuras5on1eto3neoon1ee4oned4oneaad1owon5dyon3dril1ina3dos4onauon3aiil5iqona4do2mouil4moi5lonil3ouilth4il2trad3olil5uli5lumo4moi4adoi4ilymima4cim2agomni3im1alim5amom2naomme4om2itomil44adoeomi2co3mia3adjuome4gurc3ai5mogi3monim5ooome4dom4beo3mato2malo2macim5primpu4im1ulim5umin3abo4mabur4duadi4p4olytina4lol1ouin5amin3anin3apo3losol1or4olocur3eain3auin4aw4adilol3mia5difolle2ol2itolis4o5lifoli2eo1lia4inea4inedin5eeo3leuol1erine4so3lepo3leo4ineuinev5ol5chol4an4infu4ingaola4c4ingeur5ee4ingiad4haur1er4ingo4inguoith44adeeada3v4inico3isma5daiur3faac2too3inguril4ur1m4ac3ry4ino_in3oioil5i4inos4acou4oideo2i4d4acosurn5soi5chinse2o3ic_aco3din3si5insk4aco_ac3lio3ho4ack5aohab34acitacif4in5ulin5umin3unin3ura4cicuro4do5gyrur5oturph4iod5our3shio3gr4i1olio3maog4shio3moi5opeio3phi5opoiop4sa5cato4gro4ioreo2grio4got4iorlior4nio3sci3osei3osii4osoog2naur5taiot4aio5tho4gioio5tri4otyur1teo5geyac3alurth2ip3alipap4ogen1o3gasip1ato3gamurti4ur4vaofun4iphi4i4phuip3idi5pilip3ino4fulipir4ip5isab1uloflu42abs_ip3lou3sadi4pogus3agi4pomipon3i4powip2plab3omip4reoet4rip1uli5putus3alabli4i3quaab3laus4apoet3iira4co4et_ir4agus3atoes3t4abio2abiniray4ird3iire3air3ecir5eeirel4a3bieires4oelo4ab1icoe5icir4ima3bet5irizush5aoe5cuir5olir3omusil52abe4ir5taoe4biabay4us4pais5ado5dytis1alis3amis1anis3aris5av_za5ri2s3cod3ul_xy3lod5ruo3drouss4eod3liis2er5odizod5it4iseuod4ilodes4o5degode4co5cyt2isiais5icis3ie4isim_vo1c4isisis4keus1troc5uo2ismais1onocum4iso5pu5teooc1to5ispr2is1soc2te_vi2socre3u3tieiss4o4istao2cleu3tioo5chuoch4e4istho4cea4istloc5ago3cadis1tro4cab4istyi5sulis3urut3leutli4it5abita4c4itaiit3am_vec5it4asit3at_ur4oit3eeo3busob3ul_ura4_up3lo3braith5io5botith3rithy52itiao5bolob3ocit1ieit3ig4itim_un5uob1lio3blaob3iti5tiqut5smit3ivit4liit5lo4ito_it5ol2itonit1ou_un5sobe4lu4tul_un3goat5aoap5ioan4t4itueit1ulit1urit3us2i1u2_un3eiur5euven3oal4iiv1ati4vedu5vinoad5io3acto5ace_ul4luy5er2v3abives4iv3eti4vieiv3ifnyth4va1cavacu1iv1itva4geivoc3vag5rv1al_1vale_tor1vali25valu4izahiz3i2_til4iz5oivam4i_tho4va5mo5vannnwom4jac3ujag5u_te4mja5lonwin44vasev4at_jeop34vatuvect4_ta4m4velev1ellve1nejill55jis_4venu5ve3ojoc5ojoc5ujol4e_sis35verbju1di4ves__ses1ju3ninvi4tjut3a_se1qk4abinvel3kach4k3a4gkais5vi1b4vi4ca5vicuvign3vil3i5vimekar4i1kas_kaur42v1invin2evint4kcom43vi1oviol3kdol5vi5omke5dak5ede_rit2_rin4ken4dkeno4kep5tker5ak4erenu1trker4jker5okes4iket5anu4to5vi3pkfur4_re3w_re5uvire4kilo3vir3uk2in_3kind3nunc5numik3ingkin4ik2inskir3mkir4rv3ism3kis_k1ishkit5cvit2avit1rk5kervi3tu_re5ok5leak3lerk3let_re1mv3ity_re1ivi5zovolv41know3vorc4voreko5miko5pe3vorok5ro4_po2pv5ra4vrot4ks2miv3ure_pi2ev5verwag3owais4w3al_w3alswar4fwass4nu1men3ult5labrwas4tla2can4ulowa1tela4chla2conu4isw4bonla3cula4del5admw5die_out1nug4anu3enlag3r5lah4nud5i_oth54lale_osi4_or2o_or4ilam1ol5amu_ore4lan2d_or3dn5turntub5n3tua3weedweir4n5topwel3ilapi4n3tomn1t2o_op2i_on4ent3izla4tenti3pn3tign1tient4ibwent45laur_ome2_ol4d_of5twest3_oed5l4bit_ob3lw5hidl2catwid4elcen4n1thelch4el3darl3dedl3dehwi5ern4teol5dew_no4cl3dien3teln4tecwim2pld5li_ni4cwin2ecen3int1atnt1aln3swale3cawl1ernsta4_na5kle5drleg1an3s2t3leggn5sonleg3ons3ivwl4iensi2tlel5olelu5n3sion3sien3sid5lemml3emnle2mon4sicns3ibwon2tn3sh2n5seule1nen2seslen3on5seclen5ule3onleo4swoun4wp5inn4scun2sco_mis1_mi4enre3mnre4ix4ach4les_x4adenpri4x3aggnpos4npla4npil4leur5x3amil3eva5levexan5dle4wil5exaxano4lf5id_lyo3lf3on_lub3l4gall4gemlgi4al4gidl4goixas5pxcav3now3llias4lib1rl1ic_5lich_lo2pnove2nou5v2nousli4cul3ida3nounn4oug3lieul4ifel4ifoxcor5_li4p3notenot1a_li3oxec3r1l4illil4ilim2bno3splim4pnos4on4os_lin4dl4inenor4tn4oronop5i5nood4noneno2mo1nomi3linqnol4i3liogli4ollio3mliot4li3ou5liphlipt5x5edlx5edn_le2pl4iskno3la_le4ml2it_n5ol_no4fa3lithnoe4c3litrlit4uxer4gn4odyno4dinob4ln5obilk5atxer3on5nyi_ki4ex3ia_nnov3x4iasl5lasl4lawl5lebl1lecl1legl3leil1lellle5ml1lenl3lepl3leul3lev_is4o_is4c_ir3rx5ige_in3tllic4nlet4_in3ol5lie4n1l2l2linnk5ilnk5ifn3keyl5liolli5v_in2ixim3ank5ar_in3dllo2ql4lovnjam2_im5b_il4i_ig1n_idi2llun4l5lyal3lycl3lygl3lyhl3lyil5lymx4ime_hov3_ho2ll4mer_hi3bl5mipni3vox4it__he4ilneo4x4its5loadniv4ax4ode_hab2ni4ten5iss2locynis4onis4l_gos3n4isk4loi_lo5milom4mn4is_lon4expel43nipuni1ou5nioln4inu5ninnnin4jn4imelop4en3im1l3opm1lo1qnil4ax4tednik5e3nignn3igml4os_lo1soloss4_ga4mnift4nif4flo5tu5louplp1atlp3erxtre4l5phe_fo3cl2phol3piel3pitxur4b1y2ar_eye3_ex3a3yardl5samls5an4nicllsi4mls4isyas4i_eur4l1s2tni3ba3niac_es3tl5tar_es3pl4teiyca5mlth3inhyd5y3choltin4lti3tycom4lt4ory2cosnhab3_er2al4tusyder4_epi1luch4_eos5n2gumlu4cu_ent2lu1enlu5er_en3slu4ityel5olu4mo5lumpn4gry_en5c5lune_emp4n5gic_em3by5ettlusk5luss4_el2in5geen4gae_ei5rlut5r_ei3dygi5a_ec3t_eco3l4vorygo4i_dys3_du4c_do4eyl3osly4calyc4lyl5ouy1me4news3_de4wly4pay3meny5metnet1ry5miaym5inymot4yn4cim4acanet3an1est1nessn1escmact44mad_4mada4madsma4ge5magn2nes_yn3erma5ho3ma4i4mai_maid3_der2ner2vner5oyni4c_de1mneon4m3algneo3ln3end4n1enne2moyoun4n4ely2neleyp5alneis4man3a5negune3goneg3a3nedi_dav5m4ansne2coyper3m3aphy4petne4cl5neckn3earyph4en3dyind2wemar3vn4dunndu4bn2doundor4n5docnd1lin3diem4at_n1dicnd4hin5deznde4snde4ln1dedn3deayph3in3damm4atsn3daly4p1iy4poxyp5riyp4siypt3am5becn4cuny3ragm4besyr3atm2bicnct2oyr3icm4bisy5rigncoc4n1c2lm3blimbru4mbu3lmbur4yr3is_can1ys5agys5atmea5gn4cifme4bame4biy3s2c4med_n4cicn3chun3chon3chan5ceyme4dom5edy_bre2n5cetn3cer4melen1c2anbit4nbet4mel4tnbe4n_bov4ys1icys3in3men_2menaysi4o3nautnaus3me1nenat4rnati45meogys4sonas3s4merenas5p2me2snas5iys4tomes5qyz5er1me2tnam4nmet1e3nameza4bina3lyn5algmet3o_aus5_au3b_at3t_at3rza4tena5ivmi3co5nailm4ictzen4an5agom4idina4ginag4ami5fimig5an2ae_mi2gr_as4qmi5kaz5engm3ilanadi4nach4zer5a3millmi5lomil4t3m2immim5iz3et4_ari4_ar4e_ar5d5zic4_ap4i5my3c_any5z3ing3zlemz3ler_an3smu4sem5uncm2is_m4iscmi4semuff4zo3anmsol43zoo2_and2zo3olzo3onzo5op4mity_am2i_al1k_air3_ag5nmlun42m1m2_ag4amp5trmp3tompov5mpo2tmmig3_af3tmmis3mmob3m5mocmmor3mp3is4m1n2mnif4m4ninmni5omnis4mno5l_af3f_ae5d_ad3o_ad3em3pirmp1inmo4gom5pigm5oirmok4imol3amp5idz3zarm4phlmo3lyz5zasm4phe_ach4mona4z3ziemon1gmo4no_ace45most_ab4imo3spmop4t3morpz5zot",6:"reit4i_ab3olmo5rel3moriam5orizmor5onm3orab3morse_acet3_aer3i_al5immo3sta2m1ous_al3le4monedm4pancm4pantmpath3_am5ar_am3pemper3izo5oti_am3phmo4mis_ana3b_ana3s_an5damog5rimp3ily_an4el_an4enmmut3ammin3u_an4glmmet4e_ant3am3medizing5imman4d_ar5abm5itanm3ists_ar5apmsel5fm3ist_5missimis3hamuck4e4misemmul1t2_ar4cimu5niomun3ismus5comirab4mus5kemu3til_at5ar1m4intmin3olm4initmin5ie_bas4i_be3di5myst4_be3lo_be5sm5min4d_bi4er_bo3lo_ca3de_cam5inac4te_cam3oyr5olona4d4amil4adnad4opyr3i4t_car4imid5onn4agen_ca4timid4inmi4cus_cer4imi3cul3micromi4cinmet3ri4naledyp5syfn4aliameti4cmeth4i4metedmeta3tna5nas_cit4anan4ta_co5itnan4to_co3pa4n4ard_co3ru_co3simes5enmer4iam5erannas5tenat5alna5tatn4ateena3thenath4l5mentsn4ati_nat5icn4ato_na3tomna4tosy4peroy4periy5peremend5oyoung5naut3imen4agna5vel4m5emeyo4gisnbeau4_de3linbene4mel3on_de3nomel5een4cal_yn4golncel4i_de3ra_de3rimega5tncer4en4ces_yn5ast3medityn5ap4nch4ie4medieynand5ynago43mediaym4phame5and_de3vem5blern4cles_dia3s_di4atmb5ist_din4anc4tin_dio5cm5bil5m4beryncu4lo_east5_ed5emncus4tmbat4t_elu5sn3da4c3m4attn4dalema3topnd3ancmat5omma3tognde3ciyes5tey3est__em5innd3enc_em5pyn3derlm4atit_en5tay4drouma3term4atenndic5undid5aydro5snd5ilynd4inend3ise_epi3d_er4i4nd5itynd3ler_er4o2_eros43mas1ty4collnd5ourndrag5ndram4n5dronmassi4y4colima3sonyclam4mar5rima3roone3aloma5ronne2b3umar5ol5maran_erot3_er4rima5nilych5isne4du4manic4man3dr_eth3e3m4an__eval3ne5lianeli4g_far4imal4limal3le_fen4dm3alismal3efmal5ed5male24nered_fin3gxtra3vner4r5mal3apxtra5d2mago4ma4cisne3sia5machy_fu5ganes3trmac3adnet3icne4toglys5erxtern3neut5rnev5erlypt5olymph5n4eys_lyc5osl5vet4xter3ixpoun4nfran3lv5atelu5tocxpo5n2_ge3ron3gerin5gerolut5an3lur3olu3oringio4gn5glemn3glien5gliol3unta_go3nolu2m5uxo4matluc5ralu2c5o_hama5l3t4ivltim4alti4ciltern3lt5antl4tangltan3en4icabni4cen_hem5anict5a_hy3loni4diol3phinni4ersximet4lot5atnif5ti_ico3s_in3e2loros4lo5rof_is4li_iso5ml4ored_ka5ro_kin3e5nimetn4inesl3onizl3onisloni4e3lonia_lab4olo5neyl5onellon4allo5gan3lo3drl3odis_la4me_lan5ixen4opnitch4loc5ulni3thon4itosni5tra_lep5rni3trinit4urloc3al5lob3al2m3odnivoc4niz5enlm3ing_lig3anjur5illoc5ulloc3an5kerol3linel3linal5lin__loc3anland5lli5col4liclllib4e_loph3_mac5ulli4anlli5amxa5met_math5llact4nni3killa4balk3erslk3er_lkal5ono5billiv5id_ment4_mi3gr_mirk4liv3erl5ivat5litia5liternois5il3it5a5lisselint5inom3al3lingu5lingtling3i3nonicw5sterws5ingnora4tnor5dinor4ianor4isnor3ma_mi5to_mo3bil4inasl4ina_wotch4word5ili5ger_mon3a5lidifl4idarlict4o_mu3ninova4l5licionov3el_mu3sili4cienow5erli4ani_myth3_nari4le5trenpoin4npo5lale5tra3les4sle3scon4quefler3otleros4ler3om_nast4le5rigl4eric3w4isens3cotle5recwin4tr_nec3tle5nielen4dolend4e_nom3ol5endalem5onn5sickl5emizlem3isns5ifins3ing_nos3tn3s2is4leledle3gransolu4le4ginn4soren4soryn3spirl3egan_obed5nstil4le5chansur4e_ob3elntab4unt3agew5est__oe5sont5and_om5el_on4cewel4liweliz4nt3ast_opt5ant5athnt3ati_or3eo3leaguld3ish_pal5in4tee_n4teesld4ine_pa5tald3estn4ter_n3terin5tern_pecu3war4tel5deral4cerenther5_ped3elav5atlat5usn4tic_ward5r_pend4n4tics_pep3tn3tid4_pi3la_plic4_plos4_po3lan5tillnt3ing_pop5lvo3tar_pur4rn4tis_nt3ismnt3istvo5raclat5al4laredlar5delar5anntoni4lan4tr_re3cantra3dnt3ralviv5orn3tratviv5alnt3rilv5itien5trymlan3etlan4er3landsvi5telland3i3land_lan3atlam4ievi3tal2v5istla4ic_la4gisla3gerlac5on5visiola5cerla5ceolabel4vi5ridlab5ar_re3ta5numerkin5et_rib5anu3tatn5utivkey4wok5erelkal4iska5limk2a5bunven4enven5o_ros3ajuscu4_sac5rjel5laja5panja2c5oi5vorevin5ta_sal4inym5itv5iniz5vinit3vinciiv3erii4ver_iv5elsoad5ervin4aciv5el_oak5ero3alesiv5ancoal5ino5alitit5uar_sanc5oar5eroar4se_sap5ait4titoat5eeoat5eri4tric_sa3vo4i5titob3ing2obi3o_sci3e4itio_it4insit4in_it5icuiti4coi5tholitha5lobrom4it3erait3entit3enci3tectit4ana3istry_sea3si4s1to5vider_sect4oc5ato4o3ce25vict2ocen5ovice3r_se3groch5ino3chon_sen3tvi4atroci3aboci4al5verseis4taliss4ivis5sanis4saliss5adi3s2phocu4luver4neislun4ocuss4ver3m4ocut5ris3incis5horocyt5ood3al_ish3op4ishioode4gao5dendo3dentish5eeod3icao4d1ieod3igais3harod1is2v5eriei2s3etis5ere4is3enis3ellod5olood5ousise5cr4i1secisci5cver3eiver5eaven4tris5chiis3agevent5oir5teeir5ochve5niair4is_ir2i4do3elecoelli4ir5essoe3o4pire5liven4doi5rasoven4alvel3liir4ae_ir4abiv4ellaip3plii4poliip3linip4itiip1i4tip4ine_su5daiphen3i1ph2ei3pendog5ar5v3eleripar3oi4oursi4our_iot5icio5staogoni45ioriz4ioritiora4mvel3atiod3i4ioact4_sul3tintu5m_tar5oin3til_tect45vateein4tee_tel5avast3av5a4sovar4isin3osiin5osei3nos_oi5ki5oil3eri5noleoin3de4vantlvanta4oin4tr_ter4pin3ionin4iciin5ia_oit4aling3um4ingliok4ine4ingleing5hain5galo4lacko5laliinfol4olan5dol5ast_thol45val4vole2c4ol5eciol5efiine5teole4onin3esi4in5eoo3lestin5egain5drool3icao3lice_ti5niol5ickol3icsol5id_va5lieo3lier_tri3dinde3tvager4oli5goo5linaol3ingoli5osol5ip4indes5inde5pin5darollim34vagedol4lyi3vag3ava5ceo4inataol3oido4lona_tro4vi3nas_in4ars_turb44ol1ubo3lumi_turi4ol3us_oly3phin3airin5aglin4ado4inaceimpot5im5pieo4maneomast4_tu5te_tu3toi3mos_im5mesomeg5aome3liom3enaomen4to3meriim5inoim4inei3m2ieomic5rom4ie_imat5uom4inyomiss4uv5eri_un5cei5m2asim3ageil5ureomoli3o2mo4nom5onyo4mos__un5chilit5uom5pil_un3d2il4iteil5ippo5nas__uni3c_uni3o4iliou_un3k4oncat3on4cho_un3t4u4t1raon3deru4to5sili4feili4eri5lienonec4ri3lici_ve5loon5ellil3iaron3essil3ia_ong3atilesi45u5tiz4o1niaon5iar2oni4conic5aut3istut5ismon3iesigu5iti4g5roi5gretigno5m4onneson5odiign5izono4miu5tiniut3ingo5nota_ver3nig3andu4tereon4ter_vis3ionton5if5teeon4treif5icsut5eniutch4eif3ic_u3taneoof3eriev3erook3eri5eutiiet3ieool5iei3est_i1es2ties3eloop4ieieri4ni3eresus5uri4idomioot3erooz5eridol3ausur4eo5paliopa5raopath5id4istopens4id1is43operaus4treidios4_vi5sooph4ieo5philop5holi3dicuus1to4iderm5op3iesop5ingo3p2itid3eraust3ilid3encopol3ii5cun4op5onyop5oriopoun4o2p5ovicu4luop5plioprac4op3ranict5icopro4lop5ropic4terust5igust4icicon3ous5tanic5olaor5adoich5olus3tacic5ado4oralsib3utaoran3eab5areorb3ini4boseorch3iibios4ib3eraor5eadore5arore5caab5beri5atomia5theoreo5lor3escore3shor3essusk5eru4s1inor5ett4iaritianch5i2a3loial5lii3alitab3erdor3ia_4orianori4cius5ianorien4ab3erria5demori5gaori4no4orio_or5ion4oriosia5crii2ac2rus4canor3n4a5ornisor3nitor3oneabi5onor5oseor5osohys3teorrel3orres3hyol5ior4seyor4stihyl5enort3anort3atort3erab3itaor3thior4thror4titort3izor4toror5traort3reh4warthu3siahu4minhu5merhu4matht4ineht4fooht3ensht3eniab4ituht3en_ab3otah3rym3osec3uhrom4ios5encosens43abouthre5maabu4loab3useho4tonosi4alosi4anos5ideo3sierhort5hho5roghorn5ihor5etab3usio3sophos3opoho2p5ro3specho5niohong3ioss5aros4sithon3eyur3theos4taros5teeos5tenac5ablur5tesos3tilac5ardost3orho5neuhon5emhom5inot3a4gurs3orho4magach5alho5lysurs5ero5ta5vurs5alhol3aroter4muroti4ho3donachro4ur5o4mach5urac5onro5thorurn3ero5tillurn3alh5micao3tivao5tiviur5lieo5toneo4tornhirr5ihio5looturi4oty3lehi5noph5inizhi5nieh2in2ehimos4hi5merhi5ma4h3ifi4url5erhi4cinur5ionur4iliur4ie_ac2t5roult5ih4et3ahes3trh5erwaound5aac5uatur3ettoun3troup5liour3erou5sanh4eron5ousiaher5omur1e2tur3ersova3lead5eni4ovatiad3icao4ver_over3bover3sov4eteadi4opadis4iovis5oo2v5oshere3ohere3aherb3iherb3aher4ashende5ur5diehe5mopa3ditihemis4he3menowi5neh3el3ohel4lihe5liuhe3lioh5elinhe5lat5admithe5delhec3t4adram4heast5ad3ulahdeac5ae4cithavel4ura4cipac4tepa5douhas4tehar4tipa3gan4pagataed5isu5quet4pairmpa5lanpal3inag4ariharge4pan5ac4agerihant3ah5anizh1ani4agi4asham5an4aginopara5sup3ingpa3rocpa3rolpar5onhagi3oag3onihaged5agor4apa3terpati4naha5raaid5erail3erhadi4epaul5egust5apa5vilg4uredg4uraspaw5kigui5ta5guit43guardaim5erai5neagrum4bpec4tugru3en5ped3agrim3a4grameped3isgour4igo5noma3ing_5gnorig4ni2ope5leogn4in_pen4at5p4encu5orospen5drpen4ic3p4ennal5ablg2n3ingn5edlalact4until4g5natial5ais5gnathala3map3eronalc3atald5riun4nagg5nateglu5tiglu5tepes4s3ale5ma4g5lodun5ketpet3eng5lis4gli5ong4letrg4letoal3ibrali4cigin5gigi5ganun3istph5al_gi4alluni3sogh5eniph5esiggrav3ggi4a5al5icsg5gedlun4ine3germ4phi5thgeo3logen5ti4phobla5linigen5italin5ophos3pgen4dugel5ligel4ing4atosg4ato_gat5ivgast3ral5ipegasol5ga5rotp5icalu3n2ergar3eeg5antsgan4trp4iestpi5etip5ifieg5ant_un4dus4ganed4alis_gan5atpi3lotgam4blun4diepin5et3pingegali4a5p4insga5lenga4dosga4ciefu5tilpir5acfu3sil4furedfu4minundi4cpiss5aunde4tpis4trft4inefti4etf4ter_un3dedpla5noun4dalalk5ieun4as_al4lab4pled_frant4frag5aunabu44plism4plistal4lagu4n3a4umu4lofore3tfor4difor5ayfo5ramfon4deallig4fo4liefo1l4ifoeti42p5oidpois5iump5tepo4ly1poly3spoman5flum4iump5lipon4acpon4ceump3er3ponifpon5taf3licaf5iteepo5pleal3ogrpor3ea4poredpori4ffir2m1fin4nial3ous5fininpos1s2fi3nalu4moraumi4fyu2m5iffight5fier4cfid3enfi5delal5penp4pene4ficalumen4tal3tiep4pledp5plerp5pletal5uedal3uesffor3effoni4ff3linf2f3isal5ver2a1ly4fet4inaman5dul3siffet4ala3mas_fest5ipres3aulph3op3reseulph3i5pricipri4es4pri4mam5atuam4binfest3ap5riolpri4osul4litfess3o4privafer5ompro3boul4lispro4chfe5rocpron4aul4latam5elopro3r2pros4iu5litypro3thfer3ee4feredu5litipsal5tfemin5fea3tup5sin_fant3iul5ishpsul3i4fan3aul3ingfa5lonu3linefa2c3ufa3cetpt5arcez5ersp5tenapt5enn5pteryez5er_ex4on_ew5ishamen4dp2t3inpt4inep3tisep5tisievol5eevis5oam3eraev5ishev4ileam5erle4viabpudi4ce4veriam5icapu4laramic5rpu5lisu5lentu1len4a3miliev5eliev3astpun5gieva2p3eval5eev4abieu3tereu5teneudio5am5ilypu3tat5ulcheet3udeet3tere4trima5mis_et4riaul5ardet4ranetra5mamor5aetra5getor3iet3onaamort3am5ose3quera4quere4ques_et5olo5quinauit5er3quito4quitueti4naeti4gie3ticuuisti4ethyl3ra3bolamp3liuis3erampo5luin4taet5enia5nadian3agerag5ouuinc5u3raillra5ist4raliaet3eeret3atiet3ater4andian3aliran4dura5neeui3libra3niara3noiet5aryan3arca5nastan4conrant5orapol5rap5toet3arieta5merar3efand5auug3uraan5delet3al_es4ur5e2s3ulrass5aan5difug5lifra5tapra5tatrat5eurath4erat3ifan5ditra5tocan5eeran3ellra4tosra5tuirat5umrat3urrav5aian3ganrav3itestud4ra3ziees5tooe3stocangov4rb3alian4gures5taue5starest3anesta4brbel5orb3entes4siless5eeessar5rbic5uan5ifor5binee5s2pres5potan5ionrbu5t4es5pitrcant54anityr4celean3omaan4scoans3ilrcha3irch3alan4suran2t2ar3cheor4cherud3iedr4chinrch3isr3chites3onaan3talan5tamrciz4ies3olae3s4mie3skinrcolo4rcrit5an4thies4itses4it_e5sion3anthrrd4an_es5iesr5de4lr3dens4anticrd5essrd5ianan4tiee5sickes5ic_rd3ingesi4anrd1is2rd5lere3sh4aes5encrd5ouse5seg5e3sectescut5esci5eant4ives5chees5canre5altre5ambre3anire5antre5ascreas3oeryth35erwauan4tusreb5ucre3calrec4ceer4vilan5tymre3chaan3um_an5umsap5aroerund5ert5izer4thire3disre4dolape5lireed5iu4cender4terer5tedre3finuccen5re5grare3grereg3rire3groreg3ulaph5emer4repaph5olaphyl3ero5stero5iser3oidern3it4reledre3liarel3icre5ligreli4qrel3liern3isrem5acap5icuub3linern3errem5ulu4bicuren5atr4endiap4ineren4eser4moirenic5ren4itub5blyre5num4eri2ta3planre5olare3olier4iscer3ioure4pereri4onrep5idre3pinre3plere4preeri4nauari4ner3iffre5reare3r2uapo3thre3scrre3selre3semre3serap5ronre5sitre3speapt5at4arabiara5bore5stu3retarre3tenar3agear5agire1t2ore5tonre3trare3trere5trier4ianer3ia_ergi3ver3ettrev3elrevi4ter3etser3et_ar3agoar3allaran4ger3esier5eseere5olr4geneeren4e5erende4remeer5elser5ellr5hel4rhe5oler5el_er3egrer3ealerdi4eerd5arerb5oser3batar5apaer5atuarb5etar4bidty4letri5cliri3colri5corri4craarb3lirid4aler3apyer3apier3aphera4doar4bularch5otwi5liri5gamaren5dri5l4aar5ettar3ev5ar5iff5tur5oequin4rima4gar4illrim3ate4putarimen4e3pur5ept3or5turitr4inetturf5iturb3aep5rimt4uranrins5itu5racep3rehtun5it5rioneepol3iepol3ari5p2ari5piear5iniep3licarm3erris4ise4peteris4paris4pear5mit4ristiri3tonr5it5rep5ertriv4alar3nalar3nisriv3enriv3il5ri5zoar5oidep5arceor4derk5atir5kellrk5enia5rotieol5ata5roucr3kiertud5ier5kin_r5kinsrks4meen4tusent5uptu5denr3l4icr3liner5linsen4tritu4binen5tiarma5cetuari4ent3arr4mancr4manor4marir4maryen4susars5alart5atarth4een4sumens5alrm4icar5m2iden3otyenit5ut4tupermin4erm3ingarth3rar5tizen5iere2n3euen4ettrmu3lie3nessen5esiener5var5un4as5conrn3ateas5cotrn5edlt3tlerr3nessrn5esttti3tuas3ectt5test3encept4tereen3as_rn4inee2n3arrn3isten4annash5ayem4preash5ilem5pesas5ilyempa5rask5erem3orras5ochrob3letstay4e3moniem3oloemod4uemo3birody4n4emnitem4maee4mitaem3ismem5ingem3inar4oledas4silassit5as4tatro5melro3mitas4tiaas3tisemet4eron4ac4ronalas4titron5chron4dorong5ir5onmeem5ero4asto2as3traas4trit5roto4atabiem3anaro3peltro3spem3agor5opteel5tieelp5inel5opsrosi4aro5solel5op_5troopros4tiatar3aro3tatata3t4ro4terelo4dieloc3uelo5caat3eautri3me4roussell5izel4labrow3erelit4ttri3lie4li4seli3onr3pentrp5er_el3ingat3echr3pholrp3ingat5eerrpol3ar2p5ouele3vi3tricuelev3at5ricla5tel_e5lesstres4sele5phel3enor4reo4el5eni4e4ledelea5grricu4tre5prate5lerri4oseld3ertre4moat3entat3eraelast3el5ancel5age4traddeiv3ereit5ertra4co4atesse4ins_to3warehyd5re5g4oneg5nabefut5arsell5rs3er_rs3ersa3thene4fiteath3odr4shier5si2ato3temto5stra5thonrs3ingeem5eree2l1ieed3ere4d5urrstor4to3s4ped3ulo4a3tiator5oitor5ered3imeed5igrrt3ageto5radr4tareed5icsto4posr4tedlr3tel4r5tendrt3enito5piaa2t3in4atinaat5ingede3teton5earth3rir1t4icr4ticlr5tietr5tilar5tilltom5osrt5ilyedes3tr3tinart3ingr3titirti5tue4delee5dansrt5lete5culito4mogec4titrt5ridecti4cec4teratit3urtwis4e4cremtoma4nec3ratec5oroec3oratom3acat4iviec3lipruis5iecip5i4toledec5ath5at5odrun4clruncu42t3oidrun2d4e4caporu5netecal5ea4topsec3adea4toryebus5iebot3oe4belstode5cat3ronat5rouat4tagru3tale4bel_eav5our4vanceavi4ervel4ie3atrirven4erv5er_t4nerer3vestat3uraeatit4e3atifeat5ieeat3ertmo4t5east5iat3urge1as1s3ryngoau5ceraud5ereas5erryth4iaudic4ear4tee5ar2rear4liear3ereap5eream3ersac4teeam4blea3logeal3eread3liead3ersain4teac4tedy4ad_sa5lacdwell3sa3lies4al4t5tletrdvert3sa5minault5id5un4cdum4be5tledrs4an4etlant4san5ifdu5ettau5reodu5elldu5eliau5rordrunk3tiv3isaus5erdri4g3aut3ars5ativti3tradrast4d5railsau5ciaut3erdossi4sa3voudo5simdon4atdom5itt3itisdomin5doman4tit5ildo4lonscar4cdol5ittith4edol3endo4c3u4s4ces5dlestt4istrdi4val1di1v2ditor3av3ageava5latish5idithe4av5alr3tisand4iterd4itas3disiadisen34d5irodi4oladi5nossec5andin5gisecon4dimet4di5mersed4itdi3gamdig3al3di3evdi4ersd5icurse3lecselen55dicul2s4emedic4tesemi5dav5antdic5oldic5amt3iristi5quaav3end5sentmti3pliav3ernti5omosep4side4voisep3tiser4antiol3aser4to4servode3vitde3visdev3ils5estade3tesdes3tid3est_sev3enaviol4aw5er_de3sidde3sectin3uetin4tedes4casfor5esfran5der5os3dero45dernesh4abiaw5ersder4miaw5nieay5sta3dererde5reg4deredde3raiderac4si4allsiast5tin3ets3icatdepen42s5icldeont5si5cul4tinedba5birdens5aside5lsid3enbalm5ideni4eba5lonsi4ersde1n2ade4mosde3morba5nan5tilindemo4nti4letsin5etbardi44demiedel5lisi5nolsi3nusba5romdeli4esi5o5sde3lat5de3isde4fy_bar3onde4cilsist3asist3otigi5odeb5itsit5omdeac3td3dlerd4derebas4tedaugh3dativ4dast5a3d4as2d1an4ts3kierba4th4sk5ily3baticba5tiod4a4gid5ache3ti2encys5toc3utivbat5on4cur4oti3diecur4er1c2ultb4batab4bonecul5abcu5itycub3atctro5tbcord4ti3colct5olo3smithbdeac5tic5asct5ivec4tityc4tituc3t2isbed5elc3tinict5ing4s3oid4te3loct4in_so5lansol4erso3lic3solvebe5dra5ti5bube3lit3some_bend5ac4ticsbe5nigson5atbicen5son5orc4tentbi4ers5soriosor4its5orizc2t5eec3tato5bilesct5antc5ta5gctac5u5c4ruscrost4spast45thoug3b2ill3sperms5pero4thoptcre4to5creti3spher4t5hoocre4p3sp5id_s5pierspil4lcre3atsp3ingspi5nith3oli4creancra4tecras3tbimet55crani5bin4d3spons3spoonspru5dbind3ecous5t3co3trth4is_srep5ucost3aco5rolco3rels5sam24coreds5sengs3sent5th4ioss3er_s5seriss3ers3thinkt5hillbin5etcon4iecon4eyth3eryss4in_s4siness4is_s3s2itss4ivicon4chth3ernco3mo4co5masssol3ut5herds4soreth5erc5colouco3logco3inc4c3oidco3difco3dicsta3bic4lotrs4talebin5i4s3tas_theo3lc3lingbi3re4ste5arste5atbi5rusbisul54s1teds4tedls4tedn4stereth5eas3bituas3terost5est5blastcine5a4cinabs3ti3a3sticks3ticuthal3ms4tilyst3ing5s4tir5cimenth5al_st3lercigar5ci3estch5ousstone3bla5tu5blespblim3as4tose4chotis4tray4chosostrep33strucstru5dbment4tew3arch5oid5chlorstur4echizz4ch3innch4in_ch3ily3chicoche5va3chetech4erltetr5och4eriche3olcha3pa4boledbon4iesu5ingces5trcest5oce3remcer4bites5tusu3pinsupra3sur4ascept3a5testesur3pltest3aboni4ft3ess_bon4spcent4ab3oratbor5eebor5etbor5icter5nobor5iocen5cice4metce5lomter3itt4erinsy4chrcel3aice3darcci3d4ter5ifsy5photer5idcav3ilter3iabot3an3tablica3t2rta3bolta4bout4a3cete3reota3chyta4cidc4atom3casu35t2adjta5dor5terel3cas3scashi4tage5ota5gogca3roucar5oocar5oncar3olcar3nicar3ifter5ecca3reeter3ebta5lept4aliat4alin2tere45tallut2alo43ter3bt4eragtera4c3brachtan5atbran4db4reas5taneltan5iet5aniz4b2rescap3tica5piltent4atark5ican4trte5nog5brief5tennaca3noec2an4eta3stabring5t4ateu3tatist4ato_tat4ouca5nartat3uttau3tobri4osca5lefcal5ar4tenarcab5inb5ut5obut4ivten4ag3butiob5utinbu5tarte5cha5technbus5sibusi4ete5d2abur4rite5monb4ulosb5rist5tegicb5tletbro4mab4stacbso3lubsol3e4teledtel5izbscon4ct4ina",7:"mor4atobstupe5buf5ferb5u5nattch5ettm3orat4call5inmor5talcan5tarcan5tedcan4tictar5ia_brev5ettant5anca3ra5ctand5er_ad4din5ta3mettam5arit4eratocar5ameboun5tital4l3atal5entmonolo4cas5tigta5chom3teres4ta5blemcaulk4iccent5rcces4sacel5ib5mpel5licel5lincen5ded5ternit4sweredswell5icend5encend5ersvest5isvers5acen5tedt5esses_ama5tem5perercen5testest5ertest5intest5orcep5ticmpet5itchan5gi5cherin4choredchor5olmphal5os5toratblem5atston4iecil5lin4mologu4mologss4tern_ster4iaci5nesscla5rifclemat45static4molog_5therapmogast4ssolu4b4theredcon4aticond5erconta5dcor5dedcord5ermpol5itcost5ercraft5ispon5gicra5niuspital5spic5ulspers5a4thorescret5orspens5ac5tariabi4fid_4sor3iecter4iab5ertinberga5mc5ticiabend5erso5metesoma5toctifi4esolv5erc5tin5o_an4on_ct4ivittici5ar3ti3cint4icityc5torisc5toriz4ticulecull5ercull5inbattle5cur5ialmmel5lislang5idal5lersk5iness5kiest4tific_daun5tede5cantdefor5edel5ler_an3ti34dem4issim4plyb4aniti_ant4icde4mons_an4t5osid5eri5timet4dens5er5ti5nadden5titdeposi4zin4c3i_aph5orshil5lider5minsfact5otin5tedtint5erde5scalmis4tindes5ponse5renedevol5u4tionemdiat5omti5plexseo5logsent5eemi5racu_ar4isedic5tat4scuras4scura__ar4isi5scopic3s4cope5t4istedi5vineti5t4ando5linesca5lendom5inodot4tins5atorydress5oaus4tedtiv5allsassem4dropho4duci5ansant5risan5garaun4dresan4ded_ar5sendust5erault5erdvoc5ataul5tedearth5iea4soni4ryngoleassem4eat5enieat4iturv5ers_rus4t5urus5ticrust5eeatric5urust5at_as5sibrup5licminth5oecad5enruncul5ru4moreecent5oa5tivizecon4sc_ateli4_au3g4uec5rean_aur4e5ect5atiec4t5usrtil5le4at4is__av5erar4theneedeter5edi4alsr5terered5icala4t1i4lediges4at5icizediv5idtori4asrswear4ati5citat5icisedu5cerrstrat4eer4ineefact5oming5li_ba5sicef5ereemin4ersath5eteath5eromin4er__be5r4ae5ignitr5salizmind5err5salisejudic44traistmil5iestrarch4tra5ven_blaz5o4m5iliee4lates_bos5omat5enatelch5errrin5getrend5irri4fy_rran5gie4lesteel3et3o_boun4d_bra5chtri5fli_burn5ieli4ers_ca4ginrou5sel_can5tamigh5tiros5tita5talisro5stattro4pharop4ineemarc5aem5atizemat5ole4m3eraron4tonro5nateem4icisnaffil4romant4emig5rarol5iteass5iblassa5giemon5ola4sonedem5orise4moticempara54empli_en3am3o_cen5sot5tereren4cileen4d5alen4dedlttitud45n4a3grend5ritrn5atine5nellee5nereor4mite_r4ming_en3ig3rmet5icirma5tocr4m3atinannot4en4tersen4tifyarp5ersent5rinr5kiesteol5ar_eologi4aro4mas_clem5eriv5eliri5vallris5ternan5teda5rishi3mesti4epolit5tup5lettup5lic_cop5roepres5erink5erme5si4aring5ie_co5terrim5an4equi5noment5or4tut4ivna5turiera4cierig5ant5rifugaar4donear5dinarif5tiear5chetrift5er4erati_4eratimrick4enrich5omrica5tuaran5teer5esteer5estieres5trre5termar4aged_dea5coaract4irest5erre5stalapu5lareri4ciduant5isuant5itres5ist5er5ickapo5strer4imet_de5lecuar4t5iua5terneri5staren4ter5ernaclmend5errem5atoreman4d_del5egerre5laer5sinere5galiert5er_ert5ersrec4t3rr4e1c2rreci5simelt5er_deli5ran4tone_de5nitan4tinges5idenesi5diur4d1an4rcriti4es3ol3urci5nogant5abludi4cinrch4ieru5dinisrch5ateu5ditiorch5ardes3per3mel5lerrcen5eres5piraanis5teesplen5uen4teres4s3anest5ifi_de5resues5trin4cept_rav5elianel5li4r4atom5ra5tolan4donirat4in_r4as5teand5istrass5in5meg2a1et3al5oand5eerrar5ia_an3d4atrant5inuicent55rantelran5teduild5erran4gennch5oloetell5irad4inencid5enra5culorac5ulaet3er3aet5eria3ra3binet5itivui5val5amphi5gam5peri_de5sirqua5tio4e4trala4mium_et5ressetrib5aaminos4am5inizamini4fp5u5tis5ulchrepush4ieev5eratev5eren4ulenciever4erpu5lar_puff5erevictu4evis5in_de5sisfall5inncip5ie_di4al_fend5erpros5trpropyl5proph5eul4l5ibp3roc3apris5inpring5imbival5nco5pat5pressiyllab5iulp5ingpre5matylin5dem4b3ingnct4ivife5veriffec4te_du4al_pprob5am5bererum4bar__echin5fi5anceal5tatipparat5pout5ern4curviumi5liaumin4aru4minedu4m3ingpoult5epor5tieal4orim4poratopon4i4eflo5rical4lish_ed4it_foment4_ed4itialli5anplum4befor4m3a_el3ev3fratch4pla5t4oma5turem4atizafrost5ipis5tilmat4itifuel5ligal5lerpill5ingang5ergariz4aunho5lial5ipotgass5inph5oriz4phonedgest5atg5gererphant5ipha5gedgiv5en_5glass_unk5eripet5allal5endepes5tilpert5isper5tinper4os_al5ance5p4er3nperem5indeleg4gna5turndepre4aint5eruodent4pend5er4gogram_en4dedpearl5indes5crgth5enimas4tinpat4richad4inepas4tinnd5is4ihak4inehal5anthan4crohar5dieha5rismhar4tedaet4or_aerody5pag4atihaught5_er5em5hearch44urantiheav5enurb5ingoxic5olowhith4ur5den_ur5deniowel5lih5erettovid5ennd5ism_her5ialh5erineout5ishoun5ginound5elhet4tedact5oryu5ri5cuheumat5ur5ifieact5ileought5ihi3c4anuri4os_h4i4ersh4manicurl5ingact5atemast4ichnocen5_men5taaci4erso5thermmar4shimantel5ot5estaurpen5tach5isma5chinihol4is_ot4atioot4anico5talito5stome5acanthost5icaosten5tost5ageh4op4te3house3hras5eoy4chosen5ectom4abolicht5eneror5tes_man4icay5chedei5a4g5oori5cidialect4or5este_escal5iatur4aorator5_wine5s_vo5lutich5ingo5quial_etern5us5ticiic4tedloplast4ophy5laid4ines4operag2i4d1itoost5eriff5leronvo5lui4ficaconti5fiman5dar_vic5to_fal4lemament4mal4is__ver4ieila5telonical4i5later_feoff5ili4arl_va5ledil4ificond5ent_ur5eth5ond5arut4toneil5ine_on5ativonast5i_under5ompt5eromot5ivi4matedi4matin_fi5liaimpar5a_fil5tro5lunte4inalit_tular5olon5el5neringinator5_tro4ph_fis4c5inc4tua_trin4aol4lopeoli4f3eol5ies_mal5ari_tran4c_tit4isnerv5inval4iseol5icizinfilt5olat5erin4itud_gam5etxter4m3ink4inein4sch5_tell5evas5el5insect5insec5uinsolv5int5essvat4inaoher4erint5res_tamar5xtens5o_tact4iinvol5ui4omani_gen4et_gen5iave5linei5pheriip5torivel5lerir4alinvel5opiir4alliirassi4nfortu5irl5ingirwo4meo4ducts4lut5arv5en5ue_stat4o_si5gnoverde5v4v4ere4o4duct_odu5cerodis5iaocus5siis5onerist5encxotrop4_ser4ie5vialitist5entochro4n_gnost4_sec5tovi5cariocess4iis4t3iclum4brio5calli4is4tom4itioneit5ress3vili4av5ilisev5ilizevil5linoast5eritu4als_han4de_hast5ii4vers__sa5linlsi4fiai5vilit5ivist_5ivistsnvoc5at_ho5rol_rol4lakinema4ni4cul4nultim5_re5strloth4ie5la5collos5sienight5ilor4ife_re5spolor5iatntup5li5lo5pen_re5sen_res5ci_re5linnt5ressn4trant_re5garloom5erxhort4a_ran5gilong5invol4ubi_ra5cem_put4ten5tition4tiparlo4cus__pos5si_lash4e_len5tint5ing_nit5res_le5vanxecut5o_plica4n4tify__plast45latini_phon4illow5er_li4onslligat4_peri5nntic4u4_pen5dewall5ern5ticizwan5gliwank5erwar5dedward5ern5ticisnth5ine_lo4giawar5thinmater4_pec3t4_pa4tiowav4ine_lous5i_para5t_par5af_lov5ernmor5ti_orner4nt5ativ_or5che_ma5lin_mar5ti_or4at4le5ation5tasiswel4izint4ariun4t3antntan5eon4t3ancleav5erl3eb5rannel5li_nucle5_no5ticlem5enclen5darwill5in_ni5tronsec4tewing5er4lentio5l4eriannerv5a_nas5tinres5tr5le5tu5lev5itano5blemnovel5el3ic3onwol5ver_mor5tilift5erlight5ilimet4e_mo5lec5lin3ealin4er_lin4erslin4gern5ocula_min5uenobser4_met4er_me5rin_me5ridmas4ted",8:"_musi5cobserv5anwith5erilect5icaweight5ica5laman_mal5ad5l5di5nestast5i4cntend5enntern5alnter5nat_perse5c_pe5titi_phe5nomxe5cutio5latiliz_librar5nt5ilati_les5son_po5lite_ac5tiva5latilisnis5tersnis5ter_tamorph5_pro5batvo5litiolan5tine_ref5eremophil5ila5melli_re5statca3r4i3c5lamandrcen5ter_5visecti5numentanvers5aniver5saliv5eling_salt5ercen5ters_ha5bilio4c5ativlunch5eois5terer_sev5era_glor5io_stra5tocham5perstor5ianstil5ler_ge5neti_sulph5a_tac5ticnform5eroin4t5erneuma5to_te5ra5tma5chinecine5mat_tri5bal_fran5ch_tri5sti_fi5n4it_troph5o_fin5essimparad5stant5iv_vent5il4o5nomicssor5ialight5ersight5er__evol5utm5ament_ont5ane_icotyle5orest5atiab5oliziab5olismod5ifiehrill5inothalam5oth5erinnduct5ivrth5ing_otherm5a5ot5inizov5elinghav5ersipass5ivessent5ermater5n4ain5dersuo5tatiopens5atipercent5slav5eriplant5er5sing5erfortu5naplumb5erpo5lemicpound5erffranch5ppress5oa5lumnia_domest5pref5ereprel5atea5marinepre5scina5m4aticpring5ertil4l5agmmand5er5sid5u4a_de5spoievol5utee5tometeetend5erting5ingmed5icatran5dishm5ed5ieset5allis_de5servsh5inessmlo5cutiuest5ratncent5rincarn5atdes5ignareact5ivr5ebratereced5ennbarric5sen5sorier5nalisuar5tersre4t4er3_custom5naugh5tirill5er_sen5sati5scripti_cotyle5e4p5rob5a5ri5netaun5chierin4t5errip5lica_art5icl5at5ressepend5entu4al5lir5ma5tolttitu5di_cent5ria5torianena5ture5na5geri_cas5ualromolec5elom5ateatitud5i_ca5pituround5ernac5tiva_at5omizrpass5intomat5oltrifu5gae4l3ica4rpret5erel5ativetrav5esttra5versat5ernisat5ernizefor5estath5erinef5initeto5talizto5talis_barri5c_authen5mass5ing",9:"_bap5tismna5cious_econstit5na5ciousl_at5omisena5culari_cen5tena_clima5toepe5titionar5tisti_cri5ticirill5ingserpent5inrcen5tenaest5igati_de5scrib_de5signe_determ5ifals5ifiefan5tasizplas5ticiundeter5msmu5tatiopa5triciaosclero5s_fec5unda_ulti5matindeterm5ipart5ite_string5i5lutionizltramont5_re5storeter5iorit_invest5imonolog5introl5ler_lam5enta_po5sitio_para5dis_ora5tori_me5lodio"}};Hyphenator.config({useCSS3hyphenation:true});Hyphenator.run(); | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/static/js/hyp.js | hyp.js |
(function(Da,P,l){var O=function(h){function V(a){var b,c,d={};h.each(a,function(e){if((b=e.match(/^([^A-Z]+?)([A-Z])/))&&-1!=="a aa ai ao as b fn i m o s ".indexOf(b[1]+" "))c=e.replace(b[0],b[2].toLowerCase()),d[c]=e,"o"===b[1]&&V(a[e])});a._hungarianMap=d}function G(a,b,c){a._hungarianMap||V(a);var d;h.each(b,function(e){d=a._hungarianMap[e];if(d!==l&&(c||b[d]===l))"o"===d.charAt(0)?(b[d]||(b[d]={}),h.extend(!0,b[d],b[e]),G(a[d],b[d],c)):b[d]=b[e]})}function O(a){var b=p.defaults.oLanguage,c=a.sZeroRecords;
!a.sEmptyTable&&(c&&"No data available in table"===b.sEmptyTable)&&D(a,a,"sZeroRecords","sEmptyTable");!a.sLoadingRecords&&(c&&"Loading..."===b.sLoadingRecords)&&D(a,a,"sZeroRecords","sLoadingRecords");a.sInfoThousands&&(a.sThousands=a.sInfoThousands);(a=a.sDecimal)&&db(a)}function eb(a){z(a,"ordering","bSort");z(a,"orderMulti","bSortMulti");z(a,"orderClasses","bSortClasses");z(a,"orderCellsTop","bSortCellsTop");z(a,"order","aaSorting");z(a,"orderFixed","aaSortingFixed");z(a,"paging","bPaginate");
z(a,"pagingType","sPaginationType");z(a,"pageLength","iDisplayLength");z(a,"searching","bFilter");if(a=a.aoSearchCols)for(var b=0,c=a.length;b<c;b++)a[b]&&G(p.models.oSearch,a[b])}function fb(a){z(a,"orderable","bSortable");z(a,"orderData","aDataSort");z(a,"orderSequence","asSorting");z(a,"orderDataType","sortDataType")}function gb(a){var a=a.oBrowser,b=h("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(h("<div/>").css({position:"absolute",top:1,left:1,width:100,
overflow:"scroll"}).append(h('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),c=b.find(".test");a.bScrollOversize=100===c[0].offsetWidth;a.bScrollbarLeft=1!==c.offset().left;b.remove()}function hb(a,b,c,d,e,f){var g,i=!1;c!==l&&(g=c,i=!0);for(;d!==e;)a.hasOwnProperty(d)&&(g=i?b(g,a[d],d,a):a[d],i=!0,d+=f);return g}function Ea(a,b){var c=p.defaults.column,d=a.aoColumns.length,c=h.extend({},p.models.oColumn,c,{nTh:b?b:P.createElement("th"),sTitle:c.sTitle?c.sTitle:b?b.innerHTML:
"",aDataSort:c.aDataSort?c.aDataSort:[d],mData:c.mData?c.mData:d,idx:d});a.aoColumns.push(c);c=a.aoPreSearchCols;c[d]=h.extend({},p.models.oSearch,c[d]);ia(a,d,null)}function ia(a,b,c){var b=a.aoColumns[b],d=a.oClasses,e=h(b.nTh);if(!b.sWidthOrig){b.sWidthOrig=e.attr("width")||null;var f=(e.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);f&&(b.sWidthOrig=f[1])}c!==l&&null!==c&&(fb(c),G(p.defaults.column,c),c.mDataProp!==l&&!c.mData&&(c.mData=c.mDataProp),c.sType&&(b._sManualType=c.sType),c.className&&
!c.sClass&&(c.sClass=c.className),h.extend(b,c),D(b,c,"sWidth","sWidthOrig"),"number"===typeof c.iDataSort&&(b.aDataSort=[c.iDataSort]),D(b,c,"aDataSort"));var g=b.mData,i=W(g),j=b.mRender?W(b.mRender):null,c=function(a){return"string"===typeof a&&-1!==a.indexOf("@")};b._bAttrSrc=h.isPlainObject(g)&&(c(g.sort)||c(g.type)||c(g.filter));b.fnGetData=function(a,b,c){var d=i(a,b,l,c);return j&&b?j(d,b,a,c):d};b.fnSetData=function(a,b,c){return Q(g)(a,b,c)};"number"!==typeof g&&(a._rowReadObject=!0);a.oFeatures.bSort||
(b.bSortable=!1,e.addClass(d.sSortableNone));a=-1!==h.inArray("asc",b.asSorting);c=-1!==h.inArray("desc",b.asSorting);!b.bSortable||!a&&!c?(b.sSortingClass=d.sSortableNone,b.sSortingClassJUI=""):a&&!c?(b.sSortingClass=d.sSortableAsc,b.sSortingClassJUI=d.sSortJUIAscAllowed):!a&&c?(b.sSortingClass=d.sSortableDesc,b.sSortingClassJUI=d.sSortJUIDescAllowed):(b.sSortingClass=d.sSortable,b.sSortingClassJUI=d.sSortJUI)}function X(a){if(!1!==a.oFeatures.bAutoWidth){var b=a.aoColumns;Fa(a);for(var c=0,d=b.length;c<
d;c++)b[c].nTh.style.width=b[c].sWidth}b=a.oScroll;(""!==b.sY||""!==b.sX)&&Y(a);u(a,null,"column-sizing",[a])}function ja(a,b){var c=Z(a,"bVisible");return"number"===typeof c[b]?c[b]:null}function $(a,b){var c=Z(a,"bVisible"),c=h.inArray(b,c);return-1!==c?c:null}function aa(a){return Z(a,"bVisible").length}function Z(a,b){var c=[];h.map(a.aoColumns,function(a,e){a[b]&&c.push(e)});return c}function Ga(a){var b=a.aoColumns,c=a.aoData,d=p.ext.type.detect,e,f,g,i,j,h,m,o,k;e=0;for(f=b.length;e<f;e++)if(m=
b[e],k=[],!m.sType&&m._sManualType)m.sType=m._sManualType;else if(!m.sType){g=0;for(i=d.length;g<i;g++){j=0;for(h=c.length;j<h&&!(k[j]===l&&(k[j]=w(a,j,e,"type")),o=d[g](k[j],a),!o||"html"===o);j++);if(o){m.sType=o;break}}m.sType||(m.sType="string")}}function ib(a,b,c,d){var e,f,g,i,j,n,m=a.aoColumns;if(b)for(e=b.length-1;0<=e;e--){n=b[e];var o=n.targets!==l?n.targets:n.aTargets;h.isArray(o)||(o=[o]);f=0;for(g=o.length;f<g;f++)if("number"===typeof o[f]&&0<=o[f]){for(;m.length<=o[f];)Ea(a);d(o[f],
n)}else if("number"===typeof o[f]&&0>o[f])d(m.length+o[f],n);else if("string"===typeof o[f]){i=0;for(j=m.length;i<j;i++)("_all"==o[f]||h(m[i].nTh).hasClass(o[f]))&&d(i,n)}}if(c){e=0;for(a=c.length;e<a;e++)d(e,c[e])}}function I(a,b,c,d){var e=a.aoData.length,f=h.extend(!0,{},p.models.oRow,{src:c?"dom":"data"});f._aData=b;a.aoData.push(f);for(var b=a.aoColumns,f=0,g=b.length;f<g;f++)c&&Ha(a,e,f,w(a,e,f)),b[f].sType=null;a.aiDisplayMaster.push(e);(c||!a.oFeatures.bDeferRender)&&Ia(a,e,c,d);return e}
function ka(a,b){var c;b instanceof h||(b=h(b));return b.map(function(b,e){c=la(a,e);return I(a,c.data,e,c.cells)})}function w(a,b,c,d){var e=a.iDraw,f=a.aoColumns[c],g=a.aoData[b]._aData,i=f.sDefaultContent,c=f.fnGetData(g,d,{settings:a,row:b,col:c});if(c===l)return a.iDrawError!=e&&null===i&&(R(a,0,"Requested unknown parameter "+("function"==typeof f.mData?"{function}":"'"+f.mData+"'")+" for row "+b,4),a.iDrawError=e),i;if((c===g||null===c)&&null!==i)c=i;else if("function"===typeof c)return c.call(g);
return null===c&&"display"==d?"":c}function Ha(a,b,c,d){a.aoColumns[c].fnSetData(a.aoData[b]._aData,d,{settings:a,row:b,col:c})}function Ja(a){return h.map(a.match(/(\\.|[^\.])+/g),function(a){return a.replace(/\\./g,".")})}function W(a){if(h.isPlainObject(a)){var b={};h.each(a,function(a,c){c&&(b[a]=W(c))});return function(a,c,f,g){var i=b[c]||b._;return i!==l?i(a,c,f,g):a}}if(null===a)return function(a){return a};if("function"===typeof a)return function(b,c,f,g){return a(b,c,f,g)};if("string"===
typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var c=function(a,b,f){var g,i;if(""!==f){i=Ja(f);for(var j=0,h=i.length;j<h;j++){f=i[j].match(ba);g=i[j].match(S);if(f){i[j]=i[j].replace(ba,"");""!==i[j]&&(a=a[i[j]]);g=[];i.splice(0,j+1);i=i.join(".");j=0;for(h=a.length;j<h;j++)g.push(c(a[j],b,i));a=f[0].substring(1,f[0].length-1);a=""===a?g:g.join(a);break}else if(g){i[j]=i[j].replace(S,"");a=a[i[j]]();continue}if(null===a||a[i[j]]===l)return l;a=a[i[j]]}}return a};return function(b,
e){return c(b,e,a)}}return function(b){return b[a]}}function Q(a){if(h.isPlainObject(a))return Q(a._);if(null===a)return function(){};if("function"===typeof a)return function(b,d,e){a(b,"set",d,e)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var b=function(a,d,e){var e=Ja(e),f;f=e[e.length-1];for(var g,i,j=0,h=e.length-1;j<h;j++){g=e[j].match(ba);i=e[j].match(S);if(g){e[j]=e[j].replace(ba,"");a[e[j]]=[];f=e.slice();f.splice(0,j+1);g=f.join(".");i=0;for(h=
d.length;i<h;i++)f={},b(f,d[i],g),a[e[j]].push(f);return}i&&(e[j]=e[j].replace(S,""),a=a[e[j]](d));if(null===a[e[j]]||a[e[j]]===l)a[e[j]]={};a=a[e[j]]}if(f.match(S))a[f.replace(S,"")](d);else a[f.replace(ba,"")]=d};return function(c,d){return b(c,d,a)}}return function(b,d){b[a]=d}}function Ka(a){return C(a.aoData,"_aData")}function ma(a){a.aoData.length=0;a.aiDisplayMaster.length=0;a.aiDisplay.length=0}function na(a,b,c){for(var d=-1,e=0,f=a.length;e<f;e++)a[e]==b?d=e:a[e]>b&&a[e]--; -1!=d&&c===l&&
a.splice(d,1)}function oa(a,b,c,d){var e=a.aoData[b],f;if("dom"===c||(!c||"auto"===c)&&"dom"===e.src)e._aData=la(a,e).data;else{var g=e.anCells,i;if(g){c=0;for(f=g.length;c<f;c++){for(i=g[c];i.childNodes.length;)i.removeChild(i.firstChild);g[c].innerHTML=w(a,b,c,"display")}}}e._aSortData=null;e._aFilterData=null;a=a.aoColumns;if(d!==l)a[d].sType=null;else{c=0;for(f=a.length;c<f;c++)a[c].sType=null}La(e)}function la(a,b){var c=[],d=b.firstChild,e,f,g=0,i,j=a.aoColumns,n=a._rowReadObject,m=n?{}:[],
o=function(a,b){if("string"===typeof a){var c=a.indexOf("@");-1!==c&&(c=a.substring(c+1),Q(a)(m,b.getAttribute(c)))}},k=function(a){f=j[g];i=h.trim(a.innerHTML);f&&f._bAttrSrc?(Q(f.mData._)(m,i),o(f.mData.sort,a),o(f.mData.type,a),o(f.mData.filter,a)):n?(f._setter||(f._setter=Q(f.mData)),f._setter(m,i)):m.push(i);g++};if(d)for(;d;){e=d.nodeName.toUpperCase();if("TD"==e||"TH"==e)k(d),c.push(d);d=d.nextSibling}else{c=b.anCells;d=0;for(e=c.length;d<e;d++)k(c[d])}return{data:m,cells:c}}function Ia(a,
b,c,d){var e=a.aoData[b],f=e._aData,g=[],i,j,h,m,o;if(null===e.nTr){i=c||P.createElement("tr");e.nTr=i;e.anCells=g;i._DT_RowIndex=b;La(e);m=0;for(o=a.aoColumns.length;m<o;m++){h=a.aoColumns[m];j=c?d[m]:P.createElement(h.sCellType);g.push(j);if(!c||h.mRender||h.mData!==m)j.innerHTML=w(a,b,m,"display");h.sClass&&(j.className+=" "+h.sClass);h.bVisible&&!c?i.appendChild(j):!h.bVisible&&c&&j.parentNode.removeChild(j);h.fnCreatedCell&&h.fnCreatedCell.call(a.oInstance,j,w(a,b,m),f,b,m)}u(a,"aoRowCreatedCallback",
null,[i,f,b])}e.nTr.setAttribute("role","row")}function La(a){var b=a.nTr,c=a._aData;if(b){c.DT_RowId&&(b.id=c.DT_RowId);if(c.DT_RowClass){var d=c.DT_RowClass.split(" ");a.__rowc=a.__rowc?Ma(a.__rowc.concat(d)):d;h(b).removeClass(a.__rowc.join(" ")).addClass(c.DT_RowClass)}c.DT_RowData&&h(b).data(c.DT_RowData)}}function jb(a){var b,c,d,e,f,g=a.nTHead,i=a.nTFoot,j=0===h("th, td",g).length,n=a.oClasses,m=a.aoColumns;j&&(e=h("<tr/>").appendTo(g));b=0;for(c=m.length;b<c;b++)f=m[b],d=h(f.nTh).addClass(f.sClass),
j&&d.appendTo(e),a.oFeatures.bSort&&(d.addClass(f.sSortingClass),!1!==f.bSortable&&(d.attr("tabindex",a.iTabIndex).attr("aria-controls",a.sTableId),Na(a,f.nTh,b))),f.sTitle!=d.html()&&d.html(f.sTitle),Oa(a,"header")(a,d,f,n);j&&ca(a.aoHeader,g);h(g).find(">tr").attr("role","row");h(g).find(">tr>th, >tr>td").addClass(n.sHeaderTH);h(i).find(">tr>th, >tr>td").addClass(n.sFooterTH);if(null!==i){a=a.aoFooter[0];b=0;for(c=a.length;b<c;b++)f=m[b],f.nTf=a[b].cell,f.sClass&&h(f.nTf).addClass(f.sClass)}}function da(a,
b,c){var d,e,f,g=[],i=[],j=a.aoColumns.length,n;if(b){c===l&&(c=!1);d=0;for(e=b.length;d<e;d++){g[d]=b[d].slice();g[d].nTr=b[d].nTr;for(f=j-1;0<=f;f--)!a.aoColumns[f].bVisible&&!c&&g[d].splice(f,1);i.push([])}d=0;for(e=g.length;d<e;d++){if(a=g[d].nTr)for(;f=a.firstChild;)a.removeChild(f);f=0;for(b=g[d].length;f<b;f++)if(n=j=1,i[d][f]===l){a.appendChild(g[d][f].cell);for(i[d][f]=1;g[d+j]!==l&&g[d][f].cell==g[d+j][f].cell;)i[d+j][f]=1,j++;for(;g[d][f+n]!==l&&g[d][f].cell==g[d][f+n].cell;){for(c=0;c<
j;c++)i[d+c][f+n]=1;n++}h(g[d][f].cell).attr("rowspan",j).attr("colspan",n)}}}}function L(a){var b=u(a,"aoPreDrawCallback","preDraw",[a]);if(-1!==h.inArray(!1,b))B(a,!1);else{var b=[],c=0,d=a.asStripeClasses,e=d.length,f=a.oLanguage,g=a.iInitDisplayStart,i="ssp"==A(a),j=a.aiDisplay;a.bDrawing=!0;g!==l&&-1!==g&&(a._iDisplayStart=i?g:g>=a.fnRecordsDisplay()?0:g,a.iInitDisplayStart=-1);var g=a._iDisplayStart,n=a.fnDisplayEnd();if(a.bDeferLoading)a.bDeferLoading=!1,a.iDraw++,B(a,!1);else if(i){if(!a.bDestroying&&
!kb(a))return}else a.iDraw++;if(0!==j.length){f=i?a.aoData.length:n;for(i=i?0:g;i<f;i++){var m=j[i],o=a.aoData[m];null===o.nTr&&Ia(a,m);m=o.nTr;if(0!==e){var k=d[c%e];o._sRowStripe!=k&&(h(m).removeClass(o._sRowStripe).addClass(k),o._sRowStripe=k)}u(a,"aoRowCallback",null,[m,o._aData,c,i]);b.push(m);c++}}else c=f.sZeroRecords,1==a.iDraw&&"ajax"==A(a)?c=f.sLoadingRecords:f.sEmptyTable&&0===a.fnRecordsTotal()&&(c=f.sEmptyTable),b[0]=h("<tr/>",{"class":e?d[0]:""}).append(h("<td />",{valign:"top",colSpan:aa(a),
"class":a.oClasses.sRowEmpty}).html(c))[0];u(a,"aoHeaderCallback","header",[h(a.nTHead).children("tr")[0],Ka(a),g,n,j]);u(a,"aoFooterCallback","footer",[h(a.nTFoot).children("tr")[0],Ka(a),g,n,j]);d=h(a.nTBody);d.children().detach();d.append(h(b));u(a,"aoDrawCallback","draw",[a]);a.bSorted=!1;a.bFiltered=!1;a.bDrawing=!1}}function M(a,b){var c=a.oFeatures,d=c.bFilter;c.bSort&&lb(a);d?ea(a,a.oPreviousSearch):a.aiDisplay=a.aiDisplayMaster.slice();!0!==b&&(a._iDisplayStart=0);a._drawHold=b;L(a);a._drawHold=
!1}function mb(a){var b=a.oClasses,c=h(a.nTable),c=h("<div/>").insertBefore(c),d=a.oFeatures,e=h("<div/>",{id:a.sTableId+"_wrapper","class":b.sWrapper+(a.nTFoot?"":" "+b.sNoFooter)});a.nHolding=c[0];a.nTableWrapper=e[0];a.nTableReinsertBefore=a.nTable.nextSibling;for(var f=a.sDom.split(""),g,i,j,n,m,o,k=0;k<f.length;k++){g=null;i=f[k];if("<"==i){j=h("<div/>")[0];n=f[k+1];if("'"==n||'"'==n){m="";for(o=2;f[k+o]!=n;)m+=f[k+o],o++;"H"==m?m=b.sJUIHeader:"F"==m&&(m=b.sJUIFooter);-1!=m.indexOf(".")?(n=m.split("."),
j.id=n[0].substr(1,n[0].length-1),j.className=n[1]):"#"==m.charAt(0)?j.id=m.substr(1,m.length-1):j.className=m;k+=o}e.append(j);e=h(j)}else if(">"==i)e=e.parent();else if("l"==i&&d.bPaginate&&d.bLengthChange)g=nb(a);else if("f"==i&&d.bFilter)g=ob(a);else if("r"==i&&d.bProcessing)g=pb(a);else if("t"==i)g=qb(a);else if("i"==i&&d.bInfo)g=rb(a);else if("p"==i&&d.bPaginate)g=sb(a);else if(0!==p.ext.feature.length){j=p.ext.feature;o=0;for(n=j.length;o<n;o++)if(i==j[o].cFeature){g=j[o].fnInit(a);break}}g&&
(j=a.aanFeatures,j[i]||(j[i]=[]),j[i].push(g),e.append(g))}c.replaceWith(e)}function ca(a,b){var c=h(b).children("tr"),d,e,f,g,i,j,n,m,o,k;a.splice(0,a.length);f=0;for(j=c.length;f<j;f++)a.push([]);f=0;for(j=c.length;f<j;f++){d=c[f];for(e=d.firstChild;e;){if("TD"==e.nodeName.toUpperCase()||"TH"==e.nodeName.toUpperCase()){m=1*e.getAttribute("colspan");o=1*e.getAttribute("rowspan");m=!m||0===m||1===m?1:m;o=!o||0===o||1===o?1:o;g=0;for(i=a[f];i[g];)g++;n=g;k=1===m?!0:!1;for(i=0;i<m;i++)for(g=0;g<o;g++)a[f+
g][n+i]={cell:e,unique:k},a[f+g].nTr=d}e=e.nextSibling}}}function pa(a,b,c){var d=[];c||(c=a.aoHeader,b&&(c=[],ca(c,b)));for(var b=0,e=c.length;b<e;b++)for(var f=0,g=c[b].length;f<g;f++)if(c[b][f].unique&&(!d[f]||!a.bSortCellsTop))d[f]=c[b][f].cell;return d}function qa(a,b,c){u(a,"aoServerParams","serverParams",[b]);if(b&&h.isArray(b)){var d={},e=/(.*?)\[\]$/;h.each(b,function(a,b){var c=b.name.match(e);c?(c=c[0],d[c]||(d[c]=[]),d[c].push(b.value)):d[b.name]=b.value});b=d}var f,g=a.ajax,i=a.oInstance;
if(h.isPlainObject(g)&&g.data){f=g.data;var j=h.isFunction(f)?f(b):f,b=h.isFunction(f)&&j?j:h.extend(!0,b,j);delete g.data}j={data:b,success:function(b){var d=b.error||b.sError;d&&a.oApi._fnLog(a,0,d);a.json=b;u(a,null,"xhr",[a,b]);c(b)},dataType:"json",cache:!1,type:a.sServerMethod,error:function(b,c){var d=a.oApi._fnLog;"parsererror"==c?d(a,0,"Invalid JSON response",1):4===b.readyState&&d(a,0,"Ajax error",7);B(a,!1)}};a.oAjaxData=b;u(a,null,"preXhr",[a,b]);a.fnServerData?a.fnServerData.call(i,a.sAjaxSource,
h.map(b,function(a,b){return{name:b,value:a}}),c,a):a.sAjaxSource||"string"===typeof g?a.jqXHR=h.ajax(h.extend(j,{url:g||a.sAjaxSource})):h.isFunction(g)?a.jqXHR=g.call(i,b,c,a):(a.jqXHR=h.ajax(h.extend(j,g)),g.data=f)}function kb(a){return a.bAjaxDataGet?(a.iDraw++,B(a,!0),qa(a,tb(a),function(b){ub(a,b)}),!1):!0}function tb(a){var b=a.aoColumns,c=b.length,d=a.oFeatures,e=a.oPreviousSearch,f=a.aoPreSearchCols,g,i=[],j,n,m,o=T(a);g=a._iDisplayStart;j=!1!==d.bPaginate?a._iDisplayLength:-1;var k=function(a,
b){i.push({name:a,value:b})};k("sEcho",a.iDraw);k("iColumns",c);k("sColumns",C(b,"sName").join(","));k("iDisplayStart",g);k("iDisplayLength",j);var l={draw:a.iDraw,columns:[],order:[],start:g,length:j,search:{value:e.sSearch,regex:e.bRegex}};for(g=0;g<c;g++)n=b[g],m=f[g],j="function"==typeof n.mData?"function":n.mData,l.columns.push({data:j,name:n.sName,searchable:n.bSearchable,orderable:n.bSortable,search:{value:m.sSearch,regex:m.bRegex}}),k("mDataProp_"+g,j),d.bFilter&&(k("sSearch_"+g,m.sSearch),
k("bRegex_"+g,m.bRegex),k("bSearchable_"+g,n.bSearchable)),d.bSort&&k("bSortable_"+g,n.bSortable);d.bFilter&&(k("sSearch",e.sSearch),k("bRegex",e.bRegex));d.bSort&&(h.each(o,function(a,b){l.order.push({column:b.col,dir:b.dir});k("iSortCol_"+a,b.col);k("sSortDir_"+a,b.dir)}),k("iSortingCols",o.length));b=p.ext.legacy.ajax;return null===b?a.sAjaxSource?i:l:b?i:l}function ub(a,b){var c=b.sEcho!==l?b.sEcho:b.draw,d=b.iTotalRecords!==l?b.iTotalRecords:b.recordsTotal,e=b.iTotalDisplayRecords!==l?b.iTotalDisplayRecords:
b.recordsFiltered;if(c){if(1*c<a.iDraw)return;a.iDraw=1*c}ma(a);a._iRecordsTotal=parseInt(d,10);a._iRecordsDisplay=parseInt(e,10);c=ra(a,b);d=0;for(e=c.length;d<e;d++)I(a,c[d]);a.aiDisplay=a.aiDisplayMaster.slice();a.bAjaxDataGet=!1;L(a);a._bInitComplete||sa(a,b);a.bAjaxDataGet=!0;B(a,!1)}function ra(a,b){var c=h.isPlainObject(a.ajax)&&a.ajax.dataSrc!==l?a.ajax.dataSrc:a.sAjaxDataProp;return"data"===c?b.aaData||b[c]:""!==c?W(c)(b):b}function ob(a){var b=a.oClasses,c=a.sTableId,d=a.oLanguage,e=a.oPreviousSearch,
f=a.aanFeatures,g='<input type="search" class="'+b.sFilterInput+'"/>',i=d.sSearch,i=i.match(/_INPUT_/)?i.replace("_INPUT_",g):i+g,b=h("<div/>",{id:!f.f?c+"_filter":null,"class":b.sFilter}).append(h("<label/>").append(i)),f=function(){var b=!this.value?"":this.value;b!=e.sSearch&&(ea(a,{sSearch:b,bRegex:e.bRegex,bSmart:e.bSmart,bCaseInsensitive:e.bCaseInsensitive}),a._iDisplayStart=0,L(a))},g=null!==a.searchDelay?a.searchDelay:"ssp"===A(a)?400:0,j=h("input",b).val(e.sSearch).attr("placeholder",d.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT",
g?ta(f,g):f).bind("keypress.DT",function(a){if(13==a.keyCode)return!1}).attr("aria-controls",c);h(a.nTable).on("search.dt.DT",function(b,c){if(a===c)try{j[0]!==P.activeElement&&j.val(e.sSearch)}catch(d){}});return b[0]}function ea(a,b,c){var d=a.oPreviousSearch,e=a.aoPreSearchCols,f=function(a){d.sSearch=a.sSearch;d.bRegex=a.bRegex;d.bSmart=a.bSmart;d.bCaseInsensitive=a.bCaseInsensitive};Ga(a);if("ssp"!=A(a)){vb(a,b.sSearch,c,b.bEscapeRegex!==l?!b.bEscapeRegex:b.bRegex,b.bSmart,b.bCaseInsensitive);
f(b);for(b=0;b<e.length;b++)wb(a,e[b].sSearch,b,e[b].bEscapeRegex!==l?!e[b].bEscapeRegex:e[b].bRegex,e[b].bSmart,e[b].bCaseInsensitive);xb(a)}else f(b);a.bFiltered=!0;u(a,null,"search",[a])}function xb(a){for(var b=p.ext.search,c=a.aiDisplay,d,e,f=0,g=b.length;f<g;f++){for(var i=[],j=0,h=c.length;j<h;j++)e=c[j],d=a.aoData[e],b[f](a,d._aFilterData,e,d._aData,j)&&i.push(e);c.length=0;c.push.apply(c,i)}}function wb(a,b,c,d,e,f){if(""!==b)for(var g=a.aiDisplay,d=Pa(b,d,e,f),e=g.length-1;0<=e;e--)b=a.aoData[g[e]]._aFilterData[c],
d.test(b)||g.splice(e,1)}function vb(a,b,c,d,e,f){var d=Pa(b,d,e,f),e=a.oPreviousSearch.sSearch,f=a.aiDisplayMaster,g;0!==p.ext.search.length&&(c=!0);g=yb(a);if(0>=b.length)a.aiDisplay=f.slice();else{if(g||c||e.length>b.length||0!==b.indexOf(e)||a.bSorted)a.aiDisplay=f.slice();b=a.aiDisplay;for(c=b.length-1;0<=c;c--)d.test(a.aoData[b[c]]._sFilterRow)||b.splice(c,1)}}function Pa(a,b,c,d){a=b?a:Qa(a);c&&(a="^(?=.*?"+h.map(a.match(/"[^"]+"|[^ ]+/g)||"",function(a){if('"'===a.charAt(0))var b=a.match(/^"(.*)"$/),
a=b?b[1]:a;return a.replace('"',"")}).join(")(?=.*?")+").*$");return RegExp(a,d?"i":"")}function Qa(a){return a.replace(Xb,"\\$1")}function yb(a){var b=a.aoColumns,c,d,e,f,g,i,j,h,m=p.ext.type.search;c=!1;d=0;for(f=a.aoData.length;d<f;d++)if(h=a.aoData[d],!h._aFilterData){i=[];e=0;for(g=b.length;e<g;e++)c=b[e],c.bSearchable?(j=w(a,d,e,"filter"),m[c.sType]&&(j=m[c.sType](j)),null===j&&(j=""),"string"!==typeof j&&j.toString&&(j=j.toString())):j="",j.indexOf&&-1!==j.indexOf("&")&&(ua.innerHTML=j,j=Yb?
ua.textContent:ua.innerText),j.replace&&(j=j.replace(/[\r\n]/g,"")),i.push(j);h._aFilterData=i;h._sFilterRow=i.join(" ");c=!0}return c}function zb(a){return{search:a.sSearch,smart:a.bSmart,regex:a.bRegex,caseInsensitive:a.bCaseInsensitive}}function Ab(a){return{sSearch:a.search,bSmart:a.smart,bRegex:a.regex,bCaseInsensitive:a.caseInsensitive}}function rb(a){var b=a.sTableId,c=a.aanFeatures.i,d=h("<div/>",{"class":a.oClasses.sInfo,id:!c?b+"_info":null});c||(a.aoDrawCallback.push({fn:Bb,sName:"information"}),
d.attr("role","status").attr("aria-live","polite"),h(a.nTable).attr("aria-describedby",b+"_info"));return d[0]}function Bb(a){var b=a.aanFeatures.i;if(0!==b.length){var c=a.oLanguage,d=a._iDisplayStart+1,e=a.fnDisplayEnd(),f=a.fnRecordsTotal(),g=a.fnRecordsDisplay(),i=g?c.sInfo:c.sInfoEmpty;g!==f&&(i+=" "+c.sInfoFiltered);i+=c.sInfoPostFix;i=Cb(a,i);c=c.fnInfoCallback;null!==c&&(i=c.call(a.oInstance,a,d,e,f,g,i));h(b).html(i)}}function Cb(a,b){var c=a.fnFormatNumber,d=a._iDisplayStart+1,e=a._iDisplayLength,
f=a.fnRecordsDisplay(),g=-1===e;return b.replace(/_START_/g,c.call(a,d)).replace(/_END_/g,c.call(a,a.fnDisplayEnd())).replace(/_MAX_/g,c.call(a,a.fnRecordsTotal())).replace(/_TOTAL_/g,c.call(a,f)).replace(/_PAGE_/g,c.call(a,g?1:Math.ceil(d/e))).replace(/_PAGES_/g,c.call(a,g?1:Math.ceil(f/e)))}function va(a){var b,c,d=a.iInitDisplayStart,e=a.aoColumns,f;c=a.oFeatures;if(a.bInitialised){mb(a);jb(a);da(a,a.aoHeader);da(a,a.aoFooter);B(a,!0);c.bAutoWidth&&Fa(a);b=0;for(c=e.length;b<c;b++)f=e[b],f.sWidth&&
(f.nTh.style.width=s(f.sWidth));M(a);e=A(a);"ssp"!=e&&("ajax"==e?qa(a,[],function(c){var f=ra(a,c);for(b=0;b<f.length;b++)I(a,f[b]);a.iInitDisplayStart=d;M(a);B(a,!1);sa(a,c)},a):(B(a,!1),sa(a)))}else setTimeout(function(){va(a)},200)}function sa(a,b){a._bInitComplete=!0;b&&X(a);u(a,"aoInitComplete","init",[a,b])}function Ra(a,b){var c=parseInt(b,10);a._iDisplayLength=c;Sa(a);u(a,null,"length",[a,c])}function nb(a){for(var b=a.oClasses,c=a.sTableId,d=a.aLengthMenu,e=h.isArray(d[0]),f=e?d[0]:d,d=e?
d[1]:d,e=h("<select/>",{name:c+"_length","aria-controls":c,"class":b.sLengthSelect}),g=0,i=f.length;g<i;g++)e[0][g]=new Option(d[g],f[g]);var j=h("<div><label/></div>").addClass(b.sLength);a.aanFeatures.l||(j[0].id=c+"_length");j.children().append(a.oLanguage.sLengthMenu.replace("_MENU_",e[0].outerHTML));h("select",j).val(a._iDisplayLength).bind("change.DT",function(){Ra(a,h(this).val());L(a)});h(a.nTable).bind("length.dt.DT",function(b,c,d){a===c&&h("select",j).val(d)});return j[0]}function sb(a){var b=
a.sPaginationType,c=p.ext.pager[b],d="function"===typeof c,e=function(a){L(a)},b=h("<div/>").addClass(a.oClasses.sPaging+b)[0],f=a.aanFeatures;d||c.fnInit(a,b,e);f.p||(b.id=a.sTableId+"_paginate",a.aoDrawCallback.push({fn:function(a){if(d){var b=a._iDisplayStart,j=a._iDisplayLength,h=a.fnRecordsDisplay(),m=-1===j,b=m?0:Math.ceil(b/j),j=m?1:Math.ceil(h/j),h=c(b,j),o,m=0;for(o=f.p.length;m<o;m++)Oa(a,"pageButton")(a,f.p[m],m,h,b,j)}else c.fnUpdate(a,e)},sName:"pagination"}));return b}function Ta(a,
b,c){var d=a._iDisplayStart,e=a._iDisplayLength,f=a.fnRecordsDisplay();0===f||-1===e?d=0:"number"===typeof b?(d=b*e,d>f&&(d=0)):"first"==b?d=0:"previous"==b?(d=0<=e?d-e:0,0>d&&(d=0)):"next"==b?d+e<f&&(d+=e):"last"==b?d=Math.floor((f-1)/e)*e:R(a,0,"Unknown paging action: "+b,5);b=a._iDisplayStart!==d;a._iDisplayStart=d;b&&(u(a,null,"page",[a]),c&&L(a));return b}function pb(a){return h("<div/>",{id:!a.aanFeatures.r?a.sTableId+"_processing":null,"class":a.oClasses.sProcessing}).html(a.oLanguage.sProcessing).insertBefore(a.nTable)[0]}
function B(a,b){a.oFeatures.bProcessing&&h(a.aanFeatures.r).css("display",b?"block":"none");u(a,null,"processing",[a,b])}function qb(a){var b=h(a.nTable);b.attr("role","grid");var c=a.oScroll;if(""===c.sX&&""===c.sY)return a.nTable;var d=c.sX,e=c.sY,f=a.oClasses,g=b.children("caption"),i=g.length?g[0]._captionSide:null,j=h(b[0].cloneNode(!1)),n=h(b[0].cloneNode(!1)),m=b.children("tfoot");c.sX&&"100%"===b.attr("width")&&b.removeAttr("width");m.length||(m=null);c=h("<div/>",{"class":f.sScrollWrapper}).append(h("<div/>",
{"class":f.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:d?!d?null:s(d):"100%"}).append(h("<div/>",{"class":f.sScrollHeadInner}).css({"box-sizing":"content-box",width:c.sXInner||"100%"}).append(j.removeAttr("id").css("margin-left",0).append(b.children("thead")))).append("top"===i?g:null)).append(h("<div/>",{"class":f.sScrollBody}).css({overflow:"auto",height:!e?null:s(e),width:!d?null:s(d)}).append(b));m&&c.append(h("<div/>",{"class":f.sScrollFoot}).css({overflow:"hidden",
border:0,width:d?!d?null:s(d):"100%"}).append(h("<div/>",{"class":f.sScrollFootInner}).append(n.removeAttr("id").css("margin-left",0).append(b.children("tfoot")))).append("bottom"===i?g:null));var b=c.children(),o=b[0],f=b[1],k=m?b[2]:null;d&&h(f).scroll(function(){var a=this.scrollLeft;o.scrollLeft=a;m&&(k.scrollLeft=a)});a.nScrollHead=o;a.nScrollBody=f;a.nScrollFoot=k;a.aoDrawCallback.push({fn:Y,sName:"scrolling"});return c[0]}function Y(a){var b=a.oScroll,c=b.sX,d=b.sXInner,e=b.sY,f=b.iBarWidth,
g=h(a.nScrollHead),i=g[0].style,j=g.children("div"),n=j[0].style,m=j.children("table"),j=a.nScrollBody,o=h(j),k=j.style,l=h(a.nScrollFoot).children("div"),p=l.children("table"),r=h(a.nTHead),q=h(a.nTable),fa=q[0],N=fa.style,J=a.nTFoot?h(a.nTFoot):null,t=a.oBrowser,u=t.bScrollOversize,x,v,w,K,y,z=[],A=[],B=[],C,D=function(a){a=a.style;a.paddingTop="0";a.paddingBottom="0";a.borderTopWidth="0";a.borderBottomWidth="0";a.height=0};q.children("thead, tfoot").remove();y=r.clone().prependTo(q);x=r.find("tr");
w=y.find("tr");y.find("th, td").removeAttr("tabindex");J&&(K=J.clone().prependTo(q),v=J.find("tr"),K=K.find("tr"));c||(k.width="100%",g[0].style.width="100%");h.each(pa(a,y),function(b,c){C=ja(a,b);c.style.width=a.aoColumns[C].sWidth});J&&F(function(a){a.style.width=""},K);b.bCollapse&&""!==e&&(k.height=o[0].offsetHeight+r[0].offsetHeight+"px");g=q.outerWidth();if(""===c){if(N.width="100%",u&&(q.find("tbody").height()>j.offsetHeight||"scroll"==o.css("overflow-y")))N.width=s(q.outerWidth()-f)}else""!==
d?N.width=s(d):g==o.width()&&o.height()<q.height()?(N.width=s(g-f),q.outerWidth()>g-f&&(N.width=s(g))):N.width=s(g);g=q.outerWidth();F(D,w);F(function(a){B.push(a.innerHTML);z.push(s(h(a).css("width")))},w);F(function(a,b){a.style.width=z[b]},x);h(w).height(0);J&&(F(D,K),F(function(a){A.push(s(h(a).css("width")))},K),F(function(a,b){a.style.width=A[b]},v),h(K).height(0));F(function(a,b){a.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+B[b]+"</div>";a.style.width=z[b]},
w);J&&F(function(a,b){a.innerHTML="";a.style.width=A[b]},K);if(q.outerWidth()<g){v=j.scrollHeight>j.offsetHeight||"scroll"==o.css("overflow-y")?g+f:g;if(u&&(j.scrollHeight>j.offsetHeight||"scroll"==o.css("overflow-y")))N.width=s(v-f);(""===c||""!==d)&&R(a,1,"Possible column misalignment",6)}else v="100%";k.width=s(v);i.width=s(v);J&&(a.nScrollFoot.style.width=s(v));!e&&u&&(k.height=s(fa.offsetHeight+f));e&&b.bCollapse&&(k.height=s(e),b=c&&fa.offsetWidth>j.offsetWidth?f:0,fa.offsetHeight<j.offsetHeight&&
(k.height=s(fa.offsetHeight+b)));b=q.outerWidth();m[0].style.width=s(b);n.width=s(b);m=q.height()>j.clientHeight||"scroll"==o.css("overflow-y");t="padding"+(t.bScrollbarLeft?"Left":"Right");n[t]=m?f+"px":"0px";J&&(p[0].style.width=s(b),l[0].style.width=s(b),l[0].style[t]=m?f+"px":"0px");o.scroll();if((a.bSorted||a.bFiltered)&&!a._drawHold)j.scrollTop=0}function F(a,b,c){for(var d=0,e=0,f=b.length,g,i;e<f;){g=b[e].firstChild;for(i=c?c[e].firstChild:null;g;)1===g.nodeType&&(c?a(g,i,d):a(g,d),d++),g=
g.nextSibling,i=c?i.nextSibling:null;e++}}function Fa(a){var b=a.nTable,c=a.aoColumns,d=a.oScroll,e=d.sY,f=d.sX,g=d.sXInner,i=c.length,d=Z(a,"bVisible"),j=h("th",a.nTHead),n=b.getAttribute("width"),m=b.parentNode,o=!1,k,l;for(k=0;k<d.length;k++)l=c[d[k]],null!==l.sWidth&&(l.sWidth=Db(l.sWidthOrig,m),o=!0);if(!o&&!f&&!e&&i==aa(a)&&i==j.length)for(k=0;k<i;k++)c[k].sWidth=s(j.eq(k).width());else{i=h(b).clone().empty().css("visibility","hidden").removeAttr("id").append(h(a.nTHead).clone(!1)).append(h(a.nTFoot).clone(!1)).append(h("<tbody><tr/></tbody>"));
i.find("tfoot th, tfoot td").css("width","");var p=i.find("tbody tr"),j=pa(a,i.find("thead")[0]);for(k=0;k<d.length;k++)l=c[d[k]],j[k].style.width=null!==l.sWidthOrig&&""!==l.sWidthOrig?s(l.sWidthOrig):"";if(a.aoData.length)for(k=0;k<d.length;k++)o=d[k],l=c[o],h(Eb(a,o)).clone(!1).append(l.sContentPadding).appendTo(p);i.appendTo(m);f&&g?i.width(g):f?(i.css("width","auto"),i.width()<m.offsetWidth&&i.width(m.offsetWidth)):e?i.width(m.offsetWidth):n&&i.width(n);Fb(a,i[0]);if(f){for(k=g=0;k<d.length;k++)l=
c[d[k]],e=h(j[k]).outerWidth(),g+=null===l.sWidthOrig?e:parseInt(l.sWidth,10)+e-h(j[k]).width();i.width(s(g));b.style.width=s(g)}for(k=0;k<d.length;k++)if(l=c[d[k]],e=h(j[k]).width())l.sWidth=s(e);b.style.width=s(i.css("width"));i.remove()}n&&(b.style.width=s(n));if((n||f)&&!a._reszEvt)h(Da).bind("resize.DT-"+a.sInstance,ta(function(){X(a)})),a._reszEvt=!0}function ta(a,b){var c=b!==l?b:200,d,e;return function(){var b=this,g=+new Date,i=arguments;d&&g<d+c?(clearTimeout(e),e=setTimeout(function(){d=
l;a.apply(b,i)},c)):d?(d=g,a.apply(b,i)):d=g}}function Db(a,b){if(!a)return 0;var c=h("<div/>").css("width",s(a)).appendTo(b||P.body),d=c[0].offsetWidth;c.remove();return d}function Fb(a,b){var c=a.oScroll;if(c.sX||c.sY)c=!c.sX?c.iBarWidth:0,b.style.width=s(h(b).outerWidth()-c)}function Eb(a,b){var c=Gb(a,b);if(0>c)return null;var d=a.aoData[c];return!d.nTr?h("<td/>").html(w(a,c,b,"display"))[0]:d.anCells[b]}function Gb(a,b){for(var c,d=-1,e=-1,f=0,g=a.aoData.length;f<g;f++)c=w(a,f,b,"display")+"",
c=c.replace(Zb,""),c.length>d&&(d=c.length,e=f);return e}function s(a){return null===a?"0px":"number"==typeof a?0>a?"0px":a+"px":a.match(/\d$/)?a+"px":a}function Hb(){if(!p.__scrollbarWidth){var a=h("<p/>").css({width:"100%",height:200,padding:0})[0],b=h("<div/>").css({position:"absolute",top:0,left:0,width:200,height:150,padding:0,overflow:"hidden",visibility:"hidden"}).append(a).appendTo("body"),c=a.offsetWidth;b.css("overflow","scroll");a=a.offsetWidth;c===a&&(a=b[0].clientWidth);b.remove();p.__scrollbarWidth=
c-a}return p.__scrollbarWidth}function T(a){var b,c,d=[],e=a.aoColumns,f,g,i,j;b=a.aaSortingFixed;c=h.isPlainObject(b);var n=[];f=function(a){a.length&&!h.isArray(a[0])?n.push(a):n.push.apply(n,a)};h.isArray(b)&&f(b);c&&b.pre&&f(b.pre);f(a.aaSorting);c&&b.post&&f(b.post);for(a=0;a<n.length;a++){j=n[a][0];f=e[j].aDataSort;b=0;for(c=f.length;b<c;b++)g=f[b],i=e[g].sType||"string",n[a]._idx===l&&(n[a]._idx=h.inArray(n[a][1],e[g].asSorting)),d.push({src:j,col:g,dir:n[a][1],index:n[a]._idx,type:i,formatter:p.ext.type.order[i+
"-pre"]})}return d}function lb(a){var b,c,d=[],e=p.ext.type.order,f=a.aoData,g=0,i,h=a.aiDisplayMaster,n;Ga(a);n=T(a);b=0;for(c=n.length;b<c;b++)i=n[b],i.formatter&&g++,Ib(a,i.col);if("ssp"!=A(a)&&0!==n.length){b=0;for(c=h.length;b<c;b++)d[h[b]]=b;g===n.length?h.sort(function(a,b){var c,e,g,i,h=n.length,j=f[a]._aSortData,l=f[b]._aSortData;for(g=0;g<h;g++)if(i=n[g],c=j[i.col],e=l[i.col],c=c<e?-1:c>e?1:0,0!==c)return"asc"===i.dir?c:-c;c=d[a];e=d[b];return c<e?-1:c>e?1:0}):h.sort(function(a,b){var c,
g,i,h,j=n.length,l=f[a]._aSortData,p=f[b]._aSortData;for(i=0;i<j;i++)if(h=n[i],c=l[h.col],g=p[h.col],h=e[h.type+"-"+h.dir]||e["string-"+h.dir],c=h(c,g),0!==c)return c;c=d[a];g=d[b];return c<g?-1:c>g?1:0})}a.bSorted=!0}function Jb(a){for(var b,c,d=a.aoColumns,e=T(a),a=a.oLanguage.oAria,f=0,g=d.length;f<g;f++){c=d[f];var i=c.asSorting;b=c.sTitle.replace(/<.*?>/g,"");var h=c.nTh;h.removeAttribute("aria-sort");c.bSortable&&(0<e.length&&e[0].col==f?(h.setAttribute("aria-sort","asc"==e[0].dir?"ascending":
"descending"),c=i[e[0].index+1]||i[0]):c=i[0],b+="asc"===c?a.sSortAscending:a.sSortDescending);h.setAttribute("aria-label",b)}}function Ua(a,b,c,d){var e=a.aaSorting,f=a.aoColumns[b].asSorting,g=function(a,b){var c=a._idx;c===l&&(c=h.inArray(a[1],f));return c+1<f.length?c+1:b?null:0};"number"===typeof e[0]&&(e=a.aaSorting=[e]);c&&a.oFeatures.bSortMulti?(c=h.inArray(b,C(e,"0")),-1!==c?(b=g(e[c],!0),null===b?e.splice(c,1):(e[c][1]=f[b],e[c]._idx=b)):(e.push([b,f[0],0]),e[e.length-1]._idx=0)):e.length&&
e[0][0]==b?(b=g(e[0]),e.length=1,e[0][1]=f[b],e[0]._idx=b):(e.length=0,e.push([b,f[0]]),e[0]._idx=0);M(a);"function"==typeof d&&d(a)}function Na(a,b,c,d){var e=a.aoColumns[c];Va(b,{},function(b){!1!==e.bSortable&&(a.oFeatures.bProcessing?(B(a,!0),setTimeout(function(){Ua(a,c,b.shiftKey,d);"ssp"!==A(a)&&B(a,!1)},0)):Ua(a,c,b.shiftKey,d))})}function wa(a){var b=a.aLastSort,c=a.oClasses.sSortColumn,d=T(a),e=a.oFeatures,f,g;if(e.bSort&&e.bSortClasses){e=0;for(f=b.length;e<f;e++)g=b[e].src,h(C(a.aoData,
"anCells",g)).removeClass(c+(2>e?e+1:3));e=0;for(f=d.length;e<f;e++)g=d[e].src,h(C(a.aoData,"anCells",g)).addClass(c+(2>e?e+1:3))}a.aLastSort=d}function Ib(a,b){var c=a.aoColumns[b],d=p.ext.order[c.sSortDataType],e;d&&(e=d.call(a.oInstance,a,b,$(a,b)));for(var f,g=p.ext.type.order[c.sType+"-pre"],i=0,h=a.aoData.length;i<h;i++)if(c=a.aoData[i],c._aSortData||(c._aSortData=[]),!c._aSortData[b]||d)f=d?e[i]:w(a,i,b,"sort"),c._aSortData[b]=g?g(f):f}function xa(a){if(a.oFeatures.bStateSave&&!a.bDestroying){var b=
{time:+new Date,start:a._iDisplayStart,length:a._iDisplayLength,order:h.extend(!0,[],a.aaSorting),search:zb(a.oPreviousSearch),columns:h.map(a.aoColumns,function(b,d){return{visible:b.bVisible,search:zb(a.aoPreSearchCols[d])}})};u(a,"aoStateSaveParams","stateSaveParams",[a,b]);a.oSavedState=b;a.fnStateSaveCallback.call(a.oInstance,a,b)}}function Kb(a){var b,c,d=a.aoColumns;if(a.oFeatures.bStateSave){var e=a.fnStateLoadCallback.call(a.oInstance,a);if(e&&e.time&&(b=u(a,"aoStateLoadParams","stateLoadParams",
[a,e]),-1===h.inArray(!1,b)&&(b=a.iStateDuration,!(0<b&&e.time<+new Date-1E3*b)&&d.length===e.columns.length))){a.oLoadedState=h.extend(!0,{},e);a._iDisplayStart=e.start;a.iInitDisplayStart=e.start;a._iDisplayLength=e.length;a.aaSorting=[];h.each(e.order,function(b,c){a.aaSorting.push(c[0]>=d.length?[0,c[1]]:c)});h.extend(a.oPreviousSearch,Ab(e.search));b=0;for(c=e.columns.length;b<c;b++){var f=e.columns[b];d[b].bVisible=f.visible;h.extend(a.aoPreSearchCols[b],Ab(f.search))}u(a,"aoStateLoaded","stateLoaded",
[a,e])}}}function ya(a){var b=p.settings,a=h.inArray(a,C(b,"nTable"));return-1!==a?b[a]:null}function R(a,b,c,d){c="DataTables warning: "+(null!==a?"table id="+a.sTableId+" - ":"")+c;d&&(c+=". For more information about this error, please see http://datatables.net/tn/"+d);if(b)Da.console&&console.log&&console.log(c);else if(a=p.ext,"alert"==(a.sErrMode||a.errMode))alert(c);else throw Error(c);}function D(a,b,c,d){h.isArray(c)?h.each(c,function(c,d){h.isArray(d)?D(a,b,d[0],d[1]):D(a,b,d)}):(d===l&&
(d=c),b[c]!==l&&(a[d]=b[c]))}function Lb(a,b,c){var d,e;for(e in b)b.hasOwnProperty(e)&&(d=b[e],h.isPlainObject(d)?(h.isPlainObject(a[e])||(a[e]={}),h.extend(!0,a[e],d)):a[e]=c&&"data"!==e&&"aaData"!==e&&h.isArray(d)?d.slice():d);return a}function Va(a,b,c){h(a).bind("click.DT",b,function(b){a.blur();c(b)}).bind("keypress.DT",b,function(a){13===a.which&&(a.preventDefault(),c(a))}).bind("selectstart.DT",function(){return!1})}function y(a,b,c,d){c&&a[b].push({fn:c,sName:d})}function u(a,b,c,d){var e=
[];b&&(e=h.map(a[b].slice().reverse(),function(b){return b.fn.apply(a.oInstance,d)}));null!==c&&h(a.nTable).trigger(c+".dt",d);return e}function Sa(a){var b=a._iDisplayStart,c=a.fnDisplayEnd(),d=a._iDisplayLength;b>=c&&(b=c-d);if(-1===d||0>b)b=0;a._iDisplayStart=b}function Oa(a,b){var c=a.renderer,d=p.ext.renderer[b];return h.isPlainObject(c)&&c[b]?d[c[b]]||d._:"string"===typeof c?d[c]||d._:d._}function A(a){return a.oFeatures.bServerSide?"ssp":a.ajax||a.sAjaxSource?"ajax":"dom"}function Wa(a,b){var c=
[],c=Mb.numbers_length,d=Math.floor(c/2);b<=c?c=U(0,b):a<=d?(c=U(0,c-2),c.push("ellipsis"),c.push(b-1)):(a>=b-1-d?c=U(b-(c-2),b):(c=U(a-1,a+2),c.push("ellipsis"),c.push(b-1)),c.splice(0,0,"ellipsis"),c.splice(0,0,0));c.DT_el="span";return c}function db(a){h.each({num:function(b){return za(b,a)},"num-fmt":function(b){return za(b,a,Xa)},"html-num":function(b){return za(b,a,Aa)},"html-num-fmt":function(b){return za(b,a,Aa,Xa)}},function(b,c){v.type.order[b+a+"-pre"]=c})}function Nb(a){return function(){var b=
[ya(this[p.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return p.ext.internal[a].apply(this,b)}}var p,v,q,r,t,Ya={},Ob=/[\r\n]/g,Aa=/<.*?>/g,$b=/^[\w\+\-]/,ac=/[\w\+\-]$/,Xb=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"),Xa=/[',$\u00a3\u20ac\u00a5%\u2009\u202F]/g,H=function(a){return!a||!0===a||"-"===a?!0:!1},Pb=function(a){var b=parseInt(a,10);return!isNaN(b)&&isFinite(a)?b:null},Qb=function(a,b){Ya[b]||(Ya[b]=RegExp(Qa(b),"g"));return"string"===
typeof a&&"."!==b?a.replace(/\./g,"").replace(Ya[b],"."):a},Za=function(a,b,c){var d="string"===typeof a;b&&d&&(a=Qb(a,b));c&&d&&(a=a.replace(Xa,""));return H(a)||!isNaN(parseFloat(a))&&isFinite(a)},Rb=function(a,b,c){return H(a)?!0:!(H(a)||"string"===typeof a)?null:Za(a.replace(Aa,""),b,c)?!0:null},C=function(a,b,c){var d=[],e=0,f=a.length;if(c!==l)for(;e<f;e++)a[e]&&a[e][b]&&d.push(a[e][b][c]);else for(;e<f;e++)a[e]&&d.push(a[e][b]);return d},ga=function(a,b,c,d){var e=[],f=0,g=b.length;if(d!==
l)for(;f<g;f++)e.push(a[b[f]][c][d]);else for(;f<g;f++)e.push(a[b[f]][c]);return e},U=function(a,b){var c=[],d;b===l?(b=0,d=a):(d=b,b=a);for(var e=b;e<d;e++)c.push(e);return c},Ma=function(a){var b=[],c,d,e=a.length,f,g=0;d=0;a:for(;d<e;d++){c=a[d];for(f=0;f<g;f++)if(b[f]===c)continue a;b.push(c);g++}return b},z=function(a,b,c){a[b]!==l&&(a[c]=a[b])},ba=/\[.*?\]$/,S=/\(\)$/,ua=h("<div>")[0],Yb=ua.textContent!==l,Zb=/<.*?>/g;p=function(a){this.$=function(a,b){return this.api(!0).$(a,b)};this._=function(a,
b){return this.api(!0).rows(a,b).data()};this.api=function(a){return a?new q(ya(this[v.iApiIndex])):new q(this)};this.fnAddData=function(a,b){var c=this.api(!0),d=h.isArray(a)&&(h.isArray(a[0])||h.isPlainObject(a[0]))?c.rows.add(a):c.row.add(a);(b===l||b)&&c.draw();return d.flatten().toArray()};this.fnAdjustColumnSizing=function(a){var b=this.api(!0).columns.adjust(),c=b.settings()[0],d=c.oScroll;a===l||a?b.draw(!1):(""!==d.sX||""!==d.sY)&&Y(c)};this.fnClearTable=function(a){var b=this.api(!0).clear();
(a===l||a)&&b.draw()};this.fnClose=function(a){this.api(!0).row(a).child.hide()};this.fnDeleteRow=function(a,b,c){var d=this.api(!0),a=d.rows(a),e=a.settings()[0],h=e.aoData[a[0][0]];a.remove();b&&b.call(this,e,h);(c===l||c)&&d.draw();return h};this.fnDestroy=function(a){this.api(!0).destroy(a)};this.fnDraw=function(a){this.api(!0).draw(!a)};this.fnFilter=function(a,b,c,d,e,h){e=this.api(!0);null===b||b===l?e.search(a,c,d,h):e.column(b).search(a,c,d,h);e.draw()};this.fnGetData=function(a,b){var c=
this.api(!0);if(a!==l){var d=a.nodeName?a.nodeName.toLowerCase():"";return b!==l||"td"==d||"th"==d?c.cell(a,b).data():c.row(a).data()||null}return c.data().toArray()};this.fnGetNodes=function(a){var b=this.api(!0);return a!==l?b.row(a).node():b.rows().nodes().flatten().toArray()};this.fnGetPosition=function(a){var b=this.api(!0),c=a.nodeName.toUpperCase();return"TR"==c?b.row(a).index():"TD"==c||"TH"==c?(a=b.cell(a).index(),[a.row,a.columnVisible,a.column]):null};this.fnIsOpen=function(a){return this.api(!0).row(a).child.isShown()};
this.fnOpen=function(a,b,c){return this.api(!0).row(a).child(b,c).show().child()[0]};this.fnPageChange=function(a,b){var c=this.api(!0).page(a);(b===l||b)&&c.draw(!1)};this.fnSetColumnVis=function(a,b,c){a=this.api(!0).column(a).visible(b);(c===l||c)&&a.columns.adjust().draw()};this.fnSettings=function(){return ya(this[v.iApiIndex])};this.fnSort=function(a){this.api(!0).order(a).draw()};this.fnSortListener=function(a,b,c){this.api(!0).order.listener(a,b,c)};this.fnUpdate=function(a,b,c,d,e){var h=
this.api(!0);c===l||null===c?h.row(b).data(a):h.cell(b,c).data(a);(e===l||e)&&h.columns.adjust();(d===l||d)&&h.draw();return 0};this.fnVersionCheck=v.fnVersionCheck;var b=this,c=a===l,d=this.length;c&&(a={});this.oApi=this.internal=v.internal;for(var e in p.ext.internal)e&&(this[e]=Nb(e));this.each(function(){var e={},g=1<d?Lb(e,a,!0):a,i=0,j,n=this.getAttribute("id"),e=!1,m=p.defaults;if("table"!=this.nodeName.toLowerCase())R(null,0,"Non-table node initialisation ("+this.nodeName+")",2);else{eb(m);
fb(m.column);G(m,m,!0);G(m.column,m.column,!0);G(m,g);var o=p.settings,i=0;for(j=o.length;i<j;i++){if(o[i].nTable==this){j=g.bRetrieve!==l?g.bRetrieve:m.bRetrieve;if(c||j)return o[i].oInstance;if(g.bDestroy!==l?g.bDestroy:m.bDestroy){o[i].oInstance.fnDestroy();break}else{R(o[i],0,"Cannot reinitialise DataTable",3);return}}if(o[i].sTableId==this.id){o.splice(i,1);break}}if(null===n||""===n)this.id=n="DataTables_Table_"+p.ext._unique++;var k=h.extend(!0,{},p.models.oSettings,{nTable:this,oApi:b.internal,
oInit:g,sDestroyWidth:h(this)[0].style.width,sInstance:n,sTableId:n});o.push(k);k.oInstance=1===b.length?b:h(this).dataTable();eb(g);g.oLanguage&&O(g.oLanguage);g.aLengthMenu&&!g.iDisplayLength&&(g.iDisplayLength=h.isArray(g.aLengthMenu[0])?g.aLengthMenu[0][0]:g.aLengthMenu[0]);g=Lb(h.extend(!0,{},m),g);D(k.oFeatures,g,"bPaginate bLengthChange bFilter bSort bSortMulti bInfo bProcessing bAutoWidth bSortClasses bServerSide bDeferRender".split(" "));D(k,g,["asStripeClasses","ajax","fnServerData","fnFormatNumber",
"sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback","renderer","searchDelay",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);D(k.oScroll,g,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);
D(k.oLanguage,g,"fnInfoCallback");y(k,"aoDrawCallback",g.fnDrawCallback,"user");y(k,"aoServerParams",g.fnServerParams,"user");y(k,"aoStateSaveParams",g.fnStateSaveParams,"user");y(k,"aoStateLoadParams",g.fnStateLoadParams,"user");y(k,"aoStateLoaded",g.fnStateLoaded,"user");y(k,"aoRowCallback",g.fnRowCallback,"user");y(k,"aoRowCreatedCallback",g.fnCreatedRow,"user");y(k,"aoHeaderCallback",g.fnHeaderCallback,"user");y(k,"aoFooterCallback",g.fnFooterCallback,"user");y(k,"aoInitComplete",g.fnInitComplete,
"user");y(k,"aoPreDrawCallback",g.fnPreDrawCallback,"user");n=k.oClasses;g.bJQueryUI?(h.extend(n,p.ext.oJUIClasses,g.oClasses),g.sDom===m.sDom&&"lfrtip"===m.sDom&&(k.sDom='<"H"lfr>t<"F"ip>'),k.renderer)?h.isPlainObject(k.renderer)&&!k.renderer.header&&(k.renderer.header="jqueryui"):k.renderer="jqueryui":h.extend(n,p.ext.classes,g.oClasses);h(this).addClass(n.sTable);if(""!==k.oScroll.sX||""!==k.oScroll.sY)k.oScroll.iBarWidth=Hb();!0===k.oScroll.sX&&(k.oScroll.sX="100%");k.iInitDisplayStart===l&&(k.iInitDisplayStart=
g.iDisplayStart,k._iDisplayStart=g.iDisplayStart);null!==g.iDeferLoading&&(k.bDeferLoading=!0,i=h.isArray(g.iDeferLoading),k._iRecordsDisplay=i?g.iDeferLoading[0]:g.iDeferLoading,k._iRecordsTotal=i?g.iDeferLoading[1]:g.iDeferLoading);""!==g.oLanguage.sUrl?(k.oLanguage.sUrl=g.oLanguage.sUrl,h.getJSON(k.oLanguage.sUrl,null,function(a){O(a);G(m.oLanguage,a);h.extend(true,k.oLanguage,g.oLanguage,a);va(k)}),e=!0):h.extend(!0,k.oLanguage,g.oLanguage);null===g.asStripeClasses&&(k.asStripeClasses=[n.sStripeOdd,
n.sStripeEven]);var i=k.asStripeClasses,r=h("tbody tr:eq(0)",this);-1!==h.inArray(!0,h.map(i,function(a){return r.hasClass(a)}))&&(h("tbody tr",this).removeClass(i.join(" ")),k.asDestroyStripes=i.slice());var o=[],q,i=this.getElementsByTagName("thead");0!==i.length&&(ca(k.aoHeader,i[0]),o=pa(k));if(null===g.aoColumns){q=[];i=0;for(j=o.length;i<j;i++)q.push(null)}else q=g.aoColumns;i=0;for(j=q.length;i<j;i++)Ea(k,o?o[i]:null);ib(k,g.aoColumnDefs,q,function(a,b){ia(k,a,b)});if(r.length){var s=function(a,
b){return a.getAttribute("data-"+b)?b:null};h.each(la(k,r[0]).cells,function(a,b){var c=k.aoColumns[a];if(c.mData===a){var d=s(b,"sort")||s(b,"order"),e=s(b,"filter")||s(b,"search");if(d!==null||e!==null){c.mData={_:a+".display",sort:d!==null?a+".@data-"+d:l,type:d!==null?a+".@data-"+d:l,filter:e!==null?a+".@data-"+e:l};ia(k,a)}}})}var t=k.oFeatures;g.bStateSave&&(t.bStateSave=!0,Kb(k,g),y(k,"aoDrawCallback",xa,"state_save"));if(g.aaSorting===l){o=k.aaSorting;i=0;for(j=o.length;i<j;i++)o[i][1]=k.aoColumns[i].asSorting[0]}wa(k);
t.bSort&&y(k,"aoDrawCallback",function(){if(k.bSorted){var a=T(k),b={};h.each(a,function(a,c){b[c.src]=c.dir});u(k,null,"order",[k,a,b]);Jb(k)}});y(k,"aoDrawCallback",function(){(k.bSorted||A(k)==="ssp"||t.bDeferRender)&&wa(k)},"sc");gb(k);i=h(this).children("caption").each(function(){this._captionSide=h(this).css("caption-side")});j=h(this).children("thead");0===j.length&&(j=h("<thead/>").appendTo(this));k.nTHead=j[0];j=h(this).children("tbody");0===j.length&&(j=h("<tbody/>").appendTo(this));k.nTBody=
j[0];j=h(this).children("tfoot");if(0===j.length&&0<i.length&&(""!==k.oScroll.sX||""!==k.oScroll.sY))j=h("<tfoot/>").appendTo(this);0===j.length||0===j.children().length?h(this).addClass(n.sNoFooter):0<j.length&&(k.nTFoot=j[0],ca(k.aoFooter,k.nTFoot));if(g.aaData)for(i=0;i<g.aaData.length;i++)I(k,g.aaData[i]);else(k.bDeferLoading||"dom"==A(k))&&ka(k,h(k.nTBody).children("tr"));k.aiDisplay=k.aiDisplayMaster.slice();k.bInitialised=!0;!1===e&&va(k)}});b=null;return this};var Sb=[],x=Array.prototype,
bc=function(a){var b,c,d=p.settings,e=h.map(d,function(a){return a.nTable});if(a){if(a.nTable&&a.oApi)return[a];if(a.nodeName&&"table"===a.nodeName.toLowerCase())return b=h.inArray(a,e),-1!==b?[d[b]]:null;if(a&&"function"===typeof a.settings)return a.settings().toArray();"string"===typeof a?c=h(a):a instanceof h&&(c=a)}else return[];if(c)return c.map(function(){b=h.inArray(this,e);return-1!==b?d[b]:null}).toArray()};q=function(a,b){if(!this instanceof q)throw"DT API must be constructed as a new object";
var c=[],d=function(a){(a=bc(a))&&c.push.apply(c,a)};if(h.isArray(a))for(var e=0,f=a.length;e<f;e++)d(a[e]);else d(a);this.context=Ma(c);b&&this.push.apply(this,b.toArray?b.toArray():b);this.selector={rows:null,cols:null,opts:null};q.extend(this,this,Sb)};p.Api=q;q.prototype={concat:x.concat,context:[],each:function(a){for(var b=0,c=this.length;b<c;b++)a.call(this,this[b],b,this);return this},eq:function(a){var b=this.context;return b.length>a?new q(b[a],this[a]):null},filter:function(a){var b=[];
if(x.filter)b=x.filter.call(this,a,this);else for(var c=0,d=this.length;c<d;c++)a.call(this,this[c],c,this)&&b.push(this[c]);return new q(this.context,b)},flatten:function(){var a=[];return new q(this.context,a.concat.apply(a,this.toArray()))},join:x.join,indexOf:x.indexOf||function(a,b){for(var c=b||0,d=this.length;c<d;c++)if(this[c]===a)return c;return-1},iterator:function(a,b,c){var d=[],e,f,g,h,j,n=this.context,m,o,k=this.selector;"string"===typeof a&&(c=b,b=a,a=!1);f=0;for(g=n.length;f<g;f++){var p=
new q(n[f]);if("table"===b)e=c.call(p,n[f],f),e!==l&&d.push(e);else if("columns"===b||"rows"===b)e=c.call(p,n[f],this[f],f),e!==l&&d.push(e);else if("column"===b||"column-rows"===b||"row"===b||"cell"===b){o=this[f];"column-rows"===b&&(m=Ba(n[f],k.opts));h=0;for(j=o.length;h<j;h++)e=o[h],e="cell"===b?c.call(p,n[f],e.row,e.column,f,h):c.call(p,n[f],e,f,h,m),e!==l&&d.push(e)}}return d.length?(a=new q(n,a?d.concat.apply([],d):d),b=a.selector,b.rows=k.rows,b.cols=k.cols,b.opts=k.opts,a):this},lastIndexOf:x.lastIndexOf||
function(a,b){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(a){var b=[];if(x.map)b=x.map.call(this,a,this);else for(var c=0,d=this.length;c<d;c++)b.push(a.call(this,this[c],c));return new q(this.context,b)},pluck:function(a){return this.map(function(b){return b[a]})},pop:x.pop,push:x.push,reduce:x.reduce||function(a,b){return hb(this,a,b,0,this.length,1)},reduceRight:x.reduceRight||function(a,b){return hb(this,a,b,this.length-1,-1,-1)},reverse:x.reverse,selector:null,
shift:x.shift,sort:x.sort,splice:x.splice,toArray:function(){return x.slice.call(this)},to$:function(){return h(this)},toJQuery:function(){return h(this)},unique:function(){return new q(this.context,Ma(this))},unshift:x.unshift};q.extend=function(a,b,c){if(b&&(b instanceof q||b.__dt_wrapper)){var d,e,f,g=function(a,b,c){return function(){var d=b.apply(a,arguments);q.extend(d,d,c.methodExt);return d}};d=0;for(e=c.length;d<e;d++)f=c[d],b[f.name]="function"===typeof f.val?g(a,f.val,f):h.isPlainObject(f.val)?
{}:f.val,b[f.name].__dt_wrapper=!0,q.extend(a,b[f.name],f.propExt)}};q.register=r=function(a,b){if(h.isArray(a))for(var c=0,d=a.length;c<d;c++)q.register(a[c],b);else for(var e=a.split("."),f=Sb,g,i,c=0,d=e.length;c<d;c++){g=(i=-1!==e[c].indexOf("()"))?e[c].replace("()",""):e[c];var j;a:{j=0;for(var n=f.length;j<n;j++)if(f[j].name===g){j=f[j];break a}j=null}j||(j={name:g,val:{},methodExt:[],propExt:[]},f.push(j));c===d-1?j.val=b:f=i?j.methodExt:j.propExt}};q.registerPlural=t=function(a,b,c){q.register(a,
c);q.register(b,function(){var a=c.apply(this,arguments);return a===this?this:a instanceof q?a.length?h.isArray(a[0])?new q(a.context,a[0]):a[0]:l:a})};r("tables()",function(a){var b;if(a){b=q;var c=this.context;if("number"===typeof a)a=[c[a]];else var d=h.map(c,function(a){return a.nTable}),a=h(d).filter(a).map(function(){var a=h.inArray(this,d);return c[a]}).toArray();b=new b(a)}else b=this;return b});r("table()",function(a){var a=this.tables(a),b=a.context;return b.length?new q(b[0]):a});t("tables().nodes()",
"table().node()",function(){return this.iterator("table",function(a){return a.nTable})});t("tables().body()","table().body()",function(){return this.iterator("table",function(a){return a.nTBody})});t("tables().header()","table().header()",function(){return this.iterator("table",function(a){return a.nTHead})});t("tables().footer()","table().footer()",function(){return this.iterator("table",function(a){return a.nTFoot})});t("tables().containers()","table().container()",function(){return this.iterator("table",
function(a){return a.nTableWrapper})});r("draw()",function(a){return this.iterator("table",function(b){M(b,!1===a)})});r("page()",function(a){return a===l?this.page.info().page:this.iterator("table",function(b){Ta(b,a)})});r("page.info()",function(){if(0===this.context.length)return l;var a=this.context[0],b=a._iDisplayStart,c=a._iDisplayLength,d=a.fnRecordsDisplay(),e=-1===c;return{page:e?0:Math.floor(b/c),pages:e?1:Math.ceil(d/c),start:b,end:a.fnDisplayEnd(),length:c,recordsTotal:a.fnRecordsTotal(),
recordsDisplay:d}});r("page.len()",function(a){return a===l?0!==this.context.length?this.context[0]._iDisplayLength:l:this.iterator("table",function(b){Ra(b,a)})});var Tb=function(a,b,c){"ssp"==A(a)?M(a,b):(B(a,!0),qa(a,[],function(c){ma(a);for(var c=ra(a,c),d=0,g=c.length;d<g;d++)I(a,c[d]);M(a,b);B(a,!1)}));if(c){var d=new q(a);d.one("draw",function(){c(d.ajax.json())})}};r("ajax.json()",function(){var a=this.context;if(0<a.length)return a[0].json});r("ajax.params()",function(){var a=this.context;
if(0<a.length)return a[0].oAjaxData});r("ajax.reload()",function(a,b){return this.iterator("table",function(c){Tb(c,!1===b,a)})});r("ajax.url()",function(a){var b=this.context;if(a===l){if(0===b.length)return l;b=b[0];return b.ajax?h.isPlainObject(b.ajax)?b.ajax.url:b.ajax:b.sAjaxSource}return this.iterator("table",function(b){h.isPlainObject(b.ajax)?b.ajax.url=a:b.ajax=a})});r("ajax.url().load()",function(a,b){return this.iterator("table",function(c){Tb(c,!1===b,a)})});var $a=function(a,b){var c=
[],d,e,f,g,i,j;d=typeof a;if(!a||"string"===d||"function"===d||a.length===l)a=[a];f=0;for(g=a.length;f<g;f++){e=a[f]&&a[f].split?a[f].split(","):[a[f]];i=0;for(j=e.length;i<j;i++)(d=b("string"===typeof e[i]?h.trim(e[i]):e[i]))&&d.length&&c.push.apply(c,d)}return c},ab=function(a){a||(a={});a.filter&&!a.search&&(a.search=a.filter);return{search:a.search||"none",order:a.order||"current",page:a.page||"all"}},bb=function(a){for(var b=0,c=a.length;b<c;b++)if(0<a[b].length)return a[0]=a[b],a.length=1,a.context=
[a.context[b]],a;a.length=0;return a},Ba=function(a,b){var c,d,e,f=[],g=a.aiDisplay;c=a.aiDisplayMaster;var i=b.search;d=b.order;e=b.page;if("ssp"==A(a))return"removed"===i?[]:U(0,c.length);if("current"==e){c=a._iDisplayStart;for(d=a.fnDisplayEnd();c<d;c++)f.push(g[c])}else if("current"==d||"applied"==d)f="none"==i?c.slice():"applied"==i?g.slice():h.map(c,function(a){return-1===h.inArray(a,g)?a:null});else if("index"==d||"original"==d){c=0;for(d=a.aoData.length;c<d;c++)"none"==i?f.push(c):(e=h.inArray(c,
g),(-1===e&&"removed"==i||0<=e&&"applied"==i)&&f.push(c))}return f};r("rows()",function(a,b){a===l?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var e=b;return $a(a,function(a){var b=Pb(a);if(b!==null&&!e)return[b];var i=Ba(c,e);if(b!==null&&h.inArray(b,i)!==-1)return[b];if(!a)return i;b=ga(c.aoData,i,"nTr");return typeof a==="function"?h.map(i,function(b){var e=c.aoData[b];return a(b,e._aData,e.nTr)?b:null}):a.nodeName&&h.inArray(a,b)!==-1?[a._DT_RowIndex]:h(b).filter(a).map(function(){return this._DT_RowIndex}).toArray()})});
c.selector.rows=a;c.selector.opts=b;return c});r("rows().nodes()",function(){return this.iterator("row",function(a,b){return a.aoData[b].nTr||l})});r("rows().data()",function(){return this.iterator(!0,"rows",function(a,b){return ga(a.aoData,b,"_aData")})});t("rows().cache()","row().cache()",function(a){return this.iterator("row",function(b,c){var d=b.aoData[c];return"search"===a?d._aFilterData:d._aSortData})});t("rows().invalidate()","row().invalidate()",function(a){return this.iterator("row",function(b,
c){oa(b,c,a)})});t("rows().indexes()","row().index()",function(){return this.iterator("row",function(a,b){return b})});t("rows().remove()","row().remove()",function(){var a=this;return this.iterator("row",function(b,c,d){var e=b.aoData;e.splice(c,1);for(var f=0,g=e.length;f<g;f++)null!==e[f].nTr&&(e[f].nTr._DT_RowIndex=f);h.inArray(c,b.aiDisplay);na(b.aiDisplayMaster,c);na(b.aiDisplay,c);na(a[d],c,!1);Sa(b)})});r("rows.add()",function(a){var b=this.iterator("table",function(b){var c,f,g,h=[];f=0;
for(g=a.length;f<g;f++)c=a[f],c.nodeName&&"TR"===c.nodeName.toUpperCase()?h.push(ka(b,c)[0]):h.push(I(b,c));return h}),c=this.rows(-1);c.pop();c.push.apply(c,b.toArray());return c});r("row()",function(a,b){return bb(this.rows(a,b))});r("row().data()",function(a){var b=this.context;if(a===l)return b.length&&this.length?b[0].aoData[this[0]]._aData:l;b[0].aoData[this[0]]._aData=a;oa(b[0],this[0],"data");return this});r("row().node()",function(){var a=this.context;return a.length&&this.length?a[0].aoData[this[0]].nTr||
null:null});r("row.add()",function(a){a instanceof h&&a.length&&(a=a[0]);var b=this.iterator("table",function(b){return a.nodeName&&"TR"===a.nodeName.toUpperCase()?ka(b,a)[0]:I(b,a)});return this.row(b[0])});var cb=function(a,b){var c=a.context;c.length&&(c=c[0].aoData[b!==l?b:a[0]],c._details&&(c._details.remove(),c._detailsShow=l,c._details=l))},Ub=function(a,b){var c=a.context;if(c.length&&a.length){var d=c[0].aoData[a[0]];if(d._details){(d._detailsShow=b)?d._details.insertAfter(d.nTr):d._details.detach();
var e=c[0],f=new q(e),g=e.aoData;f.off("draw.dt.DT_details column-visibility.dt.DT_details destroy.dt.DT_details");0<C(g,"_details").length&&(f.on("draw.dt.DT_details",function(a,b){e===b&&f.rows({page:"current"}).eq(0).each(function(a){a=g[a];a._detailsShow&&a._details.insertAfter(a.nTr)})}),f.on("column-visibility.dt.DT_details",function(a,b){if(e===b)for(var c,d=aa(b),f=0,h=g.length;f<h;f++)c=g[f],c._details&&c._details.children("td[colspan]").attr("colspan",d)}),f.on("destroy.dt.DT_details",function(a,
b){if(e===b)for(var c=0,d=g.length;c<d;c++)g[c]._details&&cb(f,c)}))}}};r("row().child()",function(a,b){var c=this.context;if(a===l)return c.length&&this.length?c[0].aoData[this[0]]._details:l;if(!0===a)this.child.show();else if(!1===a)cb(this);else if(c.length&&this.length){var d=c[0],c=c[0].aoData[this[0]],e=[],f=function(a,b){if(a.nodeName&&"tr"===a.nodeName.toLowerCase())e.push(a);else{var c=h("<tr><td/></tr>").addClass(b);h("td",c).addClass(b).html(a)[0].colSpan=aa(d);e.push(c[0])}};if(h.isArray(a)||
a instanceof h)for(var g=0,i=a.length;g<i;g++)f(a[g],b);else f(a,b);c._details&&c._details.remove();c._details=h(e);c._detailsShow&&c._details.insertAfter(c.nTr)}return this});r(["row().child.show()","row().child().show()"],function(){Ub(this,!0);return this});r(["row().child.hide()","row().child().hide()"],function(){Ub(this,!1);return this});r(["row().child.remove()","row().child().remove()"],function(){cb(this);return this});r("row().child.isShown()",function(){var a=this.context;return a.length&&
this.length?a[0].aoData[this[0]]._detailsShow||!1:!1});var cc=/^(.+):(name|visIdx|visible)$/,Vb=function(a,b,c,d,e){for(var c=[],d=0,f=e.length;d<f;d++)c.push(w(a,e[d],b));return c};r("columns()",function(a,b){a===l?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var e=a,f=b,g=c.aoColumns,i=C(g,"sName"),j=C(g,"nTh");return $a(e,function(a){var b=Pb(a);if(a==="")return U(g.length);if(b!==null)return[b>=0?b:g.length+b];if(typeof a==="function"){var e=Ba(c,f);return h.map(g,
function(b,f){return a(f,Vb(c,f,0,0,e),j[f])?f:null})}var k=typeof a==="string"?a.match(cc):"";if(k)switch(k[2]){case "visIdx":case "visible":b=parseInt(k[1],10);if(b<0){var l=h.map(g,function(a,b){return a.bVisible?b:null});return[l[l.length+b]]}return[ja(c,b)];case "name":return h.map(i,function(a,b){return a===k[1]?b:null})}else return h(j).filter(a).map(function(){return h.inArray(this,j)}).toArray()})});c.selector.cols=a;c.selector.opts=b;return c});t("columns().header()","column().header()",
function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTh})});t("columns().footer()","column().footer()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTf})});t("columns().data()","column().data()",function(){return this.iterator("column-rows",Vb)});t("columns().dataSrc()","column().dataSrc()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].mData})});t("columns().cache()","column().cache()",function(a){return this.iterator("column-rows",
function(b,c,d,e,f){return ga(b.aoData,f,"search"===a?"_aFilterData":"_aSortData",c)})});t("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(a,b,c,d,e){return ga(a.aoData,e,"anCells",b)})});t("columns().visible()","column().visible()",function(a,b){return this.iterator("column",function(c,d){var e;if(a===l)e=c.aoColumns[d].bVisible;else{var f=c.aoColumns;e=f[d];var g=c.aoData,i,j,n;if(a===l)e=e.bVisible;else{if(e.bVisible!==a){if(a){var m=h.inArray(!0,C(f,
"bVisible"),d+1);i=0;for(j=g.length;i<j;i++)n=g[i].nTr,f=g[i].anCells,n&&n.insertBefore(f[d],f[m]||null)}else h(C(c.aoData,"anCells",d)).detach();e.bVisible=a;da(c,c.aoHeader);da(c,c.aoFooter);if(b===l||b)X(c),(c.oScroll.sX||c.oScroll.sY)&&Y(c);u(c,null,"column-visibility",[c,d,a]);xa(c)}e=void 0}}return e})});t("columns().indexes()","column().index()",function(a){return this.iterator("column",function(b,c){return"visible"===a?$(b,c):c})});r("columns.adjust()",function(){return this.iterator("table",
function(a){X(a)})});r("column.index()",function(a,b){if(0!==this.context.length){var c=this.context[0];if("fromVisible"===a||"toData"===a)return ja(c,b);if("fromData"===a||"toVisible"===a)return $(c,b)}});r("column()",function(a,b){return bb(this.columns(a,b))});r("cells()",function(a,b,c){h.isPlainObject(a)&&(typeof a.row!==l?(c=b,b=null):(c=a,a=null));h.isPlainObject(b)&&(c=b,b=null);if(null===b||b===l)return this.iterator("table",function(b){var d=a,e=ab(c),f=b.aoData,g=Ba(b,e),e=ga(f,g,"anCells"),
i=h([].concat.apply([],e)),j,m=b.aoColumns.length,n,p,r,q,s,t;return $a(d,function(a){var c=typeof a==="function";if(a===null||a===l||c){n=[];p=0;for(r=g.length;p<r;p++){j=g[p];for(q=0;q<m;q++){s={row:j,column:q};if(c){t=b.aoData[j];a(s,w(b,j,q),t.anCells[q])&&n.push(s)}else n.push(s)}}return n}return h.isPlainObject(a)?[a]:i.filter(a).map(function(a,b){j=b.parentNode._DT_RowIndex;return{row:j,column:h.inArray(b,f[j].anCells)}}).toArray()})});var d=this.columns(b,c),e=this.rows(a,c),f,g,i,j,n,m=this.iterator("table",
function(a,b){f=[];g=0;for(i=e[b].length;g<i;g++){j=0;for(n=d[b].length;j<n;j++)f.push({row:e[b][g],column:d[b][j]})}return f});h.extend(m.selector,{cols:b,rows:a,opts:c});return m});t("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(a,b,c){return a.aoData[b].anCells[c]})});r("cells().data()",function(){return this.iterator("cell",function(a,b,c){return w(a,b,c)})});t("cells().cache()","cell().cache()",function(a){a="search"===a?"_aFilterData":"_aSortData";return this.iterator("cell",
function(b,c,d){return b.aoData[c][a][d]})});t("cells().render()","cell().render()",function(a){return this.iterator("cell",function(b,c,d){return w(b,c,d,a)})});t("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(a,b,c){return{row:b,column:c,columnVisible:$(a,c)}})});r(["cells().invalidate()","cell().invalidate()"],function(a){var b=this.selector;this.rows(b.rows,b.opts).invalidate(a);return this});r("cell()",function(a,b,c){return bb(this.cells(a,b,c))});r("cell().data()",
function(a){var b=this.context,c=this[0];if(a===l)return b.length&&c.length?w(b[0],c[0].row,c[0].column):l;Ha(b[0],c[0].row,c[0].column,a);oa(b[0],c[0].row,"data",c[0].column);return this});r("order()",function(a,b){var c=this.context;if(a===l)return 0!==c.length?c[0].aaSorting:l;"number"===typeof a?a=[[a,b]]:h.isArray(a[0])||(a=Array.prototype.slice.call(arguments));return this.iterator("table",function(b){b.aaSorting=a.slice()})});r("order.listener()",function(a,b,c){return this.iterator("table",
function(d){Na(d,a,b,c)})});r(["columns().order()","column().order()"],function(a){var b=this;return this.iterator("table",function(c,d){var e=[];h.each(b[d],function(b,c){e.push([c,a])});c.aaSorting=e})});r("search()",function(a,b,c,d){var e=this.context;return a===l?0!==e.length?e[0].oPreviousSearch.sSearch:l:this.iterator("table",function(e){e.oFeatures.bFilter&&ea(e,h.extend({},e.oPreviousSearch,{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===c?!0:c,bCaseInsensitive:null===d?!0:d}),1)})});t("columns().search()",
"column().search()",function(a,b,c,d){return this.iterator("column",function(e,f){var g=e.aoPreSearchCols;if(a===l)return g[f].sSearch;e.oFeatures.bFilter&&(h.extend(g[f],{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===c?!0:c,bCaseInsensitive:null===d?!0:d}),ea(e,e.oPreviousSearch,1))})});r("state()",function(){return this.context.length?this.context[0].oSavedState:null});r("state.clear()",function(){return this.iterator("table",function(a){a.fnStateSaveCallback.call(a.oInstance,a,{})})});r("state.loaded()",
function(){return this.context.length?this.context[0].oLoadedState:null});r("state.save()",function(){return this.iterator("table",function(a){xa(a)})});p.versionCheck=p.fnVersionCheck=function(a){for(var b=p.version.split("."),a=a.split("."),c,d,e=0,f=a.length;e<f;e++)if(c=parseInt(b[e],10)||0,d=parseInt(a[e],10)||0,c!==d)return c>d;return!0};p.isDataTable=p.fnIsDataTable=function(a){var b=h(a).get(0),c=!1;h.each(p.settings,function(a,e){if(e.nTable===b||e.nScrollHead===b||e.nScrollFoot===b)c=!0});
return c};p.tables=p.fnTables=function(a){return jQuery.map(p.settings,function(b){if(!a||a&&h(b.nTable).is(":visible"))return b.nTable})};p.util={throttle:ta};p.camelToHungarian=G;r("$()",function(a,b){var c=this.rows(b).nodes(),c=h(c);return h([].concat(c.filter(a).toArray(),c.find(a).toArray()))});h.each(["on","one","off"],function(a,b){r(b+"()",function(){var a=Array.prototype.slice.call(arguments);a[0].match(/\.dt\b/)||(a[0]+=".dt");var d=h(this.tables().nodes());d[b].apply(d,a);return this})});
r("clear()",function(){return this.iterator("table",function(a){ma(a)})});r("settings()",function(){return new q(this.context,this.context)});r("data()",function(){return this.iterator("table",function(a){return C(a.aoData,"_aData")}).flatten()});r("destroy()",function(a){a=a||!1;return this.iterator("table",function(b){var c=b.nTableWrapper.parentNode,d=b.oClasses,e=b.nTable,f=b.nTBody,g=b.nTHead,i=b.nTFoot,j=h(e),f=h(f),l=h(b.nTableWrapper),m=h.map(b.aoData,function(a){return a.nTr}),o;b.bDestroying=
!0;u(b,"aoDestroyCallback","destroy",[b]);a||(new q(b)).columns().visible(!0);l.unbind(".DT").find(":not(tbody *)").unbind(".DT");h(Da).unbind(".DT-"+b.sInstance);e!=g.parentNode&&(j.children("thead").detach(),j.append(g));i&&e!=i.parentNode&&(j.children("tfoot").detach(),j.append(i));j.detach();l.detach();b.aaSorting=[];b.aaSortingFixed=[];wa(b);h(m).removeClass(b.asStripeClasses.join(" "));h("th, td",g).removeClass(d.sSortable+" "+d.sSortableAsc+" "+d.sSortableDesc+" "+d.sSortableNone);b.bJUI&&
(h("th span."+d.sSortIcon+", td span."+d.sSortIcon,g).detach(),h("th, td",g).each(function(){var a=h("div."+d.sSortJUIWrapper,this);h(this).append(a.contents());a.detach()}));!a&&c&&c.insertBefore(e,b.nTableReinsertBefore);f.children().detach();f.append(m);j.css("width",b.sDestroyWidth).removeClass(d.sTable);(o=b.asDestroyStripes.length)&&f.children().each(function(a){h(this).addClass(b.asDestroyStripes[a%o])});c=h.inArray(b,p.settings);-1!==c&&p.settings.splice(c,1)})});p.version="1.10.3";p.settings=
[];p.models={};p.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};p.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null};p.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",
sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};p.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,
fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(a){return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(a){try{return JSON.parse((-1===a.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+a.sInstance+"_"+location.pathname))}catch(b){}},fnStateLoadParams:null,
fnStateLoaded:null,fnStateSaveCallback:function(a,b){try{(-1===a.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+a.sInstance+"_"+location.pathname,JSON.stringify(b))}catch(c){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},
sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:h.extend({},p.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",searchDelay:null,
sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null};V(p.defaults);p.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};V(p.defaults.column);p.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,
bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],
sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,searchDelay:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,
bAjaxDataGet:!0,jqXHR:null,json:l,oAjaxData:l,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==A(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==A(this)?1*this._iRecordsDisplay:
this.aiDisplay.length},fnDisplayEnd:function(){var a=this._iDisplayLength,b=this._iDisplayStart,c=b+a,d=this.aiDisplay.length,e=this.oFeatures,f=e.bPaginate;return e.bServerSide?!1===f||-1===a?b+d:Math.min(b+a,this._iRecordsDisplay):!f||c>d||-1===a?d:c},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}};p.ext=v={classes:{},errMode:"alert",feature:[],search:[],internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},header:{}},order:{},type:{detect:[],
search:{},order:{}},_unique:0,fnVersionCheck:p.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:p.version};h.extend(v,{afnFiltering:v.search,aTypes:v.type.detect,ofnSearch:v.type.search,oSort:v.type.order,afnSortData:v.order,aoFeatures:v.feature,oApi:v.internal,oStdClasses:v.classes,oPagination:v.pager});h.extend(p.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty",
sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",
sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});var Ca="",Ca="",E=Ca+"ui-state-default",ha=Ca+"css_right ui-icon ui-icon-",Wb=Ca+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";h.extend(p.ext.oJUIClasses,p.ext.classes,{sPageButton:"fg-button ui-button "+
E,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:E+" sorting_asc",sSortDesc:E+" sorting_desc",sSortable:E+" sorting",sSortableAsc:E+" sorting_asc_disabled",sSortableDesc:E+" sorting_desc_disabled",sSortableNone:E+" sorting_disabled",sSortJUIAsc:ha+"triangle-1-n",sSortJUIDesc:ha+"triangle-1-s",sSortJUI:ha+"carat-2-n-s",sSortJUIAscAllowed:ha+"carat-1-n",sSortJUIDescAllowed:ha+
"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+E,sScrollFoot:"dataTables_scrollFoot "+E,sHeaderTH:E,sFooterTH:E,sJUIHeader:Wb+" ui-corner-tl ui-corner-tr",sJUIFooter:Wb+" ui-corner-bl ui-corner-br"});var Mb=p.ext.pager;h.extend(Mb,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(a,b){return["previous",Wa(a,b),"next"]},full_numbers:function(a,b){return["first",
"previous",Wa(a,b),"next","last"]},_numbers:Wa,numbers_length:7});h.extend(!0,p.ext.renderer,{pageButton:{_:function(a,b,c,d,e,f){var g=a.oClasses,i=a.oLanguage.oPaginate,j,l,m=0,o=function(b,d){var k,p,r,q,s=function(b){Ta(a,b.data.action,true)};k=0;for(p=d.length;k<p;k++){q=d[k];if(h.isArray(q)){r=h("<"+(q.DT_el||"div")+"/>").appendTo(b);o(r,q)}else{l=j="";switch(q){case "ellipsis":b.append("<span>…</span>");break;case "first":j=i.sFirst;l=q+(e>0?"":" "+g.sPageButtonDisabled);break;case "previous":j=
i.sPrevious;l=q+(e>0?"":" "+g.sPageButtonDisabled);break;case "next":j=i.sNext;l=q+(e<f-1?"":" "+g.sPageButtonDisabled);break;case "last":j=i.sLast;l=q+(e<f-1?"":" "+g.sPageButtonDisabled);break;default:j=q+1;l=e===q?g.sPageButtonActive:""}if(j){r=h("<a>",{"class":g.sPageButton+" "+l,"aria-controls":a.sTableId,"data-dt-idx":m,tabindex:a.iTabIndex,id:c===0&&typeof q==="string"?a.sTableId+"_"+q:null}).html(j).appendTo(b);Va(r,{action:q},s);m++}}}};try{var k=h(P.activeElement).data("dt-idx");o(h(b).empty(),
d);k!==null&&h(b).find("[data-dt-idx="+k+"]").focus()}catch(p){}}}});var za=function(a,b,c,d){if(0!==a&&(!a||"-"===a))return-Infinity;b&&(a=Qb(a,b));a.replace&&(c&&(a=a.replace(c,"")),d&&(a=a.replace(d,"")));return 1*a};h.extend(v.type.order,{"date-pre":function(a){return Date.parse(a)||0},"html-pre":function(a){return H(a)?"":a.replace?a.replace(/<.*?>/g,"").toLowerCase():a+""},"string-pre":function(a){return H(a)?"":"string"===typeof a?a.toLowerCase():!a.toString?"":a.toString()},"string-asc":function(a,
b){return a<b?-1:a>b?1:0},"string-desc":function(a,b){return a<b?1:a>b?-1:0}});db("");h.extend(p.ext.type.detect,[function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c)?"num"+c:null},function(a){if(a&&!(a instanceof Date)&&(!$b.test(a)||!ac.test(a)))return null;var b=Date.parse(a);return null!==b&&!isNaN(b)||H(a)?"date":null},function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c,!0)?"num-fmt"+c:null},function(a,b){var c=b.oLanguage.sDecimal;return Rb(a,c)?"html-num"+c:null},function(a,b){var c=
b.oLanguage.sDecimal;return Rb(a,c,!0)?"html-num-fmt"+c:null},function(a){return H(a)||"string"===typeof a&&-1!==a.indexOf("<")?"html":null}]);h.extend(p.ext.type.search,{html:function(a){return H(a)?a:"string"===typeof a?a.replace(Ob," ").replace(Aa,""):""},string:function(a){return H(a)?a:"string"===typeof a?a.replace(Ob," "):a}});h.extend(!0,p.ext.renderer,{header:{_:function(a,b,c,d){h(a.nTable).on("order.dt.DT",function(e,f,g,h){if(a===f){e=c.idx;b.removeClass(c.sSortingClass+" "+d.sSortAsc+
" "+d.sSortDesc).addClass(h[e]=="asc"?d.sSortAsc:h[e]=="desc"?d.sSortDesc:c.sSortingClass)}})},jqueryui:function(a,b,c,d){h("<div/>").addClass(d.sSortJUIWrapper).append(b.contents()).append(h("<span/>").addClass(d.sSortIcon+" "+c.sSortingClassJUI)).appendTo(b);h(a.nTable).on("order.dt.DT",function(e,f,g,h){if(a===f){e=c.idx;b.removeClass(d.sSortAsc+" "+d.sSortDesc).addClass(h[e]=="asc"?d.sSortAsc:h[e]=="desc"?d.sSortDesc:c.sSortingClass);b.find("span."+d.sSortIcon).removeClass(d.sSortJUIAsc+" "+d.sSortJUIDesc+
" "+d.sSortJUI+" "+d.sSortJUIAscAllowed+" "+d.sSortJUIDescAllowed).addClass(h[e]=="asc"?d.sSortJUIAsc:h[e]=="desc"?d.sSortJUIDesc:c.sSortingClassJUI)}})}}});p.render={number:function(a,b,c,d){return{display:function(e){var f=0>e?"-":"",e=Math.abs(parseFloat(e)),g=parseInt(e,10),e=c?b+(e-g).toFixed(c).substring(2):"";return f+(d||"")+g.toString().replace(/\B(?=(\d{3})+(?!\d))/g,a)+e}}}};h.extend(p.ext.internal,{_fnExternApiFunc:Nb,_fnBuildAjax:qa,_fnAjaxUpdate:kb,_fnAjaxParameters:tb,_fnAjaxUpdateDraw:ub,
_fnAjaxDataSrc:ra,_fnAddColumn:Ea,_fnColumnOptions:ia,_fnAdjustColumnSizing:X,_fnVisibleToColumnIndex:ja,_fnColumnIndexToVisible:$,_fnVisbleColumns:aa,_fnGetColumns:Z,_fnColumnTypes:Ga,_fnApplyColumnDefs:ib,_fnHungarianMap:V,_fnCamelToHungarian:G,_fnLanguageCompat:O,_fnBrowserDetect:gb,_fnAddData:I,_fnAddTr:ka,_fnNodeToDataIndex:function(a,b){return b._DT_RowIndex!==l?b._DT_RowIndex:null},_fnNodeToColumnIndex:function(a,b,c){return h.inArray(c,a.aoData[b].anCells)},_fnGetCellData:w,_fnSetCellData:Ha,
_fnSplitObjNotation:Ja,_fnGetObjectDataFn:W,_fnSetObjectDataFn:Q,_fnGetDataMaster:Ka,_fnClearTable:ma,_fnDeleteIndex:na,_fnInvalidateRow:oa,_fnGetRowElements:la,_fnCreateTr:Ia,_fnBuildHead:jb,_fnDrawHead:da,_fnDraw:L,_fnReDraw:M,_fnAddOptionsHtml:mb,_fnDetectHeader:ca,_fnGetUniqueThs:pa,_fnFeatureHtmlFilter:ob,_fnFilterComplete:ea,_fnFilterCustom:xb,_fnFilterColumn:wb,_fnFilter:vb,_fnFilterCreateSearch:Pa,_fnEscapeRegex:Qa,_fnFilterData:yb,_fnFeatureHtmlInfo:rb,_fnUpdateInfo:Bb,_fnInfoMacros:Cb,_fnInitialise:va,
_fnInitComplete:sa,_fnLengthChange:Ra,_fnFeatureHtmlLength:nb,_fnFeatureHtmlPaginate:sb,_fnPageChange:Ta,_fnFeatureHtmlProcessing:pb,_fnProcessingDisplay:B,_fnFeatureHtmlTable:qb,_fnScrollDraw:Y,_fnApplyToChildren:F,_fnCalculateColumnWidths:Fa,_fnThrottle:ta,_fnConvertToWidth:Db,_fnScrollingWidthAdjust:Fb,_fnGetWidestNode:Eb,_fnGetMaxLenString:Gb,_fnStringToCss:s,_fnScrollBarWidth:Hb,_fnSortFlatten:T,_fnSort:lb,_fnSortAria:Jb,_fnSortListener:Ua,_fnSortAttachListener:Na,_fnSortingClasses:wa,_fnSortData:Ib,
_fnSaveState:xa,_fnLoadState:Kb,_fnSettingsFromNode:ya,_fnLog:R,_fnMap:D,_fnBindAction:Va,_fnCallbackReg:y,_fnCallbackFire:u,_fnLengthOverflow:Sa,_fnRenderer:Oa,_fnDataSource:A,_fnRowAttributes:La,_fnCalculateEnd:function(){}});h.fn.dataTable=p;h.fn.dataTableSettings=p.settings;h.fn.dataTableExt=p.ext;h.fn.DataTable=function(a){return h(this).dataTable(a).api()};h.each(p,function(a,b){h.fn.DataTable[a]=b});return h.fn.dataTable};"function"===typeof define&&define.amd?define("datatables",["jquery"],
O):"object"===typeof exports?O(require("jquery")):jQuery&&!jQuery.fn.dataTable&&O(jQuery)})(window,document); | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/static/js/jquery.dataTables.min.js | jquery.dataTables.min.js |
// AMD support
(function (factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// using AMD; register as anon module
define(['jquery'], factory);
} else {
// no AMD; invoke directly
factory( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto );
}
}
(function($) {
"use strict";
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are mutually exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
form does not have to exist when you invoke ajaxForm:
$('#myForm').ajaxForm({
delegation: true,
target: '#output'
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* Feature detection
*/
var feature = {};
feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
feature.formdata = window.FormData !== undefined;
var hasProp = !!$.fn.prop;
// attr2 uses prop when it can but checks the return type for
// an expected string. this accounts for the case where a form
// contains inputs with names like "action" or "method"; in those
// cases "prop" returns the element
$.fn.attr2 = function() {
if ( ! hasProp ) {
return this.attr.apply(this, arguments);
}
var val = this.prop.apply(this, arguments);
if ( ( val && val.jquery ) || typeof val === 'string' ) {
return val;
}
return this.attr.apply(this, arguments);
};
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
/*jshint scripturl:true */
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
var method, action, url, $form = this;
if (typeof options == 'function') {
options = { success: options };
}
else if ( options === undefined ) {
options = {};
}
method = options.type || this.attr2('method');
action = options.url || this.attr2('action');
url = (typeof action === 'string') ? $.trim(action) : '';
url = url || window.location.href || '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/)||[])[1];
}
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: method || $.ajaxSettings.type,
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var traditional = options.traditional;
if ( traditional === undefined ) {
traditional = $.ajaxSettings.traditional;
}
var elements = [];
var qx, a = this.formToArray(options.semantic, elements);
if (options.data) {
options.extraData = options.data;
qx = $.param(options.data, traditional);
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a, traditional);
if (qx) {
q = ( q ? (q + '&' + qx) : qx );
}
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}
var callbacks = [];
if (options.resetForm) {
callbacks.push(function() { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function() { $form.clearForm(options.includeHidden); });
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || this ; // jQuery 1.4+ supports scope context
for (var i=0, max=callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
if (options.error) {
var oldError = options.error;
options.error = function(xhr, status, error) {
var context = options.context || this;
oldError.apply(context, [xhr, status, error, $form]);
};
}
if (options.complete) {
var oldComplete = options.complete;
options.complete = function(xhr, status) {
var context = options.context || this;
oldComplete.apply(context, [xhr, status, $form]);
};
}
// are there files to upload?
// [value] (issue #113), also see comment:
// https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
var fileInputs = $('input[type=file]:enabled', this).filter(function() { return $(this).val() !== ''; });
var hasFileInputs = fileInputs.length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
var fileAPI = feature.fileapi && feature.formdata;
log("fileAPI :" + fileAPI);
var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
var jqxhr;
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, function() {
jqxhr = fileUploadIframe(a);
});
}
else {
jqxhr = fileUploadIframe(a);
}
}
else if ((hasFileInputs || multipart) && fileAPI) {
jqxhr = fileUploadXhr(a);
}
else {
jqxhr = $.ajax(options);
}
$form.removeData('jqxhr').data('jqxhr', jqxhr);
// clear element array
for (var k=0; k < elements.length; k++) {
elements[k] = null;
}
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// utility fn for deep serialization
function deepSerialize(extraData){
var serialized = $.param(extraData, options.traditional).split('&');
var len = serialized.length;
var result = [];
var i, part;
for (i=0; i < len; i++) {
// #252; undo param space replacement
serialized[i] = serialized[i].replace(/\+/g,' ');
part = serialized[i].split('=');
// #278; use array instead of object storage, favoring array serializations
result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
}
return result;
}
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i=0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}
if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (i=0; i < serializedData.length; i++) {
if (serializedData[i]) {
formdata.append(serializedData[i][0], serializedData[i][1]);
}
}
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});
if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function() {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
}
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
//Send FormData() provided by user
if (options.formData) {
o.data = options.formData;
}
else {
o.data = formdata;
}
if(beforeSend) {
beforeSend.call(this, xhr, o);
}
};
return $.ajax(s);
}
// private function for handling file uploads (hat tip to YAHOO!)
function fileUploadIframe(a) {
var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
var deferred = $.Deferred();
// #341
deferred.abort = function(status) {
xhr.abort(status);
};
if (a) {
// ensure that every serialized input is still enabled
for (i=0; i < elements.length; i++) {
el = $(elements[i]);
if ( hasProp ) {
el.prop('disabled', false);
}
else {
el.removeAttr('disabled');
}
}
}
s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
id = 'jqFormIO' + (new Date().getTime());
if (s.iframeTarget) {
$io = $(s.iframeTarget);
n = $io.attr2('name');
if (!n) {
$io.attr2('name', id);
}
else {
id = n;
}
}
else {
$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
}
io = $io[0];
xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function(status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
try { // #214, #257
if (io.contentWindow.document.execCommand) {
io.contentWindow.document.execCommand('Stop');
}
}
catch(ignore) {}
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
if (s.error) {
s.error.call(s.context, xhr, e, status);
}
if (g) {
$.event.trigger("ajaxError", [xhr, s, e]);
}
if (s.complete) {
s.complete.call(s.context, xhr, e);
}
}
};
g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && 0 === $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
deferred.reject();
return deferred;
}
if (xhr.aborted) {
deferred.reject();
return deferred;
}
// add submitting element to data if we know it
sub = form.clk;
if (sub) {
n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n+'.x'] = form.clk_x;
s.extraData[n+'.y'] = form.clk_y;
}
}
}
var CLIENT_TIMEOUT_ABORT = 1;
var SERVER_ABORT = 2;
function getDoc(frame) {
/* it looks like contentWindow or contentDocument do not
* carry the protocol property in ie8, when running under ssl
* frame.document is the only valid response document, since
* the protocol is know but not on the other two objects. strange?
* "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
*/
var doc = null;
// IE8 cascading access check
try {
if (frame.contentWindow) {
doc = frame.contentWindow.document;
}
} catch(err) {
// IE8 access denied under ssl & missing protocol
log('cannot get iframe.contentWindow document: ' + err);
}
if (doc) { // successful getting content
return doc;
}
try { // simply checking may throw in ie8 under ssl or mismatched protocol
doc = frame.contentDocument ? frame.contentDocument : frame.document;
} catch(err) {
// last attempt
log('cannot get iframe.contentDocument: ' + err);
doc = frame.document;
}
return doc;
}
// Rails CSRF hack (thanks to Yvan Barthelemy)
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
if (csrf_param && csrf_token) {
s.extraData = s.extraData || {};
s.extraData[csrf_param] = csrf_token;
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr2('target'),
a = $form.attr2('action'),
mp = 'multipart/form-data',
et = $form.attr('enctype') || $form.attr('encoding') || mp;
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method || /post/i.test(method) ) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized') {
setTimeout(checkState,50);
}
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
// if using the $.param format that allows for multiple values with the same name
if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
extraInputs.push(
$('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
.appendTo(form)[0]);
} else {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').val(s.extraData[n])
.appendTo(form)[0]);
}
}
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
}
if (io.attachEvent) {
io.attachEvent('onload', cb);
}
else {
io.addEventListener('load', cb, false);
}
setTimeout(checkState,15);
try {
form.submit();
} catch(err) {
// just in case form has element with name/id of 'submit'
var submitFn = document.createElement('form').submit;
submitFn.apply(form);
}
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
form.setAttribute('enctype', et); // #380
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
doc = getDoc(io);
if(!doc) {
log('cannot access response document');
e = SERVER_ABORT;
}
if (e === CLIENT_TIMEOUT_ABORT && xhr) {
xhr.abort('timeout');
deferred.reject(xhr, 'timeout');
return;
}
else if (e == SERVER_ABORT && xhr) {
xhr.abort('server abort');
deferred.reject(xhr, 'error', 'server abort');
return;
}
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut) {
return;
}
}
if (io.detachEvent) {
io.detachEvent('onload', cb);
}
else {
io.removeEventListener('load', cb, false);
}
var status = 'success', errMsg;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
var docRoot = doc.body ? doc.body : doc.documentElement;
xhr.responseText = docRoot ? docRoot.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml) {
s.dataType = 'xml';
}
xhr.getResponseHeader = function(header){
var headers = {'content-type': s.dataType};
return headers[header.toLowerCase()];
};
// support for XHR 'status' & 'statusText' emulation :
if (docRoot) {
xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
}
var dt = (s.dataType || '').toLowerCase();
var scr = /(json|script|text)/.test(dt);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
// support for XHR 'status' & 'statusText' emulation :
xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
}
else if (b) {
xhr.responseText = b.textContent ? b.textContent : b.innerText;
}
}
}
else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
xhr.responseXML = toXml(xhr.responseText);
}
try {
data = httpData(xhr, dt, s);
}
catch (err) {
status = 'parsererror';
xhr.error = errMsg = (err || status);
}
}
catch (err) {
log('error caught: ',err);
status = 'error';
xhr.error = errMsg = (err || status);
}
if (xhr.aborted) {
log('upload aborted');
status = null;
}
if (xhr.status) { // we've set xhr.status
status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (status === 'success') {
if (s.success) {
s.success.call(s.context, data, 'success', xhr);
}
deferred.resolve(xhr.responseText, 'success', xhr);
if (g) {
$.event.trigger("ajaxSuccess", [xhr, s]);
}
}
else if (status) {
if (errMsg === undefined) {
errMsg = xhr.statusText;
}
if (s.error) {
s.error.call(s.context, xhr, status, errMsg);
}
deferred.reject(xhr, 'error', errMsg);
if (g) {
$.event.trigger("ajaxError", [xhr, s, errMsg]);
}
}
if (g) {
$.event.trigger("ajaxComplete", [xhr, s]);
}
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
if (s.complete) {
s.complete.call(s.context, xhr, status);
}
callbackProcessed = true;
if (s.timeout) {
clearTimeout(timeoutHandle);
}
// clean up
setTimeout(function() {
if (!s.iframeTarget) {
$io.remove();
}
else { //adding else to clean up existing iframe response.
$io.attr('src', s.iframeSrc);
}
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function(s) {
/*jslint evil:true */
return window['eval']('(' + s + ')');
};
var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
if ($.error) {
$.error('parsererror');
}
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
return deferred;
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
options = options || {};
options.delegation = options.delegation && $.isFunction($.fn.on);
// in jQuery 1.3+ we can fix mistakes with the ready state
if (!options.delegation && this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s,o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
if ( options.delegation ) {
$(document)
.off('submit.form-plugin', this.selector, doAjaxSubmit)
.off('click.form-plugin', this.selector, captureSubmittingElement)
.on('submit.form-plugin', this.selector, options, doAjaxSubmit)
.on('click.form-plugin', this.selector, options, captureSubmittingElement);
return this;
}
return this.ajaxFormUnbind()
.bind('submit.form-plugin', options, doAjaxSubmit)
.bind('click.form-plugin', options, captureSubmittingElement);
};
// private event handlers
function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(e.target).ajaxSubmit(options); // #365
}
}
function captureSubmittingElement(e) {
/*jshint validthis:true */
var target = e.target;
var $el = $(target);
if (!($el.is("[type=submit],[type=image]"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest('[type=submit]');
if (t.length === 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX !== undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') {
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
}
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic, elements) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var formId = this.attr('id');
var els = semantic ? form.getElementsByTagName('*') : form.elements;
var els2;
if (els && !/MSIE [678]/.test(navigator.userAgent)) { // #390
els = $(els).get(); // convert to standard array
}
// #386; account for inputs outside the form which use the 'form' attribute
if ( formId ) {
els2 = $(':input[form="' + formId + '"]').get(); // hat tip @thet
if ( els2.length ) {
els = (els || []).concat(els2);
}
}
if (!els || !els.length) {
return a;
}
var i,j,n,v,el,max,jmax;
for(i=0, max=els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n || el.disabled) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(form.clk == el) {
a.push({name: n, value: $(el).val(), type: el.type });
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
if (elements) {
elements.push(el);
}
for(j=0, jmax=v.length; j < jmax; j++) {
a.push({name: n, value: v[j]});
}
}
else if (feature.fileapi && el.type == 'file') {
if (elements) {
elements.push(el);
}
var files = el.files;
if (files.length) {
for (j=0; j < files.length; j++) {
a.push({name: n, value: files[j], type: el.type});
}
}
else {
// #180
a.push({ name: n, value: '', type: el.type });
}
}
else if (v !== null && typeof v != 'undefined') {
if (elements) {
elements.push(el);
}
a.push({name: n, value: v, type: el.type, required: el.required});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++) {
a.push({name: n, value: v[i]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: this.name, value: v});
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $('input[type=text]').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $('input[type=checkbox]').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $('input[type=radio]').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
if (v.constructor == Array) {
$.merge(val, v);
}
else {
val.push(v);
}
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes.value && !(op.attributes.value.specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
$('input,select,textarea', this).clearFields(includeHidden);
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
else if (t == "file") {
if (/MSIE/.test(navigator.userAgent)) {
$(this).replaceWith($(this).clone(true));
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden can be the value true, or it can be a selector string
// indicating a special test; for example:
// $('#myForm').clearForm('.special:hidden')
// the above would clean hidden inputs that have the class of 'special'
if ( (includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden)) ) {
this.value = '';
}
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// expose debug var
$.fn.ajaxSubmit.debug = false;
// helper fn for console logging
function log() {
if (!$.fn.ajaxSubmit.debug) {
return;
}
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
})); | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/static/js/jquery.form.js | jquery.form.js |
(function($) {
$.fn.bootstrapFileInput = function() {
this.each(function(i,elem){
var $elem = $(elem);
// Maybe some fields don't need to be standardized.
if (typeof $elem.attr('data-bfi-disabled') != 'undefined') {
return;
}
// Set the word to be displayed on the button
var buttonWord = 'Browse';
if (typeof $elem.attr('title') != 'undefined') {
buttonWord = $elem.attr('title');
}
var className = '';
if (!!$elem.attr('class')) {
className = ' ' + $elem.attr('class');
}
// Now we're going to wrap that input field with a Bootstrap button.
// The input will actually still be there, it will just be float above and transparent (done with the CSS).
$elem.wrap('<a class="file-input-wrapper btn btn-primary ' + className + '"></a>').parent().prepend($('<span></span>').html(buttonWord));
})
// After we have found all of the file inputs let's apply a listener for tracking the mouse movement.
// This is important because the in order to give the illusion that this is a button in FF we actually need to move the button from the file input under the cursor. Ugh.
.promise().done( function(){
// As the cursor moves over our new Bootstrap button we need to adjust the position of the invisible file input Browse button to be under the cursor.
// This gives us the pointer cursor that FF denies us
$('.file-input-wrapper').mousemove(function(cursor) {
var input, wrapper,
wrapperX, wrapperY,
inputWidth, inputHeight,
cursorX, cursorY;
// This wrapper element (the button surround this file input)
wrapper = $(this);
// The invisible file input element
input = wrapper.find("input");
// The left-most position of the wrapper
wrapperX = wrapper.offset().left;
// The top-most position of the wrapper
wrapperY = wrapper.offset().top;
// The with of the browsers input field
inputWidth= input.width();
// The height of the browsers input field
inputHeight= input.height();
//The position of the cursor in the wrapper
cursorX = cursor.pageX;
cursorY = cursor.pageY;
//The positions we are to move the invisible file input
// The 20 at the end is an arbitrary number of pixels that we can shift the input such that cursor is not pointing at the end of the Browse button but somewhere nearer the middle
moveInputX = cursorX - wrapperX - inputWidth + 20;
// Slides the invisible input Browse button to be positioned middle under the cursor
moveInputY = cursorY- wrapperY - (inputHeight/2);
// Apply the positioning styles to actually move the invisible file input
input.css({
left:moveInputX,
top:moveInputY
});
});
$('body').on('change', '.file-input-wrapper input[type=file]', function(){
var fileName;
fileName = $(this).val();
// Remove any previous file names
$(this).parent().next('.file-input-name').remove();
if (!!$(this).prop('files') && $(this).prop('files').length > 1) {
fileName = $(this)[0].files.length+' files';
}
else {
fileName = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length);
}
// Don't try to show the name if there is none
if (!fileName) {
return;
}
var selectedFileNamePlacement = $(this).data('filename-placement');
if (selectedFileNamePlacement === 'inside') {
// Print the fileName inside
$(this).siblings('span').html(fileName);
$(this).attr('title', fileName);
} else {
// Print the fileName aside (right after the the button)
$(this).parent().after('<span class="file-input-name">'+fileName+'</span>');
}
});
});
};
// Add the styles before the first stylesheet
// This ensures they can be easily overridden with developer styles
var cssHtml = '<style>'+
'.file-input-wrapper { overflow: hidden; position: relative; cursor: pointer; z-index: 1; }'+
'.file-input-wrapper input[type=file], .file-input-wrapper input[type=file]:focus, .file-input-wrapper input[type=file]:hover { position: absolute; top: 0; left: 0; cursor: pointer; opacity: 0; filter: alpha(opacity=0); z-index: 99; outline: 0; }'+
'.file-input-name { margin-left: 8px; }'+
'</style>';
$('link[rel=stylesheet]').eq(0).before(cssHtml);
})(jQuery); | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/a3d_gui/static/js/bootstrap.file-input.js | bootstrap.file-input.js |
import os
import shutil
import logger
from subprocess import PIPE, Popen
from os.path import join, isfile
import platform
_name = "FoldX"
if platform.system() == "Windows":
_bin_name = "foldx.exe"
else:
_bin_name = "foldx"
# TODO once this is working again re-write given the fact that command line rather than files can be now used
# TODO maybe exploit the new foldx options for a cleaner pipeline of the pdb files etc
class FoldxWrap:
"""
Expects a path to folder with FoldX binary and rotabase.txt files and a script dir with repairPDB.txt file
If the file is not present in scripts dir, the class will attempt to create it
This class can be used to run energy minimization and mutant creation with foldx
"""
def __init__(self, foldx_dir="", script_dir="", work_dir="", skip_minimization=False):
self.bin_dir = foldx_dir
self.script_dir = script_dir
self.fold_config = join(self.script_dir, "repairPDB.txt")
self.mut_fold_config = join(self.script_dir, "buildModel.txt")
self.agg_work_dir = work_dir
self.skip = skip_minimization
try:
self._check_files()
except logger.FoldXError:
raise
def minimize_energy(self, working_dir="", cleanup=True, skip_min=False):
try:
os.chdir(working_dir)
except OSError:
raise logger.FoldXError("FoldX run in a non-existing directory %s" % working_dir)
if not isfile(join(working_dir, "input.pdb")):
raise logger.FoldXError("input.pdb file not present if FoldX working directory %s" % working_dir)
if not isfile(join(working_dir, "rotabase.txt")):
# In case of multiple minimizations te code below could raise a same file error
try:
os.symlink(join(self.bin_dir, "rotabase.txt"), join(working_dir, "rotabase.txt"))
os.symlink(join(self.script_dir, "repairPDB.txt"), join(working_dir, "repairPDB.txt"))
except (OSError, AttributeError): # Windows will not necessarily allow symlink creation
shutil.copyfile(join(self.bin_dir, "rotabase.txt"), join(working_dir, "rotabase.txt"))
shutil.copyfile(join(self.script_dir, "repairPDB.txt"), join(working_dir, "repairPDB.txt"))
fold_cmd = [join(self.bin_dir, _bin_name), "-f", "repairPDB.txt"]
if not skip_min:
self._run_foldx(cmd=fold_cmd, msg="Starting FoldX energy minimalization", outfile="finalRepair.out")
else:
# since the job is ran on output from parent this "input" should be the output of the parent process
shutil.move("input.pdb", "input_Repair.pdb") # Pretend it was ran
if cleanup:
try:
shutil.move("input_Repair.fxout", "RepairPDB.fxout")
shutil.move("input_Repair.pdb", "folded.pdb")
except IOError:
raise logger.FoldXError("FoldX didn't produce expected repair files. "
"Can't continue without it. This is unexpected and could indicate FoldX issues.")
def build_mutant(self, working_dir="", mutation_list=""):
os.chdir(working_dir)
logger.to_file(filename="individual_list.txt", content=mutation_list)
self.minimize_energy(working_dir=working_dir, cleanup=False, skip_min=self.skip)
_cmd = [join(self.bin_dir, _bin_name), "-f", self.mut_fold_config]
self._run_foldx(cmd=_cmd, msg="Building mutant model", outfile="buildMutant.out")
try:
shutil.move("input_Repair_1.pdb", "input.pdb")
except IOError:
raise logger.FoldXError("FoldX didn't produce expected mutant file. "
"Can't continue without it. This is unexpected and could indicate FoldX issues.")
self._cleanup()
@staticmethod
def _run_foldx(cmd, msg='', outfile=''):
"""Assumes the directory it's run from contains """
logger.info(module_name="FoldX", msg=msg)
logger.debug(module_name="FoldX", msg="Starting FoldX with %s" % " ".join(cmd))
out, err = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
if err:
logger.warning(module_name="FoldX", msg=err)
logger.to_file(filename=outfile, content=out, allow_err=False)
# TODO proper cleanup handling this is a mess + is this even necessary?
def _cleanup(self):
with open("Dif_input_Repair.fxout", 'r') as enelog:
d = enelog.readlines()[-1]
d = d.split()[1] + " kcal/mol"
logger.to_file(filename=join(self.agg_work_dir, "MutantEnergyDiff"), content=d)
try:
os.mkdir(join(self.agg_work_dir, "foldxOutput"))
except OSError:
logger.log_file(module_name=_name, msg="Couldn't create foldxOutput folder (probably already exists)")
shutil.move("Raw_input_Repair.fxout",
join(self.agg_work_dir, "foldxOutput/Stability_RepairPDB_input.fxout"))
shutil.move("Dif_input_Repair.fxout",
join(self.agg_work_dir, "foldxOutput/Dif_BuildModel_RepairPDB_input.fxout"))
def _check_files(self):
if not isfile(join(self.bin_dir,"rotabase.txt")) or not isfile(join(self.bin_dir,_bin_name)):
raise logger.FoldXError("Provided FoldX directory (%s) misses either %s or %s " %
(self.bin_dir, "rotabase.txt", _bin_name) +
"files which are required for the program to run.")
if not isfile(self.fold_config):
try:
self._recover_script()
except logger.FoldXError:
raise
if not isfile(self.mut_fold_config):
try:
self._recover_mut_script()
except logger.FoldXError:
raise
def _recover_script(self):
"""
Re-write the repairPDB file in case something goes wrong
For more info on FoldX commands and parameters see http://foldxsuite.crg.eu/documentation#manual
Default FoldX parameters include:
ph=7
temperature=298
ionStrength=0.05
vdwDesign=2
pdbHydrogens=false
"""
fold_script = (
"pdb=input.pdb\n"
"command=RepairPDB\n"
"water=-CRYSTAL\n"
)
try:
with open(self.fold_config, "w") as f:
f.write(fold_script)
except IOError:
raise logger.FoldXError("FoldX requires %s file to be present." % self.fold_config +
"If default settings are used it should be in data folder inside aggrescan directory." +
"Attempted to re-write the file %s to %s but failed" % (self.fold_config, self.script_dir))
def _recover_mut_script(self):
"""
Re-write the buildModel file in case something goes wrong
For more info on FoldX commands and parameters see http://foldxsuite.crg.eu/documentation#manual
Default FoldX parameters include:
ph=7
temperature=298
ionStrength=0.05
vdwDesign=2
pdbHydrogens=false
"""
fold_mut_script = (
"pdb=input_Repair.pdb\n"
"command=RepairPDB\n"
"water=-CRYSTAL\n")
try:
with open(self.mut_fold_config, "w") as f:
f.write(fold_mut_script)
except IOError:
raise logger.FoldXError("FoldX mutation requires %s file to be present." % self.mut_fold_config +
"If default settings are used it should be in data folder inside aggrescan directory." +
"Attempted to re-write the file %s to %s but failed" % (self.mut_fold_config, self.script_dir)) | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/foldx_module.py | foldx_module.py |
import logger
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import re
import os
import warnings
import json
from os.path import join
from collections import OrderedDict
_name = "postProc"
def params():
"""
Sets some global parameters for the plots
:return: None
"""
plt.rcParams['axes.facecolor'] = 'f5f5f5'
plt.rcParams['axes.edgecolor'] = '0.45'
plt.rcParams['axes.axisbelow'] = True
plt.rcParams['axes.labelcolor'] = '0.45'
plt.rcParams['text.color'] = '0.45'
plt.rcParams['xtick.color'] = '0.45'
plt.rcParams['ytick.color'] = '0.45'
plt.rcParams['xtick.major.pad'] = 4
plt.rcParams['ytick.major.pad'] = 5
plt.rcParams['xtick.major.width'] = 1
plt.rcParams['ytick.major.width'] = 1
def get_scores(out_file):
"""
:param out_file: path to a csv file generated by Aggrescan3D
:return: dictionary - {chainID:[residue ID, agg3d score, residue label]},
dictionary - {chainID:{"min_value":val,"max_value":val,
"total_value":val,"avg_value":val}}
"""
pattern = re.compile(r"^(.*),(.*),(.*),(.*),(.*)$", re.M)
with open(out_file, 'r') as f:
data = pattern.findall(f.read().replace("\r", ""))[1:]
chains = set([i[1] for i in data])
chains.add("All")
dat = {}
scores = {}
stats = {}
resNumber = 1
for chain_id in chains:
dat[chain_id] = []
scores[chain_id] = []
for line in data:
if len(line) != 5:
continue
chain = line[1]
label = line[3] + line[2] # One letter code + residue ID
aggScore = float(line[4])
scores[chain].append(aggScore)
scores["All"].append(aggScore)
if abs(aggScore) > 1e-10: # Skip residues with 0 score
dat[chain].append((resNumber, aggScore, label))
resNumber += 1
for chain in chains:
min3d = min(scores[chain])
max3d = max(scores[chain])
sum3d = np.sum(scores[chain])
avg3d = np.round(sum3d / len(scores[chain]), decimals=4)
stats[chain] = {"min_value": min3d, "max_value": max3d, "total_value": sum3d, "avg_value": avg3d}
return dat, stats
def make_plots(data=None, work_dir="", get_figure=False):
"""
Creates png and svg plots of Aggrescan3D scores for a single chain
:param data: dictionary - {chainID:[residue ID, agg3d score, residue label]}
:param work_dir: directory where the plots will be saved
:param get_figure: if set to True, will return the figure
:return: None or plt.figure object
"""
warnings.simplefilter("ignore")
for chain in data.keys():
if chain != "All":
dat = data[chain]
params()
fig = plt.figure(figsize=(10, 6.6))
x = np.array([l[0] for l in dat])
y = np.array([l[1] for l in dat])
l = np.array([l[2] for l in dat])
plt.xlabel("Residue")
plt.ylabel("Score")
plt.axhline(linewidth=1, color='0.45', linestyle='--')
plt.xticks(x[1::10], l[1::10], rotation=35, fontsize='small')
plt.title("A3D profile | chain " + chain)
plt.axis(ymin=-4, ymax=4, xmin=min(x) - 2, xmax=max(x) + 2)
plt.plot(x, y, linewidth=1.5, alpha=0.75, marker='o', mec='None')
plt.grid(alpha=0.5, color='0.9', linewidth=1, linestyle='--')
for x, y, l in zip(x, y, l):
if float(y) > 0.0:
plt.annotate(l, xy=(x, y), xytext=(1, 1), alpha=0.5, fontsize='small', gid="label_" + str(x),
textcoords='offset points')
logger.log_file(module_name=_name,msg="Saving plots as %s.png and %s.svg" % (chain, chain))
plt.savefig(os.path.join(work_dir, "%s.png" % chain), format="png")
plt.savefig(os.path.join(work_dir, "%s.svg" % chain), format="svg")
if get_figure: return fig
def make_auto_mut_plot(work_dir=""):
"""
Create a collective plot of mutants and the wild type, this is mostly a copy paste from server plot into mpl
#TODO actually use fig axes object rather than plt like that
"""
_target_mutations = ["E", "K", "D", "R"] # This should mirror one in auto_mutation but can't be imported because they also import this first
warnings.simplefilter("ignore")
mutants = []
with open(join(work_dir, "Mutations_summary.csv"), "r") as f:
f.readline()
for line in f:
mutants.append(line.split(",")[0])
with open(join(work_dir, "A3D.csv"), 'r') as f:
f.readline() # skip the initial line with labels
wild_labels, wild_y = [], []
for line in f:
a = line.strip().split(',')
# a goes as follows: model name, chain, index, one letter code, aggrescan score
wild_labels.append(("Chain %s" % a[1], a[2] + a[3]))
wild_y.append(float(a[-1]))
wild_x = [i for i in range(len(wild_y))]
while mutants:
data = OrderedDict()
one_r_mutated = []
mutated = mutants[0][0]
for mutant in mutants[:]: # Create a slice to prevent the iterator from skipping itmes
if mutant[0] == mutated:
one_r_mutated.append(mutants.pop(mutants.index(mutant))) # Mutations are 'guaranteed' to be unique
data["Wild_type"] = [wild_x, wild_y, wild_labels]
for mutant in one_r_mutated:
with open(join(work_dir, mutant + ".csv"), 'r') as f:
f.readline() # skip the initial line with labels
labels, y = [], []
for line in f:
a = line.strip().split(',')
# a goes as follows: model name, chain, index, one letter code, aggrescan score
labels.append(("Chain %s" % a[1], a[2]+a[3]))
y.append(float(a[-1]))
x = [i for i in range(len(y))]
data[mutant] = [x, y, labels]
_plot(data, work_dir, filename="%s_mutants" % mutant[2:])
def _plot(data, work_dir, filename):
params()
fig = plt.figure(figsize=(10, 6.6))
plt.ylabel("Score")
plt.axhline(linewidth=1, color='0.45', linestyle='--')
plt.title("A3D mutations profile")
plt.grid(alpha=0.5, color='0.9', linewidth=1, linestyle='--')
for key, value in data.iteritems():
x, y, labels = value
plt.plot(x, y, label=key, linewidth=1.5, alpha=0.75, marker='o', mec='None')
plt.xticks(x[1::10], labels[1::10], rotation=35, fontsize='small')
logger.log_file(module_name=_name, msg="Saving auto mutation plots to %s (svg and png)" % filename)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.savefig(os.path.join(work_dir, filename + ".png"), format="png", bbox_inches='tight')
plt.savefig(os.path.join(work_dir, filename + ".svg"), format="svg", bbox_inches='tight')
plt.close()
def append_scores(a3d="", in_pdb="", out_pdb="", work_dir=""):
"""
Replaces the last field in pdb file with Aggrescan3D score
:param a3d: filepath to a csv aggrescan-formatted file with scores
:param in_pdb: filepath to a input pdb file
:param out_pdb: fielapth to which the output will be written
:param work_dir: Output directory
:return: None
"""
rec = re.compile(r"^(.*),(.*),(.*),(.*),(.*)$", re.M)
amino_a_dict ={'A': 'ALA', 'R': 'ARG','N': 'ASN','D': 'ASP','C': 'CYS','E': 'GLU',
'Q': 'GLN','G': 'GLY','H': 'HIS','I': 'ILE','L': 'LEU','K': 'LYS',
'M': 'MET','F': 'PHE','P': 'PRO','S': 'SER','T':'THR','W': 'TRP',
'Y': 'TYR', 'V': 'VAL','X': 'UNK'}
with open(a3d, "r") as agg_out_fh, open(in_pdb, "r") as p:
block = p.read()
d = rec.findall(agg_out_fh.read().replace("\r", ""))[1:]
for r in d:
amino_acid = amino_a_dict[r[3]]
agg_score = "%6.2f" % (float(r[4]))
res_details = "%3s %1s%4s" % (amino_acid, r[1], r[2]) # 3 letter code, chain ID, res ID
block = re.sub(r'(?<=^ATOM.{13}'+res_details+'.{34})(.*)$', agg_score, block, flags=re.M)
logger.to_file(filename=os.path.join(work_dir, out_pdb), content=block)
def save_stats(data="", work_dir="", output="statistics"):
"""
Saves statistcs of the Aggrescan3D scores calculations
:param data: string - JSON generated by get_scores, formatted like:
{chainID:{"min_value":val,"max_value":val,"total_value":val,"avg_value":val}}
:param work_dir: Output directory
:param output: outputs filename
:return: None
"""
logger.to_file(filename=os.path.join(work_dir, output), content=data)
def prepare_output(work_dir="", final=True, model_name="", scores_to_pdb=False):
"""
Calls make_plots, save_stats and append_scores, see details there
:param work_dir: Working dir of Aggrescan3D run
:param final: [bool] if True data is plotted and output.pdb generated to work_dir
:param model_name: [string] filename of the currently analyzed pdb file (without the .pdb part)
:param scores_to_pdb: [bool] Decide if a3d score should be pun in the file's bfactor place
:return: dictionary - {chainID: {"min_value" : val, "max_value" : val,
"total_value" : val, "avg_value" : val}}
"""
data, stats = get_scores(os.path.join(work_dir, "A3D.csv"))
save_stats(data=json.dumps(stats), output=model_name + "_stats", work_dir=work_dir)
if scores_to_pdb:
append_scores(a3d=os.path.join(work_dir, "A3D.csv"), in_pdb=model_name + ".pdb",
out_pdb=model_name+".pdb", work_dir=work_dir)
if final:
make_plots(data=data, work_dir=work_dir)
append_scores(a3d=os.path.join(work_dir, "A3D.csv"), in_pdb=os.path.join(work_dir, "folded.pdb"),
out_pdb=os.path.join(work_dir, "output.pdb"), work_dir=work_dir)
return stats | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/postProcessing.py | postProcessing.py |
import sys
import pymol
from pymol import cmd, stored, util
pymol_mode = sys.argv[1]
pdb_file = sys.argv[2]
output_file = sys.argv[3]
try:
pdb_code = pdb_file.split('/')[1].split('.')[0]
except IndexError:
pdb_code = pdb_file.split('.')[0]
if pymol_mode == "s":
pymol.pymol_argv = ['pymol','-qc'] # PyMol quiet launch without GUI
out_folder = sys.argv[4]
fh = open(output_file, "r")
lines = fh.readlines()
pymol.finish_launching()
cmd.load(pdb_file)
#cmd.remove("HET")
cmd.set_name(pdb_code, pdb_code+'_A3D')
cmd.hide("all")
cmd.show("surface", "all")
cmd.color("white", "all")
#define the reds
cmd.set_color("red1", [1, 0, 0 ]) # most intense red
cmd.set_color("red2", [1, 0.2, 0.2])
cmd.set_color("red3", [1, 0.4, 0.4])
cmd.set_color("red4", [1, 0.6, 0.6])
cmd.set_color("red5", [1, 0.8, 0.8]) # lightest red
#define the blues
cmd.set_color("blue1", [0, 0, 1]) # most intense blue
cmd.set_color("blue2", [0.2, 0.2, 1])
cmd.set_color("blue3", [0.4, 0.4, 1])
cmd.set_color("blue4", [0.6, 0.6, 1])
cmd.set_color("blue5", [0.8, 0.8, 1]) # lightest blue
high_score = 0
high_res = -1500100900
for line in lines[1:]:
if not (line == "\n" or line.startswith('#')):
line_params = line.strip().replace('//', '').split(" ")
score = float(line_params[3])
chain = line_params[0]
if chain == '-':
my_res = "resi " + line_params[1]
else:
my_res = "chain " + line_params[0] + " and resi " + line_params[1]
if score > 0: # residues with a value above 0 will be colored red
if score < 0.5:
cmd.color("red4", my_res)
elif score < 1:
cmd.color("red3", my_res)
elif score < 1.5:
cmd.color("red2", my_res)
else:
cmd.color("red1", my_res)
if score > high_score:
high_score = score
high_res = my_res
elif score < -0.5: # residues with a value below -0.5 will be colored blue
if score > -1:
cmd.color("blue5", my_res)
elif score > -1.5:
cmd.color("blue4", my_res)
elif score > -2:
cmd.color("blue3", my_res)
elif score > -2.5:
cmd.color("blue2", my_res)
else:
cmd.color("blue1", my_res)
# create an object for the high score hot spot of the protein
if high_res != -1500100900:
cmd.create("hot_spot", "("+high_res+",byres "+high_res+" around 5 and not HET \
and not color white and not color blue1 and not color blue2 and not color blue3 \
and not color blue4 and not color blue5)")
stored.neighbours=[]
cmd.iterate("(hot_spot & n. ca)", "stored.neighbours.append((resi,resn))")
cmd.reset()
# Save PyMol session
if pymol_mode == "s":
cmd.viewport("640", "480")
cmd.origin()
cmd.set("field_of_view",30)
cmd.set("surface_quality", "1")
cmd.set("ray_trace_mode", "1")
cmd.bg_color("white")
cmd.set("antialias", "2")
for xx in range(1, 19):
cmd.rotate("y", 20)
cmd.ray("640", "480")
cmd.png("mov%05d.png" % (xx))
cmd.quit() | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/paintit.py | paintit.py |
import os
import sys
from time import time, strftime, gmtime
import textwrap
import platform
_name = "Logger"
colors = {
"blue": '\033[94m',
"yellow": '\033[93m',
'green': '\033[92m',
'red': '\033[91m',
'light_blue': '\033[96m',
'purple': '\033[95m',
'end': '\033[0m',
}
log_levels = {
0: "[CRITICAL]",
1: "[WARNING]",
2: "[INFO]",
3: "[OUT FILES]",
4: "[DEBUG]"
}
color_prefix = {
0: colors["red"] + "[CRITICAL]" + colors["end"],
1: colors["yellow"] + "[WARNING]" + colors["end"],
2: colors["blue"] + "[INFO]" + colors["end"],
3: colors["purple"] + "[OUT FILES]" + colors["end"],
4: colors["green"] + "[DEBUG]" + colors["end"],
}
_init_time = time()
_log_level = 2
_color = True
_stream = sys.stderr
_line_format = '%-20s %-19s%-75s %s\n'
_first_line_format = '%-20s %-19s%-75s \n'
_middle_line_format = '%-22s%-75s \n'
_last_line_format = '%-22s%-75s %s\n'
_line_break = 76
_remote = False
_prefix = color_prefix
_work_dir = ""
def setup(log_level=2, remote=False, work_dir=''):
global _log_level, _color, _stream, _remote, _line_break, _prefix, _work_dir
global _line_format, _middle_line_format, _first_line_format, _last_line_format
_log_level = log_level
_remote = remote
_work_dir = work_dir
if _remote or not sys.stderr.isatty():
_color = False
_line_format = '%-12s %-10s%-75s %s\n'
_first_line_format = '%-12s %-10s%-75s \n'
_middle_line_format = '%-22s %-75s \n'
_last_line_format = '%-22s %-75s %s\n'
_prefix = log_levels
if _remote:
_log_path = os.path.join(work_dir, "Aggrescan.log")
try:
_stream = open(_log_path, 'a+')
except IOError:
try:
os.makedirs(work_dir)
_stream = open(_log_path, 'a+')
except OSError:
warning(module_name=_name,
msg="Could not open a log file at %s. Writing to standard error instead." % _log_path)
else:
_stream.close()
_stream = _log_path
else:
_stream.close()
_stream = _log_path
if platform.system() == "Windows":
_color = False # Windows doesn't support this way of coloring its logs in the command line
_prefix = log_levels
info(_name, 'Verbosity set to: ' + str(log_level) + " - " + log_levels[log_level])
def log_files():
"""
:return: True if verbosity is high enough to save extra output (LOG FILE level)
"""
return _log_level >= 3
def get_log_level():
return _log_level
def coloring(color_name="light_blue", msg=""):
if _color:
return colors[color_name] + msg + colors["end"]
return msg
def log(module_name="MISC", msg="Processing ", l_level=2, out=None):
if out is None:
# This is not great but should use stderr if there's a problem with log file, hopefully no race happens
# This whole thing is attempting to force the log to really flush its data in real time
try:
out = open(_stream, 'a+')
except TypeError: # This should mean _stream is actually stderr
out = _stream
if l_level <= _log_level:
t = gmtime(time() - _init_time)
if len(msg) < _line_break:
msg = _line_format % (
_prefix[l_level], coloring(msg=module_name + ":", color_name='light_blue'),
msg, strftime('(%H:%M:%S)', t)
)
out.write(msg)
out.flush()
else:
lines = textwrap.wrap(msg, width=_line_break-1)
first_line = _first_line_format % (
_prefix[l_level], coloring(msg=module_name + ":", color_name='light_blue'), lines[0]
)
out.write(first_line)
for lineNumber in xrange(1, len(lines) - 1):
line = _middle_line_format % (" ", lines[lineNumber])
out.write(line)
final_line = _last_line_format % (" ", lines[-1], strftime('(%H:%M:%S)', t))
out.write(final_line)
out.flush()
if out is not sys.stderr:
out.close()
def critical(module_name="_name", msg=""):
log(module_name=module_name, msg=msg, l_level=0)
def warning(module_name="_name", msg=""):
log(module_name=module_name, msg=msg, l_level=1)
def info(module_name="_name", msg=""):
log(module_name=module_name, msg=msg, l_level=2)
def log_file(module_name="_name", msg=""):
log(module_name=module_name, msg=msg, l_level=3)
def debug(module_name="_name", msg=""):
log(module_name=module_name, msg=msg, l_level=4)
def to_file(filename='', content='', msg='', allow_err=True, traceback=True):
"""
:param filename: path for the file to be saved
:param content: a string to be saved (be careful not to pass a string that is too long
:param msg: optional: a message to be logged
:param allow_err: if True a warning will be logged on OSError, if False program exit call will be made
:param traceback: if True an Exception will be raised on exit call
:return:
"""
if filename and content:
try:
if os.path.isfile(filename):
log_file(module_name=_name, msg="Overwriting %s" % filename)
with open(filename, 'w') as f:
f.write(content)
except IOError:
if allow_err:
warning(module_name=_name, msg="IOError while writing to: %s" % filename)
else:
exit_program(module_name=_name, msg="IOError while writing to: %s" % filename, traceback=traceback)
if msg:
log_file(module_name=_name, msg=msg)
def exit_program(module_name=_name, msg="Shutting down", traceback=None, exc=None):
"""
Exits the program, depending on options might do it quietly, raise, or print traceback
:param module_name: string with the calling module's name
:param msg: string, message to be printed when the program exits
:param traceback: str, if log level is high traceback will be printed
:param exc: a specific exception passed by the caller
:return: None
"""
if exc:
_msg = '%s: %s' % (msg, exc.message)
else:
_msg = msg
critical(module_name=module_name, msg=_msg)
if _log_level > 3 and traceback:
_stream.write(traceback)
sys.exit(1)
def record_exception(trace_stack):
global _work_dir
with open(os.path.join(_work_dir, "Aggrescan.error"), 'w') as f:
file_header = "Aggrescan encountered an error and it wasn't one we were expecting. \n" \
"Please see the the following Traceback, perhaps it will be helpfull in understanding what happened.\n" \
"We would be grateful if you reported the incident to one of the authors so we can correct the error.\n"
f.write(file_header)
f.write(trace_stack)
class AggrescanError(Exception):
"""Generic class for Aggrescan Exceptions that should be handled or otherwise logged
The subclasses are meant to do most of the work, so this is obviously work in progress
and hopefully subclasses will do more in the future"""
def __init__(self, *args, **kwargs):
self.module_name = ""
self.log_if_remote = ""
self.work_dir_error = ""
self.error_msg = ""
self.err_file = ""
if "module_name" in kwargs:
self.module_name = kwargs["module_name"]
if "err_file" in kwargs: # Prevents the error log from being created - since the error is path/dir related
self.err_file = kwargs["err_file"]
if "work_dir_error" in kwargs:
self.work_dir_error = True
self.logger_msg = self.module_name + " encountered an error"
if args:
self.error_msg = args[0]
Exception.__init__(self, *args)
# This function and err_file serve a somewhat convoluted function - they split what is the message
# to be displayed on screen and the one that would be logged in a file into two separate places using a proxy -
# extra error file
def generate_error_file(self):
global _work_dir
if not self.work_dir_error:
out_file = os.path.join(_work_dir, "Aggrescan.error")
file_header = "One of Aggrescan3D modules (%s) encountered an error. \n" % self.module_name
with open(out_file, 'a+') as f:
if self.err_file:
f.write(file_header)
with open(os.path.join(_work_dir, self.err_file), 'r') as err_file:
f.write(err_file.read())
else:
f.write(file_header)
f.write(self.error_msg)
class FoldXError(AggrescanError):
def __init__(self, *args, **kwargs):
_module_name = "FoldX"
AggrescanError.__init__(self, *args, module_name=_module_name, **kwargs)
class CabsError(AggrescanError):
def __init__(self, *args, **kwargs):
_module_name = "CABS"
AggrescanError.__init__(self, *args, module_name=_module_name, **kwargs)
class ASAError(AggrescanError):
def __init__(self, program_name, filename):
_module_name = "ASA"
msg = "Aggrescan encountered an error while performing accessibility calculations with %s. " \
"See the details in the Aggrescan.error file in your working directory." % program_name
AggrescanError.__init__(self, msg, module_name=_module_name, err_file=filename)
class InputError(AggrescanError):
def __init__(self, *args):
_module_name = "OptParser"
AggrescanError.__init__(self, *args, module_name=_module_name) | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/logger.py | logger.py |
import sys,shutil
import logger
from newRunJob import Job
import optparser as opt
import traceback as _tr
_name = "Main"
def _cleanup(aggrescan_job_instance):
"""
Done to prevent a situation where Job raises an error on initialization and there is nothing to delete
Normally deletes or keeps the simulations temporary directory depending on verbosity settings
(Can't check for Exceptions in finally block, hence the function)
"""
try:
if logger.get_log_level() < 4:
shutil.rmtree(aggrescan_job_instance.get_tempdir(),ignore_errors=True)
logger.log_file(module_name=_name, msg="Removing temporary files")
else:
logger.log_file(module_name=_name,
msg="Verbosity higher than 3 - temporary files kept in %s"
% aggrescan_job_instance.get_tempdir())
except AttributeError:
pass
def run_program():
try:
a = "dummy" # to avoid cleanup on empty instances
options = opt.parse(options=sys.argv[1:])
logger.setup(log_level=options['verbose'], remote=options['remote'], work_dir=options["work_dir"])
a = Job(config=options)
a.run_job()
_cleanup(a)
logger.info(module_name="Main", msg="Simulation completed successfully.")
except KeyboardInterrupt:
_cleanup(a)
logger.info(module_name=_name, msg="Interrupted by user")
except logger.AggrescanError as custom_error:
_cleanup(a)
custom_error.generate_error_file()
logger.exit_program(module_name=custom_error.module_name,
msg=custom_error.logger_msg,
traceback=None,
exc=custom_error)
except Exception as e:
_cleanup(a)
logger.record_exception(trace_stack=_tr.format_exc())
logger.critical(module_name=_name,
msg="Unhandled Exception caught: %s." % e.message)
if logger.get_log_level() > 2:
logger.info(module_name=_name,
msg="Verbosity higher than 2 - raising the Exception to provide traceback.")
raise
else:
logger.exit_program() | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/__main__.py | __main__.py |
import os
import errno
import shutil
import logger
from os.path import join, abspath
from subprocess import Popen, PIPE
from glob import glob
from pkg_resources import resource_filename
import json
import tarfile
from postProcessing import prepare_output
from analysis import aggregation_analysis as analyze
from collections import OrderedDict
_name = "CABS"
def run_cabs(config, pdb_input="input.pdb"):
"""Takes an Aggrescan3D Job config dictionary and should never change it"""
real_work_dir = config["work_dir"]
os.chdir(real_work_dir)
real_cabs_dir = os.path.join(real_work_dir, "CABS_sim")
real_models_dir = os.path.join(real_cabs_dir, "output_pdbs")
try:
_makedir(real_cabs_dir)
_makedir("models")
_makedir("stats")
shutil.copyfile(pdb_input, os.path.join(real_cabs_dir,
pdb_input))
except OSError:
raise logger.CabsError("Failed to prepare CABS directory at: %s" % real_cabs_dir)
os.chdir(real_cabs_dir)
logger.info(module_name=_name,
msg="Running CABS flex simulation")
cabs_cmd = _prepare_command(pdb_input=pdb_input, cabs_dir=config["cabs_dir"],
cabs_config=config["cabs_config"], n_models=config["n_models"])
logger.debug(module_name=_name,
msg="CABS ran with: %s" % " ".join(cabs_cmd))
out, err = Popen(cabs_cmd, stdout=PIPE, stderr=PIPE).communicate()
if err:
with open(join(real_work_dir, "CABSerror"), 'w') as f:
f.write(err)
_cleanup_files(work_dir=real_work_dir, cabs_dir=real_cabs_dir, clean=False)
raise logger.CabsError("Please see CABSerror file within your work directory for more details",
err_file="CABSerror")
try:
_check_output(models_dir=real_models_dir, n_models=config["n_models"])
except logger.CabsError:
shutil.move(join(real_cabs_dir, "CABS.log"), join(real_work_dir, "CABS.log"))
_cleanup_files(work_dir=real_work_dir, cabs_dir=real_cabs_dir, clean=False)
raise logger.CabsError("Please see CABS.log file within your work directory for more details",
err_file="CABS.log")
shutil.copyfile(pdb_input, join("output_pdbs", pdb_input))
os.chdir("output_pdbs")
models = glob("model*.pdb")
top = ""
max_avg = -100
averages = {}
for model in models:
model_path = abspath(model)
analyze(config=config, target=model_path, working_dir=real_models_dir, agg_work_dir=real_work_dir)
stats = prepare_output(work_dir=real_models_dir, final=False,
model_name=model.split(".")[0], scores_to_pdb=True)
current_avg = stats["All"]["avg_value"]
averages[model] = current_avg
if current_avg > max_avg:
max_avg = stats["All"]["avg_value"]
top = model
shutil.move("A3D.csv", join(real_work_dir, "stats", model.split(".")[0] + ".csv"))
shutil.move(model, join(real_work_dir, "models", model))
analyze(config=config, target=pdb_input, working_dir=real_models_dir, agg_work_dir=real_work_dir)
stats = prepare_output(work_dir=real_models_dir, final=False,
model_name=pdb_input.split(".")[0], scores_to_pdb=True)
current_avg = stats["All"]["avg_value"]
averages[pdb_input] = current_avg
if current_avg > max_avg:
top = pdb_input
shutil.move("A3D.csv", join(real_work_dir, "stats", pdb_input.split(".")[0] + ".csv"))
shutil.move(pdb_input, join(real_work_dir, "models", pdb_input))
with open('averages', 'w') as avg:
json.dump(_sort_dict(my_dict=averages), avg)
os.chdir(real_work_dir)
_cleanup_files(work_dir=real_work_dir, cabs_dir=real_cabs_dir, input_pdb=pdb_input, top=top, clean=True)
superimpose(first_model="input.pdb", second_model="folded.pdb")
def superimpose(first_model, second_model):
try:
pymol_cmd = ["pymol", "-cq", resource_filename("aggrescan", join("data", "superimpose.pml")), "--", first_model, second_model]
out, err = Popen(pymol_cmd, stdout=PIPE, stderr=PIPE).communicate()
if err:
logger.warning(module_name="Pymol",
msg="Pymol reports an error: %s" % err)
shutil.move("superimposed.png", "CABSflex_supe.png")
except OSError:
logger.warning(module_name=_name,
msg="Pymol failed to launch (most likely not present on the system)."
"Couldn't create a superimposed picture of CABS input and output ")
except (shutil.Error, IOError):
logger.critical(module_name="Pymol",
msg="Pymol failed to create a superimposed image for input and "
"most aggregation prone CABS model")
def _prepare_command(pdb_input="input.pdb", cabs_dir=".", cabs_config='', n_models=12):
"""Prepare CABS settings according to user input"""
cabs_cmd = []
if cabs_dir:
cabs_cmd.extend(["python", cabs_dir, "flex"])
else:
cabs_cmd.append("CABSflex")
if cabs_config:
cabs_cmd.extend(["-c", cabs_config])
else:
cabs_cmd.extend(["--image-file-format", "png", "-v", "4"])
cabs_cmd.extend(["--input", pdb_input, "--clustering-medoids", str(n_models), "--aa-rebuild", "--log"])
return cabs_cmd
def _cleanup_files(work_dir="", cabs_dir="", input_pdb="", top="", clean=True):
"""If clean some files will be saved, else only remove all created files"""
if clean:
shutil.move(join(cabs_dir, "plots", "RMSF_seq.png"), join(work_dir, "CABSflex_rmsf.png"))
shutil.move(join(cabs_dir, "plots", "RMSF.csv"), join(work_dir, "CABSflex_rmsf.csv"))
shutil.copyfile(join(work_dir, "models", top.strip()), join(work_dir, "folded.pdb"))
shutil.copyfile(join(cabs_dir, "output_pdbs", "averages"), "averages")
if logger.get_log_level() >= 2 and clean:
logger.log_file(module_name="CABS",
msg="Saving top CABS models as %s" % "models.tar.gz")
with tarfile.open(join(work_dir, "models.tar.gz"), "w:gz") as tar:
tar.add(join(work_dir, "models"), arcname=os.path.sep)
logger.log_file(module_name="CABS",
msg="Saving Aggrescan3D statistics for all CABS models as %s" % "stats.tar.gz")
with tarfile.open(join(work_dir, "stats.tar.gz"), "w:gz") as tar:
tar.add(join(work_dir, "stats"), arcname=os.path.sep)
shutil.rmtree(join(work_dir, "stats"), ignore_errors=True)
shutil.rmtree(join(work_dir, "models"), ignore_errors=True)
_del_cabs_dir(cabs_dir=cabs_dir)
def _del_cabs_dir(cabs_dir="CABS_sim"):
shutil.rmtree(cabs_dir, ignore_errors=True)
def _check_output(models_dir, n_models):
"""Check if all the required files were created"""
_file_list = ["CABS.log"]
_file_list.extend([join(models_dir, "model_%s.pdb" % str(i)) for i in range(n_models)])
_file_list.append(join("plots", "RMSF_seq*"))
_file_list.append(join("plots", "RMSF*"))
for filename in _file_list:
if not glob(filename):
logger.critical(module_name="CABS",
msg="File %s which CABS should have generated was not found." % filename)
raise logger.CabsError
def _sort_dict(my_dict):
"""Return a reverse-sorted by value, OrderedDict of a regular dictionary with number values"""
new_dict = OrderedDict()
for key, value in sorted(my_dict.iteritems(), key=lambda (k, v): (v, k), reverse=True):
new_dict[key] = value
return new_dict
def _makedir(path):
"""Ignore error if path exists"""
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/dynamic_module.py | dynamic_module.py |
import os
import math
import csv
import logger
# minimum and maximum surface exposition to be considered
min_surf = 10
max_surf = 55
_name = "agg3D"
class Residue:
def __init__(self, chain, resi, resn, coords, rsa, score_matrix):
if chain == ' ':
self.chain = '-'
else:
self.chain = chain
self.resi = resi
self.resn = get_one_letter(resn) # we store it in one-letter code
self.coords = coords
self.score_matrix = score_matrix
self.agg_sup = self.calc_res_agg_fin(rsa=rsa)
self.agg_fin = 0
def __str__(self):
return self.chain+self.resn
def set_agg_fin(self, agg_dis_sum):
self.agg_fin = self.agg_sup + agg_dis_sum
def id(self):
return self.chain+self.resn+self.resi
def set_rsa(self, rsa):
self.agg_sup = self.calc_res_agg_fin(rsa=rsa)
def calc_res_agg_fin(self, rsa):
if rsa < min_surf:
return 0
else:
if rsa > max_surf:
rsa = max_surf
return float(self.score_matrix[self.resn]) * 0.0599 * math.exp(0.0521 * rsa)
class Protein:
def __init__(self, pdb_code, residues, out_dir, max_dist):
self.name = pdb_code
self.residues = residues
self.out_dir = out_dir
self.max_dist = max_dist
def __str__(self):
return self.name
def add_residue(self, res):
self.residues.append(res)
def change_res_rsa(self, res_number, res_id, rsa):
if self.residues[res_number].id() == res_id:
self.residues[res_number].set_rsa(rsa)
else:
logger.critical(module_name=_name,
msg="Error while parsing freeSasa output. Probably freeSasa failed quietly.")
logger.critical(module_name=_name,
msg="Failed to assign rsa to %s proper id is: %s " %
(res_id, self.residues[res_number].id()) +
"(ChainID, residue's one letter code, residue's ID)")
raise logger.AggrescanError("Failed to parse freeSasa output. Qutting.",
module_name=_name)
def calc_agg_fin(self):
"""Calculate the agg_dis_sum for every Residue in the Protein"""
dist_correction = -2.56 / self.max_dist
for central in self.residues:
agg_dis_sum = 0
if not central.agg_sup == 0:
for peripheric in self.residues:
dist = get_distance(central.coords, peripheric.coords)
if dist < self.max_dist and not dist == 0:
agg_dis_sum += peripheric.agg_sup * 1.2915 * math.exp(dist_correction*dist)
central.set_agg_fin(agg_dis_sum)
def short_summary(self):
"""Return a short summarized output and identify it with a leading #"""
total_sum = 0
maximum = 0
minimum = 0
pos_auc = 0
neg_auc = 0
prev_score = 0
res_number = len(self.residues)
for res in self.residues:
total_sum += res.agg_fin
if res.agg_fin > maximum:
maximum = res.agg_fin
if res.agg_fin < minimum:
minimum = res.agg_fin
if res.agg_fin != 0:
if prev_score != 0:
auc = (res.agg_fin + prev_score)/2
if auc > 0:
pos_auc += abs(auc)
else:
neg_auc += abs(auc)
prev_score = res.agg_fin
return '#' + self.name + " " + ' '.join(str("%.4f" % round(val, 4))
for val in (total_sum,
total_sum/res_number,
maximum,
minimum,
pos_auc))
def long_output(self):
"""Return the complete output and identify it with a leading //"""
output = ""
for res in self.residues:
output += '//' + " ".join((res.chain, res.resi, res.resn)) + " %.4f\n" % round(res.agg_fin, 4)
return output
def out_csv(self):
"""Save the complete output in a csv file"""
csv_file = os.path.join(self.out_dir, "A3D.csv")
c = csv.writer(open(csv_file, "w"))
if os.stat(csv_file).st_size == 0:
c.writerow(["protein", "chain", "residue", "residue_name", "score"])
for res in self.residues:
c.writerow([self.name.split("/")[-1], res.chain, res.resi, res.resn, "%.4f" % round(res.agg_fin, 4)])
def get_residues(self):
return self.residues
def get_one_letter(raw):
"""Return the one letter code for a residue"""
if len(raw) > 3:
aa = raw[-3:]
else:
aa = raw
three_letters = aa.capitalize()
conversion = {"Ala": "A", "Arg": "R", "Asn": "N", "Asp": "D", "Cys": "C",
"Glu": "E", "Gln": "Q", "Gly": "G", "His": "H", "Ile": "I",
"Leu": "L", "Lys": "K", "Met": "M", "Phe": "F", "Pro": "P",
"Ser": "S", "Thr": "T", "Trp": "W", "Tyr": "Y", "Val": "V"}
try:
one_letter = conversion[three_letters]
except KeyError:
logger.warning(module_name=_name,
msg='Could not recognize the following residue symbol: "%s"' % raw)
one_letter = None
return one_letter
def get_distance(a, b):
"""Return the distance between two cartesian tri dimensional points"""
return math.sqrt((a[0] - b[0])**2 +
(a[1] - b[1])**2 +
(a[2] - b[2])**2)
def parse_matrix(filename=''):
"""Parse the matrix input into a dictionary"""
with open(filename, 'r') as fh:
matdict = {}
for line in fh.readlines():
if not line == '\n':
pair = line.strip().split(" ")
matdict[pair[0]] = pair[1]
return matdict
def parse_naccess(pdb_code, work_dir, score_matrix, max_dist):
"""Parse the output of naccess into an object of class Protein"""
with open(os.path.join(work_dir,pdb_code) + ".rsa", "r") as fh:
rsa_dict = {line[3:8].strip() + # resn
line[8] + # chain
line[9:16].strip(): # resi
float(line[22:28].strip()) # rsa
for line in fh.readlines()
if line.startswith('RES')}
my_protein = Protein(pdb_code=pdb_code, residues=[], out_dir=work_dir, max_dist=max_dist)
center_atom = 'CA' # atom to be considered the center of the residue
with open(os.path.join(work_dir,pdb_code) + '.asa', 'r') as fh:
for line in fh.readlines():
# use data only from alpha carbons
if line[12:16].strip() == center_atom:
# extract the data according to the characteristics of the pdb format
my_chain = line[21]
my_resi = line[22:29].strip()
my_resn = line[17:20].strip()
x = float(line[30:38].strip())
y = float(line[38:46].strip())
z = float(line[46:54].strip())
res_id = my_resn + my_chain + my_resi
my_rsa = rsa_dict[res_id]
my_protein.add_residue(Residue(chain=my_chain,
resi=my_resi,
resn=my_resn,
coords=(x, y, z),
rsa=my_rsa,
score_matrix=score_matrix))
return my_protein
def parse_freesasa(pdb_code, work_dir, filename, score_matrix, max_dist):
my_protein = Protein(pdb_code=pdb_code, residues=[], out_dir=work_dir, max_dist=max_dist)
residue_count = 0
central_atom = 'CA' # atom to be considered the center of the residue
with open(os.path.join(work_dir, filename), 'r') as f:
for line in f:
if line.startswith("ATOM "): # this is the same as naccess asa file
if line[12:16].strip() == central_atom:
# extract the data according to the characteristics of the pdb format
my_chain = line[21]
my_resi = line[22:29].strip()
my_resn = line[17:20].strip()
x = float(line[30:38].strip())
y = float(line[38:46].strip())
z = float(line[46:54].strip())
my_protein.add_residue(Residue(chain=my_chain,
resi=my_resi,
resn=my_resn,
coords=(x, y, z),
rsa=0,
score_matrix=score_matrix))
elif line.startswith("RES"): # equivalent to naccess rsa file
this_id = line[8] + get_one_letter(line[3:8].strip()) + line[9:16].strip()
rsa = float(line[22:28].strip())
my_protein.change_res_rsa(res_number=residue_count, res_id=this_id, rsa=rsa)
residue_count += 1
return my_protein
def run(pdb_file='', mat_file='', max_dist='', work_dir='', naccess=False):
score_matrix = parse_matrix(filename=mat_file)
pdb_code = pdb_file.split(".")[0]
if naccess:
my_protein = parse_naccess(pdb_code=pdb_code, work_dir=work_dir,
score_matrix=score_matrix, max_dist=max_dist)
else:
my_protein = parse_freesasa(pdb_code=pdb_code, work_dir=work_dir,
filename="sasa.out", score_matrix=score_matrix, max_dist=max_dist)
my_protein.calc_agg_fin()
my_protein.out_csv()
short_summary = my_protein.short_summary()+"\n"
long_summary = my_protein.long_output()
return short_summary + long_summary | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/aggrescan_3d.py | aggrescan_3d.py |
import os
import shutil
import json
from pkg_resources import resource_filename
from subprocess import Popen, PIPE
from os.path import exists, isdir, join, isfile
import logger
import pdb
from postProcessing import prepare_output
from analysis import aggregation_analysis as analyze
from dynamic_module import run_cabs
from foldx_module import FoldxWrap as fold
from glob import glob
from optparser import save_config_file
from auto_mutation import run_auto_mutation
__all__ = ["Job"]
_name = "runJob"
'''
Note to future self:
The Job atributes are kinda global variables here they
Pdb files fate during simulation is as follows:
original_input.pdb is kept during all the simulation and then renamed as input.pdb
input.pdb is the foldx result at each simulation stage, and is the "current" file
folded.pdb is a product of calculations usually soon renamed to input.pdb
output.pdb is the final product of the simulation
Whole thing is a mess mostly due to how foldx works (which has now improved but this program is still behind on it)
'''
class Job:
def __init__(self, config):
for argName, argValue in config.items():
setattr(self, argName, argValue)
logger.debug(module_name=_name, msg="Setting %s to %s" % (argName, argValue))
self.config = config
if exists(self.work_dir):
if not isdir(self.work_dir):
raise logger.AggrescanError('Selected working directory: %s already exists and is not a directory. '
'Quitting.' % self.work_dir,
module_name=_name,
work_dir_error=True)
if self.overwrite and isfile(join(self.work_dir, "output.pdb")):
raise logger.AggrescanError("The --overwrite options was seen. "
"\nStopping the program to avoid overwriting files "
"(workdir exists and contains output.pdb).",
module_name=_name,
work_dir_error=True)
else:
logger.warning(module_name=_name,
msg='Working directory already exists (possibly overwriting previous results -ow '
'to prevent this behavior)')
else:
try:
os.makedirs(self.work_dir)
except OSError:
raise logger.AggrescanError("Could not create working directory at %s" % self.work_dir,
module_name=_name,
work_dir_error=True)
try:
os.mkdir(self.tmp_dir)
except OSError:
pass
if self.foldx:
self.foldx_handler = fold(foldx_dir=self.foldx, work_dir=self.work_dir,
script_dir=resource_filename("aggrescan", "data"),
skip_minimization=self.subprocess)
save_config_file(config=config, work_dir=self.work_dir)
def run_job(self):
logger.info(module_name=_name, msg='Starting aggrescan3d job on: %s with %s chain(s) selected' %
(self.protein, self.chain or "all"))
logger.info(module_name=_name, msg="Creating pdb object from: %s" % self.protein)
pdbObj = pdb.Pdb(self.protein, output=join(self.work_dir, 'input.pdb'), chain=self.chain)
pdbObj.validate()
pdbObj.savePdbFile(path=join(self.work_dir, "original_input.pdb"))
pdbObj.savePdbFile(path=join(self.tmp_dir, "input.pdb"))
if self.mutate:
if self.foldx:
mutation = self.find_mutations(pdb_obj=pdbObj)
self.foldx_handler.build_mutant(working_dir=self.tmp_dir, mutation_list=mutation)
else:
raise logger.AggrescanError("FoldX required for mutation analysis. To run aggrescan on a mutant without"
" FoldX provide a mutant pdb file and run Aggrescan3D on it.",
module_name=_name)
if self.foldx:
self.foldx_handler.minimize_energy(working_dir=self.tmp_dir)
else:
logger.info(module_name=_name,
msg="FoldX not utilized. Treating input pdb file as it was already optimized.")
pdbObj.savePdbFile(path=join(self.tmp_dir, "folded.pdb"))
if self.dynamic:
os.chdir(self.work_dir)
shutil.move(join(self.tmp_dir, "folded.pdb"), "input.pdb")
run_cabs(config=self.config)
shutil.move(join(self.work_dir, "folded.pdb"), join(self.tmp_dir, "folded.pdb"))
analyze(config=self.config, target="folded.pdb", working_dir=self.tmp_dir, agg_work_dir=self.work_dir)
if self.movie:
self.create_movie()
self.post_processing(work_dir=self.tmp_dir, final=True, model_name="folded")
self.cleanup()
if self.auto_mutation:
self.check_auto_mut(pdb_obj=pdbObj) # This will also modify the auto_mutation excluded part slightly
run_auto_mutation(work_dir=self.work_dir, options=self.auto_mutation,
foldx_loc=self.foldx, distance=self.distance)
def post_processing(self, work_dir="", final=True, model_name="folded"): # TODO remove this function?
prepare_output(work_dir=work_dir, final=final, model_name=model_name)
def find_mutations(self, pdb_obj=None):
chain_numbering = pdb_obj.getChainIdxResname()
t = json.loads(chain_numbering)
to_mutate = []
for row in self.mutate:
oi = str(row['idx'])
on = str(row['oldres'])
nn = str(row['newres'])
ch = str(row['chain'])
found = False
try:
for r in t[ch]:
if r['resname'] == on and r['chain'] == ch \
and r['residx'] == oi:
to_mutate.append(on + ch + oi + nn)
found = True
break
except KeyError:
logger.warning(module_name=_name, msg="Mutation %s likely tried to mutate a chain "
"that doesn't exist." % json.dumps(row))
logger.info(module_name=_name, msg="Available chains: %s" % t.keys())
if not found:
logger.warning(module_name=_name, msg="Could not find the requested mutation: %s" % json.dumps(row))
if len(to_mutate) == 0:
raise logger.AggrescanError("Mutations table provided but its parsing failed. "
"Most likely all the provided mutations were incorrect "
"(referring to non existing residues, numbering errors, etc.)",
module_name=_name)
mutation = ",".join(to_mutate).strip() + ";"
logger.debug(module_name=_name, msg="Mutation list: %s" % mutation)
return mutation
def check_auto_mut(self, pdb_obj=None):
print self.auto_mutation
if len(self.auto_mutation) > 2:
chain_numbering = pdb_obj.getChainIdxResname()
t = json.loads(chain_numbering)
counted = 0
for row in self.auto_mutation[2]:
oi = str(row['idx'])
ch = str(row['chain'])
found = False
try:
for r in t[ch]:
if r['chain'] == ch \
and r['residx'] == oi:
found = True
counted += 1
break
except KeyError:
logger.warning(module_name="Auto_mut", msg="Attempted to exclude a residue that probably"
"doesn't exist. (%s)" % json.dumps(row))
logger.info(module_name="Auto_mut", msg="Available chains: %s" % t.keys())
if not found:
logger.warning(module_name="Auto_mut", msg="Couldn't find the residue number %s in chain %s to exclude from "
"auto mutation" % (oi, ch))
if counted == 0:
logger.critical(msg="Residues to exclude from automated mutations provided but none "
"could be found in the pdb file.",
module_name="Auto_mut")
# Parse it into "mutation syntax" for easier comparisons later on
self.auto_mutation = list(self.auto_mutation)
self.auto_mutation[2] = [i['idx'] + i["chain"] for i in self.auto_mutation[2]]
def cleanup(self):
"""Move output from the temporary directory to work directory before the former is deleted"""
os.chdir(self.tmp_dir)
shutil.move(join(self.tmp_dir, "A3D.csv"), join(self.work_dir, "A3D.csv"))
shutil.move(join(self.tmp_dir, "output.pdb"), join(self.work_dir, "output.pdb"))
shutil.move(join(self.work_dir, "original_input.pdb"), join(self.work_dir, "input.pdb"))
extensions = [".svg", ".png"]
for ext in extensions:
for f in glob("*%s" % ext):
shutil.move(f, join(self.work_dir, f))
def create_movie(self):
"""
First uses paintit.py to create movie frame png, then run avconv to create a movie
This is a legacy function while it should work it's no longer really relevant or updated/tested
"""
os.chdir(self.tmp_dir)
pymCmd = "pymol -qc %s -- s input.pdb input_output ." % resource_filename("aggrescan", join("data", "paintit.py"))
logger.debug(module_name="pyMol", msg="Pymol ran with: %s" % pymCmd)
try:
out,err = Popen(pymCmd,stdout=PIPE,stderr=PIPE,shell=True).communicate()
if err:
logger.critical(module_name="pyMol",
msg="Pymol encountered an error: %s Movie creation failed." % err.strip("\n"))
return
except OSError as e:
logger.debug(module_name="pyMol", msg="Exception caught: %s" % e)
logger.critical(module_name="pyMol", msg="OSError while launching pymol. Perhaps it's not installed?")
return
self.movie = self.movie.strip()
if self.movie == "mp4":
av_cmd = 'avconv -r 8 -i mov%05d.png -vcodec libx264 -pix_fmt yuv420p -profile:v baseline ' \
'-preset slower -crf 18 -vf "scale=trunc(in_w/2)*2:trunc(in_h/2)*2" clip.mp4'
logger.info(module_name="Movie",msg="Creting movie with %s format" % self.movie)
elif self.movie == "webm":
av_cmd = 'avconv -r 8 -i mov%05d.png -c:v libvpx -c:a libvorbis -pix_fmt yuv420p ' \
'-b:v 2M -crf 5 -vf "scale=trunc(in_w/2)*2:trunc(in_h/2)*2" clip.webm'
logger.info(module_name="Movie",msg="Creting movie with %s format" % self.movie)
else:
logger.warning(module_name="Movie",msg="Wrong movie format specified: %s Using webm instead." % self.movie)
av_cmd = 'avconv -r 8 -i mov%05d.png -c:v libvpx -c:a libvorbis -pix_fmt yuv420p ' \
'-b:v 2M -crf 5 -vf "scale=trunc(in_w/2)*2:trunc(in_h/2)*2" clip.webm'
self.movie = "webm"
try:
logger.debug(module_name="Avconv", msg="Avconv ran with: %s" % av_cmd)
out, err = Popen(av_cmd,stdout=PIPE, stderr=PIPE, shell=True).communicate()
if err:
logger.debug(module_name="Avconv",
msg="Avconv output: %s" % err.strip("\n"))
if self.movie == "mp4":
shutil.move("clip.mp4", join(self.work_dir,"clip.mp4"))
else:
shutil.move("clip.webm", join(self.work_dir,"clip.webm"))
except OSError as e:
logger.critical(module_name="Avconv", msg="OSError while launching avconv. Perhaps it's not installed?")
logger.debug(module_name="Avconv", msg="Exception caught: %s" % e)
except IOError as e2:
logger.critical(module_name="Avconv", msg="Couldn't move the clip to working directory. "
"Movie creation likely failed")
logger.debug(module_name="Avconv", msg="Exception caught: %s" % e2)
finally:
file_list = os.listdir(self.tmp_dir)
for f in file_list:
if ".png" in f:
os.remove(f)
def get_tempdir(self):
return self.tmp_dir | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/newRunJob.py | newRunJob.py |
"""Module that handles argument parsing and stores default program options"""
import argparse
from os import getcwd
from os.path import abspath, join, isfile
import json
import re
import logger
from pkg_resources import resource_filename
_name = "AggParser"
_shorts = {
'i': 'protein',
'm': 'mutate',
'd': 'dynamic',
'D': 'distance',
'w': 'work_dir',
'O': 'overwrite',
'v': 'verbose',
'C': 'chain',
'f': 'foldx',
'M': 'movie',
'n': 'naccess',
'o': 'output',
'r': 'remote',
'cabs': "cabs_dir",
'cabs_config': 'cabs_config',
'n_models': 'n_models',
'am': 'auto_mutation'
}
class ExtendAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
items = getattr(namespace, self.dest) or []
items.extend(values)
setattr(namespace, self.dest, items)
def parse(options):
parser = get_parser_object()
read = parser.parse_args(options)
data, mut = [], []
if read.config_file:
data, mut = parse_config_file(read.config_file)
data.extend(options)
read = parser.parse_args(data)
auto_mutation = _parse_auto_mut(read.auto_mutation)
# This is a safety measure in case a path is changed inside the program and the relative would be no longer valid
cabs_config, foldx, naccess = '', '', ''
if read.cabs_config:
cabs_config = abspath(read.cabs_config)
if read.foldx != "argument_not_used" and read.foldx is not None: # Prevent assiging a path to not-used argument
read.foldx = abspath(read.foldx)
if read.naccess:
naccess = abspath(read.naccess)
foldx = _handle_foldx(read.foldx)
work_dir = abspath(read.work_dir)
tmp_dir = join(work_dir, "tmp")
new_mut = _parse_mut(read.mutate)
if new_mut:
mut.extend(new_mut)
# Catch some of the unwanted option combinations here.
if new_mut and auto_mutation:
raise logger.InputError("Both manual and automated mutations selected. Please select just one of those as they are exclusive.")
if auto_mutation and read.dynamic:
raise logger.InputError("Automated mutations are not (yet?) supported with dynamic mode.")
if auto_mutation and not foldx:
raise logger.InputError("Automated mutations require FoldX to work. Please specify a path with -f.")
options = {
'protein': read.protein,
'dynamic': read.dynamic,
'mutate': mut,
'distance': read.distance,
'work_dir': work_dir,
'overwrite': read.overwrite,
'verbose': read.verbose,
'chain': read.chain,
'movie': read.movie,
'naccess': naccess,
"foldx": foldx,
'auto_mutation': auto_mutation,
'remote': read.remote,
"cabs_dir": read.cabs_dir,
"cabs_config": cabs_config,
"n_models": read.n_models,
"tmp_dir": tmp_dir,
"subprocess": read.subprocess
}
return options
def parse_config_file(filename):
parsed = []
option_pattern = re.compile(
r'(?P<option>[^:=]*)'
r'[:=]'
r'(?P<value>.*)$'
)
mutation_pattern = re.compile(r'{+.+\}+')
path = abspath(filename)
logger.debug(module_name=_name, msg="Parsing data from: %s" % path)
to_mutate = []
try:
with open(path, 'r') as f:
for line in f:
if line == '' or line[0] in ';#\n':
continue
elif mutation_pattern.search(line):
try:
mutation = mutation_pattern.findall(line)[0]
mutation = re.sub("\'", "\"", mutation)
to_mutate.append(json.loads(mutation))
except Exception:
logger.critical(module_name=_name,
msg="Error while loading the mutation table in line:\n %s" % line.strip("\n"))
raise logger.InputError("Failed to properly load config file. Quitting.")
elif line.startswith("am") or line.startswith("auto_mutation"): # Special case, this is getting super messy
parsed.append("--auto_mutation")
parsed.append(" ".join(line.split()[1:]))
else:
match = option_pattern.match(line)
if match:
option, value = match.groups()
option = option.strip()
if option in _shorts.values():
if value.strip() != "True":
parsed.append("--"+option)
parsed.append(value.strip())
else:
parsed.append("--"+option)
elif option in _shorts.keys():
if value.strip() != "True":
parsed.append("-"+option)
parsed.append(value.strip())
else:
parsed.append("-"+option)
else:
logger.warning(module_name=_name,
msg="option: %s seen in config file not recognized" % option)
elif line.strip() in _shorts.values():
parsed.append("--"+line.strip())
elif line.strip() in _shorts.keys():
parsed.append("-"+line.strip())
else:
logger.warning(module_name=_name, msg="line: %s couldn't be parsed" % line.strip("\n"))
except IOError:
raise logger.InputError("Could not load the file %s" % path)
return parsed, to_mutate
def save_config_file(config, work_dir):
tmp = ""
for argName, argValue in config.items():
if type(argValue) == list: # This will catch mutations
for mutation in argValue:
tmp += json.dumps(mutation) + "\n" # assuming its a mutation entry, which should be dumps'able
elif type(argValue) == tuple: # This will catch automated mutations, as long as no new tuples/lists are introduced this works
if len(argValue) > 2:
tmp += "%s: %d %d %s\n" % (argName, argValue[0], argValue[1], " ".join([i['idx']+i['chain'] for i in argValue[2]]))
else:
tmp += "%s: %d %d\n" % (argName, argValue[0], argValue[1])
elif argValue and (argName in _shorts.keys() or argName in _shorts.values()):
tmp += "%s : %s\n" % (argName, argValue)
logger.to_file(filename=join(work_dir, "config.ini"), content=tmp)
def get_parser_object():
parser = argparse.ArgumentParser(
description='Aggrescan 3D standalone application. Please read and run configReadme.ini to test if the program works.')
parser.register('action', 'extend', ExtendAction)
parser.add_argument('-c',
'--config_file',
metavar='',
type=str,
help='''Input file with specified config options. One can specify a config file and some additional flags
Command line options have priority over config file.
For further help on creating config files please refer to configReadme.ini''')
parser.add_argument('-i',
'--protein',
metavar='',
type=str,
help='Input pdb code or a path to file on which the simulation is performed')
parser.add_argument('-d',
'--dynamic',
default=False,
action='store_true',
help='Use the dynamic module for the simulation. '
'CABS flex will be used to perform a protein dynamics simulation '
'If CABS is not installed but present in the filesystem use --cabs_dir to provide a path to its location '
'--cabs_config can be used to provide a CABS config file '
'--n_models can be used to decide how many models will be taken into further calculations')
parser.add_argument('-m',
'--mutate',
metavar='',
default='',
type=str,
nargs='+',
action='extend',
help="""Provide a residue mutation. This option can be used multiple times to provide multiple mutations.
The format is: <Old residue><New residue><Residue number><Chain ID>
For example: MW1A to change the first residue of chain A from methionine to tyrosine.
Please note that this option requires FoldX usage.""")
parser.add_argument('-D',
'--distance',
metavar='',
default=10,
type=int,
help='Distance cutoff for naccess calculations. Default: 10')
parser.add_argument('-w',
'--work_dir',
metavar='',
default=getcwd(),
type=str,
help="Sets the directory in which the simulation is performed")
parser.add_argument('--cabs_dir',
metavar='',
default='',
type=str,
help="If used CABS will be run from the provided directory. Should be used when CABS is not installed"
"or one wants to use a specific CABS version for the dynamic simulations")
parser.add_argument('--cabs_config',
metavar='',
default='',
type=str,
help="If used CABS will be run with selected config file. "
"Aggrescan will not parse the config in any way so its up to the user to supply a working config file."
"For debugging purposes use verboisty 3 or higher, "
"CABS simulation log will be then kept, see the CABSlog file for details on what went wrong with the CABS run."
"Few caveats include:"
"CABS work-dir should not be used"
"if --n_models is used it will overwrite --clustering-medoids in the config file specified by this option"
"CABS input option will be overwritten"
"--aa-rebuild and --remote will be specified by default")
parser.add_argument('--n_models',
metavar='',
default=12,
type=int,
help='Sets the number of models CABS will generate in the dynamic analysis.'
'This option will overwrite cabs config file if you chose both options'
' '
)
parser.add_argument('-r',
'--remote',
default=False,
action="store_true",
help='Automatically redirects output to a Aggrescan.log file created in the working directory,'
'turns off log coloring. Piping standard error will not work with this option.'
'If a log file already exists it will be appended to.')
parser.add_argument('-O',
'--overwrite',
default=False,
action='store_true',
help="""If the working directory already exists and contains an output.pdb file
this will stop the program to prevent overwriting possible results that might be there""")
parser.add_argument('-f',
'--foldx',
metavar='',
type=str,
nargs='?',
default="argument_not_used",
help="""The program will attempt to run foldX on the provided pdb file or code
using the path provided in this option. Once the path is provided subsequent runs can
can omit the path and simply use -f (it will be written in program data""")
parser.add_argument('-v',
'--verbose',
metavar='',
default=2,
type=int,
help="""Sets the verbosity of the program
0 for silent mode (only critical messages) and 4 for maximum verbosity.
Verbosity level 3 might raise some Exceptions that would otherwise only be logged as critical messages""")
parser.add_argument('-C',
'--chain',
metavar='',
default='',
type=str,
help="""Only consider a specific chain while performing calculations""")
parser.add_argument('-M',
'--movie',
metavar='',
default='',
type=str,
help="""Create a short movie of the result protein. Available formats: mp4, webm
Usage: -m mp4
Please note pymol and avconv are used and need to be installed for this option to work""")
parser.add_argument('-n',
'--naccess',
metavar="",
default="",
type=str,
help="""Run the simulation with naccess instead of freeSasa.
Run this argument with a path to the naccess program exectuable.""")
parser.add_argument('-am',
'--auto_mutation',
metavar='',
default='is_not_used', # The actual option is in _parse_auto_mut, this is to recognize the argument was NOT used
nargs='?',
type=str,
help="Automatically mutate most aggregation prone residues The option should be formatted as follows: "
"number_of mutations number_of_used_processes [list of residues that are not to be mutated]"
" The list is optional and if no arguments are specified two resides using two threads will be attempted"
"The list should follow the naming convention of <Residue number><Chain ID>"
"For example: '2 2 1A' to mutate 2 residues using 2 processes at once and exclude the first residue of A chain"
" from the mutation candidates. Which will result in 8 mutants (4*2)")
parser.add_argument('--subprocess',
default=False,
action="store_true",
help="""Internal option but can be used by the user - this is used to signal that the run is
actually a subprocess of A3D's auto mutation procedure. Using this option means that no
energy minimization will be perfomed before creating a mutant.""")
return parser
def _parse_auto_mut(argument):
_pattern = re.compile('(?P<id>[0-9]+)'
'(?P<chain>[A-Z])')
if argument == "is_not_used":
return None
elif argument is None: # Happens when option with no arguments is used
return 2, 2
else:
argument = argument.strip()
parsed_argument = argument.split()
if parsed_argument[0] == ":" or parsed_argument[0] == "=": # This can happen in a config file
parsed_argument.pop(0)
if len(parsed_argument) == 1:
parsed_argument += "2" # To add to the default
try:
n_mutations = int(parsed_argument[0])
except ValueError:
raise logger.InputError("Failed to convert the first argument for automated mutations to a number. Expected a number,"
"got %s. Valid input would look like: -am '2 2 1A 2A'. Your input: %s" % (parsed_argument[0], argument))
try:
n_threads = int(parsed_argument[1])
except ValueError:
raise logger.InputError("Failed to convert the second argument for automated mutations to a number. Expected a number,"
"got %s. Valid input would look like: -am '2 2 1A'. Your input: %s" % (parsed_argument[1], argument)
)
if len(parsed_argument) > 2:
excluded_list = []
for item in parsed_argument[2:]:
try:
parse = _pattern.match(item).groups()
excluded_list.append({
'idx': parse[0],
'chain': parse[1]
})
except AttributeError:
raise logger.InputError(
"Failed to parse excluded residues for aumated mutations. Residues should be provided in a "
"<Residue ID><Chain> format i.e. 1A 2B etc. Failed item: %s. Whole input for the option: %s" % (item, argument))
return n_mutations, n_threads, excluded_list
else:
return n_mutations, n_threads
def _parse_mut(mutation_list):
p = re.compile('(?P<oldres>[A-Z])'
'(?P<newres>[A-Z])'
'(?P<id>[0-9]+)'
'(?P<chain>[A-Z])')
out_list = []
for mutation in mutation_list:
try:
parsed = p.match(mutation).groups()
out_list.append({'oldres': parsed[0],
'newres': parsed[1],
'idx': parsed[2],
'chain': parsed[3]
})
except AttributeError:
raise logger.InputError(
"Your mutation %s was provided in wrong format. " % mutation +
"Correct formatting is <Oldres><Newres><ID><chain>. "
"For example MW1A. Mind the capital letters. ")
return out_list
def _handle_foldx(user_input):
"""
Either save the provdied FoldX path to a file or try to read the path from the file.
If the user sepcified -f with no argument the user_input is None
if the user never used the -f the user_input is default ("")
"""
if user_input == "argument_not_used": # The option was never selected
return ""
if user_input is not None: # A path is actually provided
try:
with open(join(resource_filename("aggrescan", "data"), "foldx_dir.txt"), 'w') as f:
f.write(user_input)
except IOError as e:
if "Permission denied" in str(e):
try:
with open(join(resource_filename("aggrescan", "data"), "foldx_dir.txt"), 'r') as f:
user_input = f.read().strip()
except IOError:
raise logger.InputError(
"--foldx option used but no path has been specified. If you've never used the option "
"you need to privde a path to FoldX directory. It can be ommited in subsequent runs "
"as it will be saved in program's data")
else:
if not isfile(join(resource_filename("aggrescan", "data"), "foldx_dir.txt")):
raise logger.InputError("--foldx option used but no path has been specified. If you've never used the option "
"you need to privde a path to FoldX directory. It can be ommited in subsequent runs "
"as it will be saved in program's data")
with open(join(resource_filename("aggrescan", "data"), "foldx_dir.txt"), 'r') as f:
user_input = f.read().strip()
return user_input | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/optparser.py | optparser.py |
import os
from os.path import join, abspath
from subprocess import PIPE, Popen
from pkg_resources import resource_filename
from aggrescan_3d import run as run_aggrescan_3d
import logger
import platform
_name = "Analysis"
if platform.system() == "Windows":
_bin_name = "freesasa.exe"
elif platform.system() == "Darwin":
_bin_name = "freesasa_Darwin"
else:
_bin_name = "freesasa"
def aggregation_analysis(config, target="input.pdb", working_dir=".", agg_work_dir=""):
"""Takes Aggrescaan3D Job class config as an argument and should never change it"""
os.chdir(working_dir) # Just in case one of the programs handles abspaths poorly
if config["naccess"]:
_run_naccess(target=target, agg=agg_work_dir, naccess_dir=config["naccess"])
else:
_run_free_sasa(target=target, agg=agg_work_dir)
_run_aggrescan(target=target, working_dir=working_dir, config=config)
def _run_aggrescan(target, working_dir, config):
"""
Takes target pdb file, working directory for analysis
and aggrescan config dict as arguments so need the two in sync
"""
logger.info(module_name=_name, msg="Starting Aggrescan3D on %s" % target.split("/")[-1])
logger.debug(module_name=_name, msg="Running Aggrescan3D program on %s" % abspath(target))
matrix_dir = resource_filename('aggrescan', join("data", "matrices", "aggrescan.mat"))
out = run_aggrescan_3d(target, matrix_dir, config["distance"], working_dir, naccess=config["naccess"])
logger.to_file(filename=join(config["tmp_dir"], "input_output"), content=out, allow_err=False)
def _run_free_sasa(target="folded.pdb", agg=""):
sasa_dir = resource_filename('aggrescan', join("data", "freesasa-2.0.1", "src", _bin_name))
sasa_cmd = [sasa_dir, "--resolution", "100", target, "--radii", "naccess", "--format", "pdb", "--format", "rsa"]
logger.debug(module_name="freeSasa", msg="Starting freeSasa with %s" % " ".join(sasa_cmd))
_fname = join(agg, "ASA.error")
out, err = Popen(sasa_cmd, stdout=PIPE, stderr=PIPE).communicate()
if err:
logger.to_file(_fname, content=err)
for line in err.split("\n"):
if "warning" in line:
logger.critical(module_name="freeSasa", msg="Warning detected: %s" % line)
logger.critical(module_name="freeSasa", msg="Attempting to continue.")
else:
raise logger.ASAError(program_name="freeSasa", filename=_fname)
logger.to_file(filename="sasa.out", content=out, allow_err=False)
def _run_naccess(target="folded.pdb", agg="", naccess_dir=""):
naccess_cmd = [naccess_dir, target, "-p", "1.4", "-z", "0.05"]
logger.debug(module_name=_name, msg="running naccess program with %s" % " ".join(naccess_cmd))
_fname = join(agg, "ASA.error")
try:
out, err = Popen(naccess_cmd, stdout=PIPE, stderr=PIPE).communicate()
except OSError:
raise logger.AggrescanError("Couldn't start the naccess program. Naccess requires csh shell to be present on the system."
" If it is present please run the program in debug mode and see if the path printed in "
"Naccess command actually contains the file.", module_name="Naccess")
if err:
logger.to_file(filename=_fname, content=err)
raise logger.ASAError(program_name="Naccess", filename=_fname)
try:
for msg in out.split("\n"):
if msg:
logger.debug(module_name="Naccess", msg=msg)
except AttributeError:
pass | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/analysis.py | analysis.py |
import os
import logger
import re
import gzip
from urllib2 import urlopen, HTTPError, URLError
from StringIO import StringIO
import json
_name = "PDB"
class Pdb:
"""
Pdb parser. Initialized by:
1. pdb filename
2. gzipped pdb filename
3. 4-letter pdb code
"""
def __init__(self,*args, **kwargs):
self.file_name = None
self.pdb_code = None
self.dir = os.getcwd()
self.loc = os.path.join(self.dir, "input_pdb")
self.codification = {"ALA" : 'A', "CYS" : 'C', "ASP" : 'D', "GLU" : 'E', "PHE" : 'F', "GLY" : 'G', "HIS" : 'H',
"ILE" : 'I', "LYS" : 'K', "LEU" : 'L', "MET" : 'M', "MSE" : 'M', "ASN" : 'N', "PYL" : 'O',
"PRO" : 'P', "GLN" : 'Q', "ARG" : 'R', "SER" : 'S', "THR" : 'T', "SEC" : 'U', "VAL" : 'V',
"TRP" : 'W', "5HP" : 'E', "ABA" : 'A', "AIB" : 'A', "BMT" : 'T', "CEA" : 'C', "CGU" : 'E',
"CME" : 'C', "CRO" : 'X', "CSD" : 'C', "CSO" : 'C', "CSS" : 'C', "CSW" : 'C', "CSX" : 'C',
"CXM" : 'M', "DAL" : 'A', "DAR" : 'R', "DCY" : 'C', "DGL" : 'E', "DGN" : 'Q', "DHI" : 'H',
"DIL" : 'I', "DIV" : 'V', "DLE" : 'L', "DLY" : 'K', "DPN" : 'F', "DPR" : 'P', "DSG" : 'N',
"DSN" : 'S', "DSP" : 'D', "DTH" : 'T', "DTR" : 'X', "DTY" : 'Y', "DVA" : 'V', "FME" : 'M',
"HYP" : 'P', "KCX" : 'K', "LLP" : 'K', "MLE" : 'L', "MVA" : 'V', "NLE" : 'L', "OCS" : 'C',
"ORN" : 'A', "PCA" : 'E', "PTR" : 'Y', "SAR" : 'G', "SEP" : 'S', "STY" : 'Y', "TPO" : 'T',
"TPQ" : 'F', "TYS" : 'Y', "TYR" : 'Y' }
keys = self.codification.keys()
self.sequences = {}
self.onlycalfa = ""
self.allatoms = ""
self.chain = ""
self.canumber = 0
self.allnumber = 0
if args and len(args) == 1:
if args[0] is None: raise logger.AggrescanError("No pdb code/file provided. Quitting.",
module_name=_name)
if os.path.isfile(args[0]):
self.file_name = args[0]
else:
self.pdb_code = args[0]
if kwargs:
self.loc = kwargs['output']
try:
self.chain = kwargs['chain']
except KeyError:
pass
if self.file_name:
try:
self.handler = gzip.GzipFile(filename=self.file_name)
self.data = self.handler.readlines()
logger.debug(module_name=_name, msg="Reading %s" % os.path.abspath(self.file_name))
except IOError:
try:
self.handler = open(self.file_name)
self.data = self.handler.readlines()
logger.debug(module_name=_name, msg="Reading %s" % os.path.abspath(self.file_name))
except IOError:
raise logger.AggrescanError("Couldnt open specified filename %s. Quitting.' % os.path.abspath(self.file_name)",
module_name=_name)
elif self.pdb_code:
self.handler = self.download_pdb()
self.data = self.handler.readlines()
seq = re.compile(r"^ATOM.{9}CA..(?P<seqid>.{3}).(?P<chain>.{1})(?P<resid>.{4})") # TODO zle dla alternatywnych
if self.chain != '':
atm = re.compile(r"^ATOM.{9}(.{2}).( |A).{4}" + self.chain + "(?P<resid>.{4})(?P<x>.{12})(?P<y>.{8})(?P<z>.{8})")
else:
atm = re.compile(r"^ATOM.{9}(.{2}).( |A).{5}(?P<resid>.{4})(?P<x>.{12})(?P<y>.{8})(?P<z>.{8})")
ter = re.compile(r'^END|^TER')
mod = re.compile(r"^ENDMDL")
self.trajectory = []
self.sequence = ""
lines = self.data
end = len(lines) - 1
counter = 0
self._chainsOrder(lines)
self._resIndexes(lines)
self.mutatedata = {}
for line in lines:
line = re.sub(r'^HETATM(.{11})MSE(.*$)', r'ATOM \1MET\2', line)
localData = atm.match(line)
data_seq = seq.match(line)
if data_seq:
seqid = data_seq.groups()[0].strip()
chainid = data_seq.groups()[1].strip()
resid = data_seq.groups()[2].strip()
if seqid in keys:
s = self.codification[seqid]
else:
s = "X"
self.sequence += s
# add to mutate page
if chainid in self.mutatedata.keys():
self.mutatedata[chainid].append({'chain': chainid,
'resname': s,
'residx': resid})
else:
self.mutatedata[chainid] = [{'chain': chainid,
'resname': s,
'residx': resid}]
if chainid in self.sequences.keys():
self.sequences[chainid] += s
else:
self.sequences[chainid] = s
if localData:
self.allnumber += 1
self.allatoms += line
dg = localData.groups()
if dg[0] == 'CA':
self.onlycalfa += line
self.canumber += 1
if counter == end:
self.onlycalfa += line
self.allatoms += line
if ter.match(line):
if self.chain:
if line[21] == self.chain:
self.onlycalfa += line
self.allatoms += line
else:
self.onlycalfa += line
self.allatoms += line
if (mod.match(line) and len(self.onlycalfa) > 1) or counter == end:
break
counter += 1
self.handler.close()
def _resIndexes(self, body):
atm = re.compile(r"^ATOM.{9}CA..(?P<seqid>.{3}).(?P<chain>.{1})(?P<resid>.{4})")
ter = re.compile(r'^END|^TER')
mod = re.compile(r"^ENDMDL")
self.numb = {}
for chain in self.chains_order:
self.numb[chain] = []
for line in body:
d = atm.match(line)
if d:
self.numb[d.group('chain').strip()].append(int(d.group('resid')))
if mod.match(line):
break
def _chainsOrder(self, body):
atm = re.compile(r"^ATOM.{9}CA..(?P<seqid>.{3}).(?P<chain>.{1})(?P<resid>.{4})")
self.chains_order = []
for line in body:
d = atm.match(line)
if d and d.group('chain') not in self.chains_order:
self.chains_order.append(d.group('chain'))
def isSingleChain(self):
if self.chain != '' or len(self.sequences.keys()) == 1:
return True
else:
return False
def containsOnlyCA(self):
if self.allnumber == self.canumber:
return True
else:
return False
def isBroken(self):
brk = []
if self.chain != '':
indexes = self.numb[self.chain]
first = indexes[0]
for i in range(1, len(indexes)):
if indexes[i] - 1 != first:
brk.append(str(first) + "-" + str(indexes[i]))
first = indexes[i]
else:
for chain in self.sequences.keys():
indexes = self.numb[chain]
first = indexes[0]
for i in range(1, len(indexes)):
if indexes[i] - 1 != first:
brk.append(str(first) + "-" + str(indexes[i]))
first = indexes[i]
if len(brk) > 0:
return ", ".join(brk)
return False
def getResIndexes(self):
t = [str(i) for i in self.numb[self.chain]]
return ",".join(t)
def getBody(self):
return self.allatoms
def containsChain(self, chain):
if chain in self.sequences.keys():
return True
def getSequenceNoHTML(self):
if self.chain != '':
return self.sequences[self.chain]
else:
out = ""
for k in self.sequences.keys():
out += "".join(self.sequences[k])
return out
def getSequence(self):
if self.chain != '':
return "<strong>" + self.chain + "</strong>: " + self.sequences[self.chain]
else:
out = ""
for k in self.sequences.keys():
out += "<strong>" + k + "</strong>: "
out += "".join(self.sequences[k])
out += "<br>"
return out
def getChainIdxResname(self):
if self.chain == '':
return json.dumps(self.mutatedata)
else:
return json.dumps({self.chain: self.mutatedata[self.chain]})
def savePdbFile(self,path=''):
if path:
logger.to_file(filename=path, content=self.allatoms, allow_err=True)
else:
logger.to_file(filename=self.loc, content=self.allatoms, allow_err=True)
def getPath(self):
if os.path.isfile(self.loc):
return self.loc
else:
raise logger.AggrescanError("Location for pdb file requested at: %s. The file was not found." % self.loc,
module_name=_name)
def download_pdb(self):
try:
gz_string = urlopen('http://www.rcsb.org/pdb/files/' + self.pdb_code.lower() + '.pdb.gz').read()
except HTTPError as e:
raise logger.AggrescanError("Could not download the pdb file. %s is not a valid pdb code/file. " % self.pdb_code,
module_name=_name)
except URLError as e:
raise logger.AggrescanError("Could not download the pdb file. Can't connect to the PDB database - quitting",
module_name=_name)
fileLike = StringIO(gz_string)
logger.debug(module_name=_name, msg="Successfully downloaded %s" % self.pdb_code.lower() + '.pdb.gz')
return gzip.GzipFile(fileobj=fileLike,mode="rb")
def validate(self):
logger.debug(module_name=_name,msg='Validating pdb file: %s' % self.loc)
if self.chain != '' and not self.containsChain(self.chain):
raise logger.AggrescanError("Selected chain: %s not found in the pdb file. Quitting." % self.chain,
module_name=_name)
seq = self.getSequence()
seq = re.sub("<strong>\w+</strong>:", "", seq)
seq = re.sub("<br>", "", seq)
seq = seq.replace(" ", "")
allowed_seq = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'Y']
if len(seq) < 4:
raise logger.AggrescanError("Sequence too short (perhaps something went wrong with pdb parsing).",
module_name=_name)
for e in seq:
if e not in allowed_seq:
raise logger.AggrescanError("Not supported amino acid: %s found in pdb file. Quitting." % e,
module_name=_name)
if __name__ == '__main__':
pass | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/pdb.py | pdb.py |
import multiprocessing as mp
from subprocess import Popen, PIPE
from collections import OrderedDict
from os.path import join, isfile
from postProcessing import make_auto_mut_plot
import os
import re
import shutil
import logger
_name = "Auto_mut"
# Define some variables that dictate how some properties of this - maybe they get to be parameters in the future
_score_threshold = -0.2 # How high an A3D score has to be for the residue to be considered for mutation
_energy_threshold = 0.0 # When a mutation is considered "good"
_score_diff_threshold = 5 # When a mutation is considered to increase solubility +5 should accept all while 0 would
# already be qutite restrictive
_target_mutations = ["E", "K", "D", "R"] # Glutamic acid, lysine, aspartic acid, arginine
# The slicing in this code can be hard to read so here is a short summary:
# Chain ID and residue names come as one letter shorts while the number can have more than one char
# Final mutation code is <Old residue><New residue><Residue number><Chain ID>
# The auto_mutation to_exclude argument comes as <Residue number><Chain ID>
# The one that comes from A3D file comes as < Old residue><Residue number><Chain ID>
def run_auto_mutation(work_dir, options, foldx_loc, distance):
n_mutations = options[0]
n_processes = options[1]
to_exclude = [] # Not to worry about it even exists
if len(options) > 2:
to_exclude = options[2]
pool = mp.Pool(n_processes)
mutations, avg_score = _mutation_list(work_dir=work_dir, excluded_list=to_exclude, n_mutations=n_mutations)
if not mutations:
with open(join(work_dir, "Mutations_summary.csv"), "w") as f: # leave an empty file for the server
pass
return
pool.map(_run_job, [(i, foldx_loc, work_dir, str(distance)) for i in mutations])
_analyze_results(work_dir=work_dir, output_file="Mutations_summary.csv", mutation_list=mutations,
base_avg_score=avg_score)
_cleanup(work_dir=work_dir, mutation_list=mutations)
try:
_plots(work_dir=work_dir)
except Exception as e: # This is hopefully not needed but in case something happens the user will at least see a
# message rather than a traceback
logger.critical(module_name=_name, msg="It seems that all the mutation attempts failed or some other unexpected"
" error arisen while trying to plot the automated mutations.")
raise
def _mutation_list(work_dir, excluded_list, n_mutations):
scores = _parse_a3dcsv(os.path.join(work_dir, "A3D.csv"))
avg_score = sum(scores.values())/len(scores.values())
mutation_list = []
counter = 0
for residue, value in scores.items():
if value > _score_threshold and residue[1:] not in excluded_list and residue[0] not in _target_mutations \
and value != 0:
mutation_list.extend(["%s%s%s" % (residue[0], i, residue[1:]) for i in _target_mutations])
logger.info(module_name=_name, msg="Residue number %s from chain %s and a score of %.3f (%s) selected "
"for automated muatation" % (residue[1:-1], residue[-1], value,
_aa_dict_F[residue[0]]))
counter += 1
if counter >= n_mutations:
break
elif value > _score_threshold and residue[1:] in excluded_list:
logger.info(module_name=_name, msg="Residue number %s from chain %s and a score of %.3f omitted "
"from automated muatation (excluded by the user)." % (residue[1:-1], residue[-1], value))
if not mutation_list:
logger.critical(module_name=_name, msg="Couldn't find residues suitable for automated mutations (exceeding a "
"threshold of %.2f). No automated mutations performed." % _score_threshold)
return mutation_list, avg_score
def _parse_a3dcsv(filepath): #TODO this is done on muttiple occasions so maybe should be unified somwhere
"""
Return an OrderedDict of label:score type. The dict is sorted by score so highest is on top
"""
pattern = re.compile(r"^(.*),(.*),(.*),(.*),(.*)$", re.M)
scores = OrderedDict()
try:
with open(filepath, 'r') as f:
data = pattern.findall(f.read().replace("\r", ""))[1:] #
except IOError:
return False # The mutation likely failed this should pass the info to analyze_results
for line in data:
label = line[3] + line[2] + line[1] # One letter code + residue ID + chain ID (the mutation syntax)
aggScore = float(line[4])
scores[label] = aggScore
scores = OrderedDict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
return scores
def _run_job(args):
"""
Run a single A3D job with a specific mutation
args go as follows: mutation code, FoldX location, main job's work dir, a3d distance argument
"""
mutation, foldx, work_dir, distance = args
os.chdir(work_dir)
cmd = ["aggrescan", "-i", "output.pdb", "-v", "4", "-w", mutation, "-m", mutation, "-f", foldx,
"--subprocess", "--distance", distance]
logger.info(module_name=_name, msg="Mutating residue number %s from chain %s (%s) into %s "
" " % (mutation[2:-1], mutation[-1], _aa_dict_F[mutation[0]],
_aa_dict_F[mutation[1]])) # converting letters into full names
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
proc.communicate()
if proc.returncode != 0:
logger.warning(module_name=_name, msg="Mutation %s could have failed (this can be ignored if the main program "
"reports the energy difference). Simulation log for that run should be "
"available at %s" % (mutation,
os.path.join(work_dir, mutation, "Aggrescan.error")))
def _analyze_results(work_dir, output_file, mutation_list, base_avg_score):
"""
Analyze the results and select all of those that are not relevant on keeping top X mutations and return the rest
to the cleaner that will get rid of them, but keeping their scores in the output_file
"""
data = OrderedDict()
unnecessary_results = []
for mutation in mutation_list:
scores = _parse_a3dcsv(os.path.join(work_dir, mutation, "A3D.csv"))
if not scores:
continue
with open(os.path.join(work_dir, mutation, "MutantEnergyDiff"), 'r') as f:
mutation_energy = float(f.read().split()[0]) # This should be guaranteed to work given the check above
avg_score = sum(scores.values())/len(scores.values())
data[mutation] = [mutation_energy, avg_score, avg_score - base_avg_score]
if mutation_energy > _energy_threshold or avg_score - base_avg_score > _score_diff_threshold:
unnecessary_results.append(mutation)
logger.info(module_name=_name, msg="Effect of mutation residue number %s from chain %s (%s) into %s: "
"Energy difference: %.4f kcal/mol, Difference in average score from the "
"base case: %.4f"
"" % (mutation[2:-1], mutation[-1], _aa_dict_F[mutation[0]],
_aa_dict_F[mutation[1]], mutation_energy, avg_score - base_avg_score))
data = OrderedDict(sorted(data.items(), key=lambda x: x[1][0])) # sort by mutation energy
with open(os.path.join(work_dir, output_file), "w") as f:
f.write("%s,%s,%s,%s\n" % ("Mutation", "EnergyDiff", "AvgScore", "AvgScoreDiff"))
for mutation, values in data.items():
f.write("%s,%.4f,%.4f,%.4f\n" % (mutation, values[0], values[1], values[2]))
return unnecessary_results
def _cleanup(work_dir, mutation_list):
for mutation in mutation_list:
if isfile(join(work_dir, mutation, "A3D.csv")) and isfile(join(work_dir, mutation, "output.pdb")):
shutil.move(join(work_dir, mutation, "A3D.csv"), join(work_dir, "%s%s" % (mutation, ".csv")))
shutil.move(join(work_dir, mutation, "output.pdb"), join(work_dir, "%s%s" % (mutation, ".pdb")))
shutil.rmtree(join(work_dir, mutation))
else:
if isfile(join(work_dir, mutation, "Aggrescan.error")):
shutil.move(join(work_dir, mutation, "Aggrescan.error"), join(work_dir, "%s%s" % (mutation, ".error")))
shutil.rmtree(join(work_dir, mutation))
else:
with open(join(work_dir, "%s%s" %(mutation, ".error")), "w") as f:
f.write("The mutation has failed and no error log was created during the simulation. "
"This is unexpected and if you require further assistance please contact us or leave a bug "
"report on our bitbucket at "
"https://bitbucket.org/lcbio/aggrescan3d/issues?status=new&status=open")
def _plots(work_dir):
make_auto_mut_plot(work_dir)
# This is a copy from somewhere else, maybe should put it somewhere for imports
_aa_dict_F = {'A': 'alanine', 'R': 'arginine', 'N': 'asparagine',
'D': 'aspartic acid', 'C': 'cysteine', 'E': 'glutamic acid',
'Q': 'glutamine', 'G': 'glycine', 'H': 'histidine',
'I': 'isoleucine', 'L': 'leucine', 'K': 'lysine',
'M': 'methionine', 'F': 'phenylalanine', 'P': 'proline',
'S': 'serine', 'T': 'threonine', 'W': 'tryptophan',
'Y': 'tyrosine', 'V': 'valine', 'X': 'unknown'} | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/auto_mutation.py | auto_mutation.py |
import sys
import pymol
from pymol import cmd, stored, util
pymol_mode = sys.argv[1]
pdb_file = sys.argv[2]
output_file = sys.argv[3]
try:
pdb_code = pdb_file.split('/')[1].split('.')[0]
except IndexError:
pdb_code = pdb_file.split('.')[0]
if pymol_mode == "s":
pymol.pymol_argv = ['pymol','-qc'] # PyMol quiet launch without GUI
out_folder = sys.argv[4]
fh = open(output_file, "r")
lines = fh.readlines()
pymol.finish_launching()
cmd.load(pdb_file)
#cmd.remove("HET")
cmd.set_name(pdb_code, pdb_code+'_A3D')
cmd.hide("all")
cmd.show("surface", "all")
cmd.color("white", "all")
#define the reds
cmd.set_color( "red1", [1, 0, 0 ] ) # most intense red
cmd.set_color( "red2", [1, 0.2, 0.2] )
cmd.set_color( "red3", [1, 0.4, 0.4] )
cmd.set_color( "red4", [1, 0.6, 0.6] )
cmd.set_color( "red5", [1, 0.8, 0.8] ) # lightest red
#define the blues
cmd.set_color( "blue1", [0, 0, 1] ) # most intense blue
cmd.set_color( "blue2", [0.2, 0.2, 1] )
cmd.set_color( "blue3", [0.4, 0.4, 1] )
cmd.set_color( "blue4", [0.6, 0.6, 1] )
cmd.set_color( "blue5", [0.8, 0.8, 1] ) # lightest blue
high_score=0
high_res = -1500100900
for line in lines[1:]:
if not (line == "\n" or line.startswith('#')):
line_params = line.strip().replace('//', '').split(" ")
score = float(line_params[3])
chain = line_params[0]
if chain == '-':
my_res = "resi " + line_params[1]
else:
my_res = "chain " + line_params[0] + " and resi " + line_params[1]
if score > 0: # residues with a value above 0 will be colored red
if score < 0.5:
cmd.color("red4", my_res)
elif score < 1:
cmd.color("red3", my_res)
elif score < 1.5:
cmd.color("red2", my_res)
else:
cmd.color("red1", my_res)
if score > high_score:
high_score = score
high_res = my_res
elif score < -0.5: # residues with a value below -0.5 will be colored blue
if score > -1:
cmd.color("blue5", my_res)
elif score > -1.5:
cmd.color("blue4", my_res)
elif score > -2:
cmd.color("blue3", my_res)
elif score > -2.5:
cmd.color("blue2", my_res)
else:
cmd.color("blue1", my_res)
# create an object for the high score hot spot of the protein
if high_res != -1500100900:
cmd.create("hot_spot", "("+high_res+",byres "+high_res+" around 5 and not HET \
and not color white and not color blue1 and not color blue2 and not color blue3 \
and not color blue4 and not color blue5)")
stored.neighbours=[]
cmd.iterate("(hot_spot & n. ca)","stored.neighbours.append((resi,resn))")
cmd.reset()
# Save PyMol session
if pymol_mode == "s":
cmd.viewport("640","480")
cmd.origin()
cmd.set("field_of_view",30)
cmd.set("surface_quality", "1")
cmd.set("ray_trace_mode", "1")
cmd.bg_color("white")
cmd.set("antialias", "2")
for xx in range(1,19):
cmd.rotate("y",20)
cmd.ray("640","480")
cmd.png("mov%05d.png" %(xx))
cmd.quit() | Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/data/paintit.py | paintit.py |
FreeSASA
========
[](https://zenodo.org/badge/latestdoi/18467/mittinatten/freesasa)
[](https://travis-ci.org/mittinatten/freesasa)
[](https://coveralls.io/github/mittinatten/freesasa?branch=master)
C-library for calculating Solvent Accessible Surface Areas.
License: MIT (see file LICENSE). Copyright: Simon Mitternacht 2013-2016.
FreeSASA is a C library and command line tool for calculating Solvent
Accessible Surface Area (SASA) of biomolecules. It is designed to be
simple to use with defaults, but allows customization of all
parameters of the calculation and provides a few different tools to
analyze the results. Python bindings are also included in the
repository.
By default Lee & Richards' algorithm is used, but Shrake & Rupley's is
also available. Both can be parameterized to arbitrary precision, and
for high resolution versions of the algorithms, the calculations give
identical results.
FreeSASA assigns a radius and a class to each atom. The atomic radii
are by default the _ProtOr_ radii defined by Tsai et
al. ([JMB 1999, 290: 253](http://www.ncbi.nlm.nih.gov/pubmed/10388571))
for standard amino acids and nucleic acids, and the van der Waals
radius of the element for other atoms. Each atom is also classified as
either polar or apolar.
Users can provide their own atomic radii and classifications via
configuration files. The input format for configuration files is
described in the
[online documentation](http://freesasa.github.io/doxygen/Config-file.html),
and the `share/` directory contains some sample configurations,
including one for the NACCESS parameters
([Hubbard & Thornton 1993](http://www.bioinf.manchester.ac.uk/naccess/)).
Version 2.0 adds some new features and breaks a few parts of the
interface from 1.x (mainly the API), see CHANGELOG.md for detailed
information.
Building and installing
------------------------
FreeSASA can be compiled and installed using the following
./configure
make && make install
NB: If the source is downloaded from the git repository the
configure-script needs to be set up first using `autoreconf -i`. Users
who don't have autotools installed, can download a tarball that
includes the autogenerated scripts from http://freesasa.github.io/ or
from the latest
[GitHub-release](https://github.com/mittinatten/freesasa/releases).
The above commands build and install the command line tool `freesasa`
(built in `src/`), the command
freesasa -h
gives an overview of options. To run a calculation from PDB-file input
using the defaults, simply type
freesasa <pdb-file>
In addition, `make install` installs the header `freesasa.h` and the
library `libfreesasa`. If the configure script is called with the
option `--enable-python-bindings`, the Python module is also built and
installed.
The configuration can be changed with these options:
* `--enable-python-bindings` builds Python bindings, requires Cython
0.21 or higher. On some platforms the C library needs to be
compiled with `CFLAGS=-fPIC` to allow it to be linked to the
Python module.
* `--with-python=<python>` specifies which python binary to use
* `--disable-json` build without support for JSON output.
* `--disable-xml` build without support for XML output.
* `--disable-threads` build without multithreaded calculations
* `--enable-doxygen` activates building of Doxygen documentation
For developers:
* `--enable-check` enables unit-testing using the Check framework
* `--enable-gcov` adds compiler flags for measuring coverage of tests
using gcov
* `--enable-parser-generator` rebuild parser/lexer source from
Flex/Bison sources (the autogenerated code is included in the
repository, so no need to do this if you are not going to change
the parser).
Documentation
-------------
Enabling Doxygen builds a [full reference
manual](http://freesasa.github.io/doxygen/), documenting both CLI and
API in the folder `doc/html/doxygen/`, also available on the web at
http://freesasa.github.io/.
After building the package, calling
freesasa -h
explains how the commandline tool can be used.
Compatibility and dependencies
------------------------------
The program has been tested successfully with several versions of GNU
C Compiler and Clang/LLVM. The library can be built using only
standard C and GNU libraries. The standard build depends on
[json-c](https://github.com/json-c/json-c) and
[libxml2](http://xmlsoft.org/). These can be disabled by configuring
with `--disable-json` and `--disable-xml` respectively.
Developers who want to do testing need to install the Check unit
testing framework. Building the full reference manual requires Doxygen
(version > 1.8.8). Building the Python bindings requires
Cython. Changing the selection parser and lexer requires Flex and
Bison. These build options, which add extra dependencies, are disabled
by default to simplify installation for users only interested in the
command line tool and and/or C Library.
Citing FreeSASA
---------------
FreeSASA can be cited using the following publication
* Simon Mitternacht (2016) FreeSASA: An open source C library for
solvent accessible surface area calculations. _F1000Research_
5:189. (doi:
[10.12688/f1000research.7931.1](http://dx.doi.org/10.12688/f1000research.7931.1))
The [DOI numbers from Zenodo](https://zenodo.org/badge/latestdoi/18467/mittinatten/freesasa)
can be used to cite a specific version of FreeSASA.
| Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/data/freesasa-2.0.1/README.md | README.md |
FreeSASA
========
These pages document the
- @ref CLI
- @ref API "FreeSASA C API"
- @ref Python "FreeSASA Python interface"
- @ref Config-file
- @ref Selection
- @ref Geometry
The library is released under the [MIT license](license.md).
Installation instructions can be found in the [README](README.md) file.
@page CLI Command-line Interface
Building FreeSASA creates the binary `freesasa`, which is installed by
`make install`. Calling
$ freesasa -h
displays a help message listing all options. The following text
explains how to use most of them.
@section CLI-Default Run using defaults
In the following we will use the RNA/protein complex PDB structure
3WBM as an example. It has four protein chains A, B, C and D, and two
RNA strands X and Y. To run a simple SASA calculation using default
parameters, simply type:
$ freesasa 3wbm.pdb
This generates the following output
## FreeSASA 2.0 ##
PARAMETERS
algorithm : Lee & Richards
probe-radius : 1.400
threads : 2
slices : 20
INPUT
source : 3wbm.pdb
chains : ABCDXY
atoms : 3714
RESULTS (A^2)
Total : 25190.77
Apolar : 11552.38
Polar : 13638.39
CHAIN A : 3785.49
CHAIN B : 4342.33
CHAIN C : 3961.12
CHAIN D : 4904.30
CHAIN X : 4156.46
CHAIN Y : 4041.08
The results are all in the unit Ångström-squared.
@section parameters Changing parameters
If higher precision is needed, the command
$ freesasa -n 100 3wbm.pdb
specifies that the calculation should use 100 slices per atom instead of
the default 20. The command
$ freesasa --shrake-rupley -n 200 --probe-radius 1.2 --n-threads 4 3wbm.pdb
instead calculates the SASA using Shrake & Rupley's algorithm with 200
test points, a probe radius of 1.2 Å, using 4 parallel threads to
speed things up.
If the user wants to use their own atomic radii the command
$ freesasa --config-file <file> 3wbm.pdb
Reads a configuration from a file and uses it to assign atomic
radii. The program will halt if it encounters atoms in the PDB input
that are not present in the configuration. See @ref Config-file for
instructions how to write a configuration.
To use the atomic radii from NACCESS call
$ freesasa --radii=naccess 3wbm.pdb
Another way to specify a custom set of atomic radii is to store them as
occupancies in the input PDB file
$ freesasa --radius-from-occupancy 3wbm.pdb
This option allows the user to first use the option `--format=pdb` (see @ref CLI-PDB) to
write generate a PDB file with the radii used in the calculation,
modify the radii of individual atoms in that file, and then recalculate
the SASA with these modified radii.
@section Output Output formats
In addition to the standard output format above FreeSASA can export
the results as @ref CLI-JSON, @ref CLI-XML, @ref CLI-PDB, @ref
CLI-RSA, @ref CLI-RES and @ref CLI-SEQ using the option
`--format`. The level of detail of JSON and XML output can be
controlled with the option `--output-depth=<depth>` which takes the
values `atom`, `residue`, `chain` and `structure`. If `atom` is
chosen, SASA values are shown for all levels of the structure,
including individual atoms. With `chain`, only structure and chain
SASA values are printed (this is the default).
The output can include relative SASA values for each residues. To
calculate these a reference SASA value is needed, calculated using the
same atomic radii. At the moment such values are only available for
the ProtOr and NACCESS radii (selected using the option `--radii`), if
other radii are used relative SASA will be excluded (in RSA output all
REL columns will have the value 'N/A').
The reference SASA values for residue X are calculated from Ala-X-Ala
peptides in a stretched out configuration. The reference
configurations are supplied for reference in the directory
`rsa`. Since these are not always the most exposed possible
configuration, and because bond lengths and bond angles vary, the
relative SASA values will sometimes be larger than 100 %. At the
moment there is no interface to supply user-defined reference values.
@subsection CLI-JSON JSON
The command
$ freesasa --format=xml --output-depth=residue 3wbm.pdb
generates the following
~~~~{.json}
{
"source":"FreeSASA 2.0",
"length-unit":"Ångström",
"results":[
{
"input":"3wbm.pdb",
"classifier":"ProtOr",
"parameters":{
"algorithm":"Lee & Richards",
"probe-radius":1.3999999999999999,
"resolution":20
},
"structures":[
{
"chain-labels":"ABCDXY",
"area":{
"total":25190.768387067546,
"polar":13638.391677017404,
"apolar":11552.376710050148,
"main-chain":3337.1622502425053,
"side-chain":21853.606136825045
},
"chains":[
{
"label":"A",
"n-residues":86,
"area":{
"total":3785.4864049452635,
"polar":1733.8560208488598,
"apolar":2051.6303840964056,
"main-chain":723.34358684348558,
"side-chain":3062.1428181017791
}
"residues":[
{
"name":"THR",
"number":"5",
"area":{
"total":138.48216994006549,
"polar":56.887951514571867,
"apolar":81.594218425493622,
"main-chain":38.898190013033592,
"side-chain":99.583979927031905
},
"relative-area":{
"total":104.05152148175331,
"polar":113.98106895325961,
"apolar":98.093554250413092,
"main-chain":96.330336832673567,
"side-chain":107.414496739329
},
"n-atoms":7
},
...
},
...
]
}
]
}
]
}
~~~~
Where ellipsis indicates the remaining residues and chains.
@subsection CLI-XML XML
The command
$ freesasa --format=xml 3wbm.pdb
Generates the following
~~~~{.xml}
<?xml version="1.0" encoding="UTF-8"?>
<results xmlns="http://freesasa.github.io/" source="FreeSASA 2.0" lengthUnit="Ångström">
<result classifier="ProtOr" input="3wbm.pdb">
<parameters algorithm="Lee & Richards" probeRadius="1.400000" resolution="20"/>
<structure chains="ABCDXY">
<area total="25190.768" polar="13638.392" apolar="11552.377" mainChain="3337.162" sideChain="21853.606"/>
<chain label="A" nResidues="86">
<area total="3785.486" polar="1733.856" apolar="2051.630" mainChain="723.344" sideChain="3062.143"/>
</chain>
<chain label="B" nResidues="84">
<area total="4342.334" polar="1957.114" apolar="2385.220" mainChain="853.707" sideChain="3488.627"/>
</chain>
<chain label="C" nResidues="86">
<area total="3961.119" polar="1838.724" apolar="2122.395" mainChain="782.652" sideChain="3178.468"/>
</chain>
<chain label="D" nResidues="89">
<area total="4904.298" polar="2332.306" apolar="2571.991" mainChain="977.459" sideChain="3926.838"/>
</chain>
<chain label="X" nResidues="25">
<area total="4156.455" polar="2919.576" apolar="1236.879" mainChain="0.000" sideChain="4156.455"/>
</chain>
<chain label="Y" nResidues="25">
<area total="4041.076" polar="2856.815" apolar="1184.261" mainChain="0.000" sideChain="4041.076"/>
</chain>
</structure>
</result>
</results>
~~~~
@subsection CLI-PDB PDB
The command-line interface can also be used as a PDB filter:
$ cat 3wbm.pdb | freesasa --format=pdb
REMARK 999 This PDB file was generated by FreeSASA 2.0.
REMARK 999 In the ATOM records temperature factors have been
REMARK 999 replaced by the SASA of the atom, and the occupancy
REMARK 999 by the radius used in the calculation.
MODEL 1
ATOM 1 N THR A 5 -19.727 29.259 13.573 1.64 9.44
ATOM 2 CA THR A 5 -19.209 28.356 14.602 1.88 5.01
ATOM 3 C THR A 5 -18.747 26.968 14.116 1.61 0.40
...
The output is a PDB-file where the temperature factors have been
replaced by SASA values (last column), and occupancy numbers by the
radius of each atom (second to last column).
Only the atoms and models used in the calculation will be present in
the output (see @ref Input for how to modify this).
@subsection CLI-RES SASA of each residue type
Calculate the SASA of each residue type:
$ freesasa --format=res 3wbm.pdb
# Residue types in 3wbm.pdb
RES ALA : 251.57
RES ARG : 2868.98
RES ASN : 1218.87
...
RES A : 1581.57
RES C : 2967.12
RES G : 1955.16
RES U : 1693.68
@subsection CLI-SEQ SASA of each residue
Calculate the SASA of each residue in the sequence:
$ freesasa --format=seq 3wbm.pdb
# Residues in 3wbm.pdb
SEQ A 5 THR : 138.48
SEQ A 6 PRO : 25.53
SEQ A 7 THR : 99.42
...
@subsection CLI-RSA RSA
The CLI can also produce output similar to the RSA format from
NACCESS. This format includes both absolute SASA values (ABS) and
relative ones (REL) compared to a precalculated reference max
value. The only significant difference between FreeSASA's RSA output
format and that of NACCESS (except differences in areas due to
different atomic radii), is that FreeSASA will print the value "N/A"
where NACCESS prints "-99.9".
$ freesasa --format=rsa 3wbm.pdb
REM FreeSASA 2.0
REM Absolute and relative SASAs for 3wbm.pdb
REM Atomic radii and reference values for relative SASA: ProtOr
REM Chains: ABCDXY
REM Algorithm: Lee & Richards
REM Probe-radius: 1.40
REM Slices: 20
REM RES _ NUM All-atoms Total-Side Main-Chain Non-polar All polar
REM ABS REL ABS REL ABS REL ABS REL ABS REL
RES THR A 5 138.48 104.1 99.58 107.4 38.90 96.3 81.59 98.1 56.89 114.0
RES PRO A 6 25.53 19.3 11.31 11.0 14.23 47.7 21.67 18.7 3.86 23.9
...
RES GLY A 15 0.64 0.9 0.00 N/A 0.64 0.9 0.00 0.0 0.64 2.0
...
RES U Y 23 165.16 N/A 165.16 N/A 0.00 N/A 52.01 N/A 113.15 N/A
RES C Y 24 165.01 N/A 165.01 N/A 0.00 N/A 46.24 N/A 118.77 N/A
RES C Y 25 262.46 N/A 262.46 N/A 0.00 N/A 85.93 N/A 176.52 N/A
END Absolute sums over single chains surface
CHAIN 1 A 3785.5 3062.1 723.3 2051.6 1733.9
CHAIN 2 B 4342.3 3488.6 853.7 2385.2 1957.1
CHAIN 3 C 3961.1 3178.5 782.7 2122.4 1838.7
CHAIN 4 D 4904.3 3926.8 977.5 2572.0 2332.3
CHAIN 5 X 4156.5 4156.5 0.0 1236.9 2919.6
CHAIN 6 Y 4041.1 4041.1 0.0 1184.3 2856.8
END Absolute sums over all chains
TOTAL 25190.8 21853.6 3337.2 11552.4 13638.4
Note that each `RES` is a single residue, not a residue type as above
(i.e. has the same meaning as `SEQ` above). This unfortunate confusion
of labels is due to RSA support being added much later than the other
options. Fixing it now would break the interface, and will thus
earliest be dealt with in the next major release.
@subsubsection RSA-naccess Using the NACCESS configuration
The reference values for the NACCESS configuration in FreeSASA are not
exactly the same as those that ship with NACCESS, but have been
calculated from scratch using the tripeptides that ship with
FreeSASA. Calling
$ freesasa 3wbm.pdb --format=rsa --radii=naccess
will give an RSA file where the ABS columns should be identical to
NACCESS (if the latter is run with the flag `-b`). REL values will
differ slightly, due to the differences in reference values. NACCESS
also gives different results for the nucleic acid main-chain and
side-chain (possibly due to a bug in NACCESS?). FreeSASA defines the
(deoxy)ribose and phosphate groups as main-chain and the base as
side-chain.
@section CLI-select Selecting groups of atoms
The option `--select` can be used to define groups of atoms whose
integrated SASA we are interested in. It uses a subset of the Pymol
`select` command syntax, see @ref Selection for full
documentation. The following example shows how to calculate the sum of
exposed surface areas of all aromatic residues and of the four chains
A, B, C and D (just the sum of the areas above).
$ freesasa --select "aromatic, resn phe+tyr+trp+his+pro" --select "abcd, chain A+B+C+D" 3wbm.pdb
...
SELECTIONS
freesasa: warning: Found no matches to resn 'TRP', typo?
freesasa: warning: Found no matches to resn 'HIS', typo?
aromatic : 1196.45
abcd : 16993.24
The lines shown above are appended to the regular output. This
particular protein did not have any TRP or HIS residues, hence the
warnings (written to stderr). The warnings can be supressed with the
flag `-w`.
@section Chain-groups Analyzing groups of chains
Calculating the SASA of a given chain or group of chains separately
from the rest of the structure, can be useful for measuring how buried
a chain is in a given structure. The option `--chain-groups` can be
used to do such a separate calculation, calling
$ freesasa --chain-groups=ABCD+XY 3wbm.pdb
produces the regular output for the structure 3WBM, but in addition it
runs a separate calculation for the chains A, B, C and D as though X
and Y aren't in the structure, and vice versa:
PARAMETERS
algorithm : Lee & Richards
probe-radius : 1.400
threads : 2
slices : 20
####################
INPUT
source : 3wbm.pdb
chains : ABCDXY
atoms : 3714
RESULTS (A^2)
Total : 25190.77
Apolar : 11552.38
Polar : 13638.39
CHAIN A : 3785.49
CHAIN B : 4342.33
CHAIN C : 3961.12
CHAIN D : 4904.30
CHAIN X : 4156.46
CHAIN Y : 4041.08
####################
INPUT
source : 3wbm.pdb
chains : ABCD
atoms : 2664
RESULTS (A^2)
Total : 18202.78
Apolar : 9799.46
Polar : 8403.32
CHAIN A : 4243.12
CHAIN B : 4595.18
CHAIN C : 4427.11
CHAIN D : 4937.38
####################
INPUT
source : 3wbm.pdb
chains : XY
atoms : 1050
RESULTS (A^2)
Total : 9396.28
Apolar : 2743.09
Polar : 6653.19
CHAIN X : 4714.45
CHAIN Y : 4681.83
@section Input PDB input
@subsection Hetatom-hydrogen Including extra atoms
The user can ask to include hydrogen atoms and HETATM entries in the
calculation using the options `--hydrogen` and `--hetatm`. In both
cases adding unknown atoms will emit a warning for each atom. This can
either be amended by using the flag `-w` to suppress warnings, or by
using a custom classifier so that they are recognized (see @ref
Config-file).
@subsection Halt-skip Skipping unknown atoms
By default FreeSASA guesses the element of an unknown atom and uses
that elements VdW radius. If this fails the radius is set to 0 (and
hence the atom will not contribute to the calculated area). Users can
request to either skip unknown atoms completely (i.e. no guessing) or
to halt when unknown atoms are found and exit with an error. This is
done with the option `--unknown` which takes one of the three
arguments `skip`, `halt` or `guess` (default). Whenever an unknown
atom is skipped or its radius is guessed a warning is printed to
stderr.
@subsection Chains-models Separating and joining chains and models
If a PDB file has several chains and/or models, by default all chains
of the first model are used, and the rest of the file is ignored. This
behavior can be modified using the following options
- `--join-models`: Joins all models in the input into one large
structure. Useful for biological assembly files were different
locations of the same chain in the oligomer are represented by
different MODEL entries.
- `--separate-models`: Calculate SASA separately for each model in
the input. Useful when the same file contains several
conformations of the same molecule.
- `--separate-chains`: Calculate SASA separately for each chain in
the input. Can be joined with `--separate-models` to calculate
SASA of each chain in each model.
- `--chain-groups`: see @ref Chain-groups
@page API FreeSASA API
@section Basic-API Basics
The API is found in the header [freesasa.h](freesasa_8h.html). The
other source-files and headers in the repository are for internal use,
and are not presented here, but are documented in the source
itself. The file [example.c](example_8c_source.html) contains a simple
program that illustrates how to use the API to read a PDB file from
`stdin` and calculate and print the SASA.
To calculate the SASA of a structure, there are two main options:
1. Initialize a structure from a PDB-file, using either the default
classifier or a custom one to determine the radius of each atom,
and then run the calculation.
2. Provide an array of cartesian coordinates and an array containing
the radii of the corresponding atoms to freesasa\_calc\_coord().
@subsection API-PDB Calculate SASA for a PDB file
The following explains how to use FreeSASA to calculate the SASA of a
fictive PDB file (1abc.pdb). At each step one or more error checks
should have been done, but these are ignored here for brevity. See
the documentation of each function to see what errors can occur.
Default parameters are used at every step, the section @ref
Customizing explains how to configure the calculations.
@subsubsection API-Read-PDB Open PDB file
The function freesasa\_structure\_from\_pdb() reads the atom
coordinates from a PDB file and assigns a radius to each atom. The
third argument can be used to pass options for how to read the PDB
file.
~~~{.c}
FILE *fp = fopen("1abc.pdb");
const freesasa_classifier *classifier = &freesasa_default_classifier;
freesasa_structure *structure = freesasa_structure_from_pdb(fp, classifier, 0);
~~~
@subsubsection API-Calc Perform calculation and get total SASA
Next we use freesasa\_calc\_structure() to calculate SASA using the
structure we just generated, and then print the total area. The argument
`NULL` means use default freesasa_parameters.
~~~{.c}
freesasa_result *result = freesasa_calc_structure(structure, NULL);
printf("Total area: %f A2\n",result->total);
~~~
@subsubsection API-Classes Get polar and apolar area
We are commonly interested in the polar and apolar areas of a
molecule, this can be calculated by freesasa\_result\_classes(). To
get other classes of atoms we can either define our own classifier, or
use freesasa\_select\_area() defined in the next section. The return
type ::freesasa\_nodearea is a struct contains the total area and the
area of all apolar and polar atoms, and main-chain and side-chain
atoms.
~~~{.c}
freesasa_nodearea area = freesasa_result_classes(structure, result);
printf("Total : %f A2\n", area.total);
printf("Apolar : %f A2\n", area.apolar);
printf("Polar : %f A2\n", area.polar);
printf("Main-chain : %f A2\n", area.main_chain);
printf("Side-chain : %f A2\n", area.side_chain);
~~~
@see @ref Classification
@subsubsection API-Select Get area of custom groups of atoms
Groups of atoms can be defined using freesasa\_selection\_new(), which
takes a selection definition uses a subset of the Pymol select syntax
~~~{.c}
freesasa_selection *selection =
freesasa_selection_new("aromatic, resn phe+tyr+trp+his+pro",
structure, result);
printf("Area of selection '%s': %f A2\n",
freesasa_selection_name(selection), freesasa_selection_area(selection);
~~~
@see @ref Selection
@subsubsection structure-node Navigating the results as a tree
In addition to the flat array of results in ::freesasa\_result, and
the global values returned by freesasa\_result\_classes(), FreeSASA
has an interface for navigating the results as a tree. The leaf nodes
are individual atoms, and there are parent nodes at the residue,
chain, and structure levels. The function freesasa\_calc\_tree() does
a SASA calculation and returns the root node of such a tree. (If one
already has a ::freesasa\_result the function freesasa\_tree\_init()
can be used instead). Each node stores a ::freesasa\_nodearea for the
sum of all atoms belonging to the node. The tree can be traversed with
freesasa\_node\_children(), freesasa\_node\_parent() and
freesasa\_node\_next(), and the area, type and name using
freesasa\_node\_area(), freesasa\_node\_type() and
freesasa\_node\_name(). Additionally there are special properties for
each level of the tree.
@see node
@subsubsection export-tree Exporting to RSA, JSON and XML
The tree structure can also be exported to an RSA, JSON or XML file
using freesasa\_tree\_export(). The RSA format is fixed, but the user
can select which levels of the tree to include in JSON and XML. The
following illustrates how one would generate a tree and export it to
XML, including nodes for the whole structure, chains and residues (but
excluding individual atoms).
~~~~{.c}
freesasa_node *tree = freesasa_calc_tree(structure,
&freesasa_default_parameters,
&freesasa_default_classifier);
FILE *file = fopen("output.xml", "w");
freesasa_tree_export(file, tree, FREESASA_XML | FREESASA_OUTPUT_RESIDUE);
fclose(file);
freesasa_node_free(tree);
~~~~
@subsection Coordinates
If users wish to supply their own coordinates and radii, these are
accepted as arrays of doubles passed to the function
freesasa\_calc\_coord(). The coordinate-array should have size 3*n with
coordinates in the order `x1,y1,z1,x2,y2,z2,...,xn,yn,zn`.
~~~{.c}
double coord[] = {1.0, /* x */
2.0, /* y */
3.0 /* z */ };
double radius[] = {2.0};
int n_atoms = 1;
freesasa_result *result = freesasa_calc_coord(coord, radius, n_atoms, NULL);
~~~
@subsection Error-handling
The principle for error handling is that unpredictable errors should
not cause a crash, but rather allow the user to exit gracefully or
make another attempt. Therefore, errors due to user or system
failures, such as faulty parameters, malformatted config-files, I/O
errors or out of memory errors, are reported through return values,
either ::FREESASA\_FAIL or ::FREESASA\_WARN, or by `NULL` pointers,
depending on the context (see the documentation for the individual
functions).
Errors that are attributable to programmers using the library, such as
passing null pointers where not allowed, are checked by asserts.
@subsection Thread-safety
The only global state the library stores is the verbosity level (set
by freesasa\_set\_verbosity()) and the pointer to the error-log
(defaults to `stderr`, can be changed by freesasa\_set\_err\_out()).
It should be clear from the documentation when the other functions
have side effects such as memory allocation and I/O, and thread-safety
should generally not be an issue (to the extent that your C library
has threadsafe I/O and dynamic memory allocation). The SASA
calculation itself can be parallelized by using a
::freesasa\_parameters struct with ::freesasa\_parameters.n\_threads
\> 1 (default is 2) where appropriate. This only gives a significant
effect on performance for large proteins or at high precision, and
because not all steps are parallelized it is usually not worth it to
go beyond 2 threads.
@section Customizing Customizing behavior
The types ::freesasa\_parameters and ::freesasa\_classifier can be
used to change the parameters of the calculations. Users who wish to
use the defaults can pass `NULL` wherever pointers to these are
requested.
@subsection Parameters Parameters
Calculation parameters can be stored in a ::freesasa\_parameters
object. It can be initialized to default by
~~~{.c}
freesasa_parameters param = freesasa_default_parameters;
~~~
The following code would run a high precision Shrake & Rupley
calculation with 10000 test points on the provided structure.
~~~{.c}
freesasa_parameters param = freesasa_default_parameters;
param.alg = FREESASA_SHRAKE_RUPLEY;
param.shrake_rupley_n_points = 10000;
freesasa_result *result = freesasa_calc_structure(structure, param);
~~~
@subsection Classification Specifying atomic radii and classes
Classifiers are used to determine which atoms are polar or apolar, and
to specify atomic radii. In addition the three standard classifiers
(see below) have reference values for the maximum areas of the 20
standard amino acids which can be used to calculate relative areas of
residues, as in the RSA output.
The default classifier is available through the const variable
::freesasa\_default\_classifier. This uses the *ProtOr* radii, defined
in the paper by Tsai et
al. ([JMB 1999, 290: 253](http://www.ncbi.nlm.nih.gov/pubmed/10388571))
for the standard amino acids (20 regular plus SEC, PYL, ASX and GLX),
for some capping groups (ACE/NH2) and the standard nucleic acids. If
the element can't be determined or is unknown, a zero radius is
assigned. It classes all carbons as *apolar* and all other known atoms
as *polar*.
Early versions of FreeSASA used the atomic radii by Ooi et
al. ([PNAS 1987, 84: 3086-3090](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC304812/)),
this classifier is still available through ::freesasa_oons_classifier.
Users can provide their own classifiers through @ref Config-file. At
the moment these do not allow the user to specify reference values to
calculate relative SASA values for RSA output.
The default behavior of freesasa_structure_from_pdb(),
freesasa_structure_array(), freesasa_structure_add_atom() and
freesasa_structure_add_atom_wopt() is to first try the provided
classifier and then guess the radius if necessary (emitting warnings
if this is done, uses VdW radii defined by [Mantina et al. J Phys Chem
2009, 113:5806](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3658832/)).
See the documentation for these functions for what parameters to use
to change the default behavior.
@page Config-file Classifier configuration files
The configuration files read by freesasa_classifier_from_file() or the
command-line option `-c` should have two sections: `types:` and
`atoms:`, and optionally the section `name:`.
The types-section defines what types of atoms are available
(aliphatic, aromatic, hydroxyl, ...), what the radius of that type is
and what class a type belongs to ('polar' or 'apolar', case
insensitive). The types are just shorthands to associate an atom with
a given combination of class and radius. The user is free to define as
many types and classes as necessary.
The atoms-section consists of triplets of residue-name, atom-name (as
in the corresponding PDB entries) and type. A prototype file would be
~~~
name: myclassifier # tag and value must be on the same line (optional)
types:
C_ALIPHATIC 2.00 apolar
C_AROMATIC 1.75 apolar
N 1.55 polar
atoms:
ANY N N
ANY CA C_ALIPHATIC
ANY CB C_ALIPHATIC
ARG CG C_ALIPHATIC
PRO CB C_AROMATIC # overrides ANY CB
~~~
The residue type `ANY` can be used for atoms that are the same in all
or most residues (such as backbone atoms). If there is an exception
for a given amino acid this can be overridden as is shown for `PRO CB`
in the example.
A few example configurations are available in the directory
[share/](https://github.com/mittinatten/freesasa/tree/master/share). The
configuration-file
[protor.config](https://github.com/mittinatten/freesasa/tree/master/share/protor.config)
is a copy of the default classifier, and can be used to add extra
atoms that need to be classified, while keeping the defaults for the
standard residues (also see the file
[scripts/chemcomp2config.pl](https://github.com/mittinatten/freesasa/tree/master/scripts/)
for instructions on how to generate configurations for new chemical
components semi-automatically). If something common is missing in the
default classifier, [create an
issue](https://github.com/mittinatten/freesasa/issues) on Github so
that it can be added.
FreeSASA also ships with some configuration-files that mimic other
popular programs, such as
[NACCESS](https://github.com/mittinatten/freesasa/tree/master/share/naccess.config)
and
[DSSP](https://github.com/mittinatten/freesasa/tree/master/share/dssp.config).
The static classifiers in the API were generated using
[scripts/config2c.pl](https://github.com/mittinatten/freesasa/tree/master/scripts/)
to convert the correspoding configurations in `share` to C code.
@page Selection Selection syntax
FreeSASA uses a subset of the Pymol select commands to give users an
easy way of summing up the SASA of groups of atoms. This is done by
the function freesasa\_selection\_new() in the C API,
freesasa.selectArea() in the Python interface and the option
`--select` for the command line tool. All commands are case
insensitive. A basic selection has a selection name, a property
selector and a list of arguments
<selection-name>, <selector> <list>
For example
aromatic, resn phe+tyr+trp+his+pro
Several selectors can be joined using boolean logic and parentheses,
<selection-name>, (<s1> <l1>) and not (<s2> <l2> or <s3> <l3>)
where s1, s2 and s3 are selectors and l1, l2 and l3 are lists. The
operator `and` has precedence over `or`, so the second parentheses is
necessary but not the first, in the example above. The selection name
can include letters, numbers and underscores. The name can't be longer
than ::FREESASA\_MAX\_SELECTION\_NAME characters.
The following property selectors are supported
- `resn` Residue names like "ala", "arg", "du", etc
- `resi` Residue index (positive or negative integers)
- `chain` Chain labels (single characters)
- `name` Atom names, such as "ca", "c", "oxt", etc
- `symbol` Element symbols, such as "C", "O", "Se", "Fe", etc.
A list of residues can be selected using
resn ala+val+leu+ile+met
and similarly for the other four selectors. In addition `resi` and
`chain` support ranges
resi 1-10 (residues 1 to 10)
resi -10 (residues indices < 10)
resi 10- (residues indices > 10)
resi 1-10+20-30+35- (residues 1 to 10, 20 to 30 and above 35)
resi \-20-\-15+\-10-5 (residues -20 to -15 and -10 to 5)
chain A+C-E (chains A and C to E, no open intervals allowed here)
Combining ranges with plus signs, as in the three last lines, is not
allowed in Pymol but supported by FreeSASA.
If a selection list contains elements not found in the molecule that
is analyzed, a warning is printed and that part of the list does not
contribute to the selection. Not finding a list element can be because
it specifies a residue that does not exist in the particular molecule,
or because of typos. The selector does not keep a list of valid
elements, residue names, etc.
@page Python Python interface
If Python is enabled using
$ ./configure --enable-python-bindings
Cython is used to build Python bindings for FreeSASA, and `make
install` will install them. The option `--with-python=...` can be
specified to specify which Python binary to use.
Below follow some illustrations of how to use the package, see the
@ref freesasa "package documentation" for details.
@section Python-basics Basic calculations
Using defaults everywhere a simple calculation can be carried out as
follows (assuming the PDB structure 1UBQ is available)
~~~{.py}
import freesasa
structure = freesasa.Structure("1ubq.pdb")
result = freesasa.calc(structure)
area_classes = freesasa.classifyResults(result, structure)
print "Total : %.2f A2" % result.totalArea()
for key in area_classes:
print key, ": %.2f A2" % area_classes[key]
~~~
Which would give the following output
Total : 4804.06 A2
Polar : 2504.22 A2
Apolar : 2299.84 A2
The following does a high precision L&R calculation
~~~{.py}
result = freesasa.calc(structure,
freesasa.Parameters({'algorithm' : freesasa.LeeRichards,
'n-slices' : 100}))
~~~
Using the results from a calculation we can also integrate SASA over a selection of
atoms, using a subset of the Pymol selection syntax (see @ref Selection):
~~~{.py}
selections = freesasa.selectArea(('alanine, resn ala', 'r1_10, resi 1-10'),
structure, result)
for key in selections:
print key, ": %.2f A2" % selections[key]
~~~
which gives the output
alanine : 120.08 A2
r1_10 : 634.31 A2
@section Python-classification Customizing atom classification
This uses the NACCESS parameters (the file 'naccess.config' is
available in the share/ directory of the repository).
~~~{.py}
classifier = freesasa.Classifier("naccess.config")
structure = freesasa.Structure("1ubq.pdb", classifier)
result = freesasa.calc(structure)
area_classes = freesasa.classifyResults(result, structure, classifier)
~~~
Classification can be customized also by extending the Classifier
interface. The code below is an illustration of a classifier that
classes Nitrogens separately, and assigns radii based on element only
(and crudely).
~~~{.py}
import freesasa
import re
class DerivedClassifier(Classifier):
def classify(self, residueName, atomName):
if re.match('\s*N', atomName):
return 'Nitrogen'
return 'Not-nitrogen'
def radius(self, residueName, atomName):
if re.match('\s*N',atomName): # Nitrogen
return 1.6
if re.match('\s*C',atomName): # Carbon
return 1.7
if re.match('\s*O',atomName): # Oxygen
return 1.4
if re.match('\s*S',atomName): # Sulfur
return 1.8
return 0; # everything else (Hydrogen, etc)
classifier = DerivedClassifier()
# use the DerivedClassifier to calculate atom radii
structure = freesasa.Structure("1ubq.pdb", classifier)
result = freesasa.calc(structure)
# use the DerivedClassifier to classify atoms
area_classes = freesasa.classifyResults(result,structure,classifier)
~~~
Of course, this example is somewhat contrived, if we only want the
integrated area of Nitrogen atoms, the simpler choice would be
~~~{.py}
selection = freesasa.selectArea('nitrogen, symbol n', structure, result)
~~~
However, extending freesasa.Classifier, as illustrated above, allows
classification to arbitrary complexity and also lets us redefine the
radii used in the calculation.
@section BioPDB Bio.PDB
FreeSASA can also calculate the SASA of a Bio.PDB structure
~~~{.py}
from Bio.PDB import PDBParser
parser = PDBParser()
structure = parser.get_structure("Ubiquitin", "1ubq.pdb")
result, sasa_classes = freesasa.calcBioPDB(structure)
~~~
If one needs more control over the analysis the structure can be
converted to a freesasa.Structure using freesasa.structureFromBioPDB()
and the calculation can be performed the normal way using this
structure.
@page Geometry Geometry of Lee & Richards' algorithm
This page explains the geometry of the calculations in L&R
and can be used to understand the source code. As far as possible the
code uses similar notation to the formulas here.
We will use the following notation: An atom \f$i\f$ has a van der
Waals radius \f$r_i\f$, the rolling sphere (or *probe*) has radius
\f$r_\text{P}\f$ and when these are added we get an extended radius
\f$R_i = r_i + r_\text{P}\f$. The sphere of radius \f$R_i\f$ centered
at the position of atom \f$i\f$ represents the volume not accessible
to the center of the probe. The SASA for a molecule is then obtained
by calculating the non-buried surface area of the extended spheres.
The L&R algorithm calculates the surface area by slicing the
protein, calculating the length of the solvent exposed contours in
each slice and then adding up the length multiplied by the slice
thickness.

Divide atom \f$i\f$ into \f$n\f$ slices, orthogonal to an arbitrary
axis, of thickness \f$\delta = 2R_i/n\f$. The position of the middle
of the slice along that axis is denoted \f$z\f$, and the center of
atom \f$i\f$, along the same axis, is at \f$z_i\f$. In each slice, the
atom is thus a circle of radius \f[R_i^\prime =
\sqrt{R_i^2-(z-z_i)^2}\,.\f] These circles are either completely
buried inside neighboring atoms, completely exposed, or partially
exposed.

The exposed arc lengths for each atom can be calculated exactly. For
each pair of atoms \f$i,j\f$, the distance between their centers
projected on the slice is \f$d_{ij}\f$ (independent of \f$z\f$). If
\f$d_{ij} > R_i^\prime + R_j^\prime\f$, there is no overlap. If
\f$d_{ij} < R_j^\prime - R_i^\prime\f$ circle \f$i\f$ is completely
inside \f$j\f$ (and the other way around). If \f$d_{ij}\f$ lies
between these two cases the angle of circle \f$i\f$ that is buried due
to circle \f$j\f$ is
\f[ \alpha = 2\arccos \bigl[({R_i^\prime}^2_{\,}
+ d_{ij}^2 - {R_{j}^\prime}^2_{\,})/(2R_i^\prime d_{ij})\bigr]. \f]
If the middle point of this arc on the circle is at an angle
\f$\beta\f$, the arc spans the interval
\f$[\beta-\alpha/2,\beta+\alpha/2]\f$. By adding up these arcs and
taking into account any overlap between them we get the total buried
angle \f$\gamma\f$ in this slices. The exposed arc angle for this atom
and slice is thus \f$2\pi-\gamma\f$ and the total SASA of that atom
\f[ A_i =R_i \delta \!\! \sum_{s\in\text{slices}} \!\!
\left[2\pi-\gamma_s\right]\,. \f]
The angle is multiplied by \f$R_i\f$ (not \f$R_i^\prime\f$) to give
the area of a conical frustum circumscribing the sphere at the
slice. Finally, the total area \f$A\f$ is the sum of all \f$A_i\f$.
In FreeSASA, the L\&R SASA calculation begins by finding overlapping
spheres and storing the contacts in an adjacency list. It then
iterates through all the slices of each atom and checks for overlap
with adjacent atoms in each slice, and adds up the exposed arcs to
calculate the atom's contribution to the SASA of the slice. The
calculations for each atom are completely independent and can thus be
parallelized over an arbitrary number of threads, whereas the
calculation of adjacency lists has not been parallelized.
| Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/data/freesasa-2.0.1/doc/doxy_main.md | doxy_main.md |
The MIT License (MIT)
Copyright (c) 2016 Simon Mitternacht
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/data/freesasa-2.0.1/doc/license.md | license.md |
FreeSASA
========
[](https://zenodo.org/badge/latestdoi/18467/mittinatten/freesasa)
[](https://travis-ci.org/mittinatten/freesasa)
[](https://coveralls.io/github/mittinatten/freesasa?branch=master)
C-library for calculating Solvent Accessible Surface Areas.
License: MIT (see file LICENSE). Copyright: Simon Mitternacht 2013-2016.
FreeSASA is a C library and command line tool for calculating Solvent
Accessible Surface Area (SASA) of biomolecules. It is designed to be
simple to use with defaults, but allows customization of all
parameters of the calculation and provides a few different tools to
analyze the results. Python bindings are also included in the
repository.
By default Lee & Richards' algorithm is used, but Shrake & Rupley's is
also available. Both can be parameterized to arbitrary precision, and
for high resolution versions of the algorithms, the calculations give
identical results.
FreeSASA assigns a radius and a class to each atom. The atomic radii
are by default the _ProtOr_ radii defined by Tsai et
al. ([JMB 1999, 290: 253](http://www.ncbi.nlm.nih.gov/pubmed/10388571))
for standard amino acids and nucleic acids, and the van der Waals
radius of the element for other atoms. Each atom is also classified as
either polar or apolar.
Users can provide their own atomic radii and classifications via
configuration files. The input format for configuration files is
described in the
[online documentation](http://freesasa.github.io/doxygen/Config-file.html),
and the `share/` directory contains some sample configurations,
including one for the NACCESS parameters
([Hubbard & Thornton 1993](http://www.bioinf.manchester.ac.uk/naccess/)).
Version 2.0 adds some new features and breaks a few parts of the
interface from 1.x (mainly the API), see CHANGELOG.md for detailed
information.
Building and installing
------------------------
FreeSASA can be compiled and installed using the following
./configure
make && make install
NB: If the source is downloaded from the git repository the
configure-script needs to be set up first using `autoreconf -i`. Users
who don't have autotools installed, can download a tarball that
includes the autogenerated scripts from http://freesasa.github.io/ or
from the latest
[GitHub-release](https://github.com/mittinatten/freesasa/releases).
The above commands build and install the command line tool `freesasa`
(built in `src/`), the command
freesasa -h
gives an overview of options. To run a calculation from PDB-file input
using the defaults, simply type
freesasa <pdb-file>
In addition, `make install` installs the header `freesasa.h` and the
library `libfreesasa`. If the configure script is called with the
option `--enable-python-bindings`, the Python module is also built and
installed.
The configuration can be changed with these options:
* `--enable-python-bindings` builds Python bindings, requires Cython
0.21 or higher. On some platforms the C library needs to be
compiled with `CFLAGS=-fPIC` to allow it to be linked to the
Python module.
* `--with-python=<python>` specifies which python binary to use
* `--disable-json` build without support for JSON output.
* `--disable-xml` build without support for XML output.
* `--disable-threads` build without multithreaded calculations
* `--enable-doxygen` activates building of Doxygen documentation
For developers:
* `--enable-check` enables unit-testing using the Check framework
* `--enable-gcov` adds compiler flags for measuring coverage of tests
using gcov
* `--enable-parser-generator` rebuild parser/lexer source from
Flex/Bison sources (the autogenerated code is included in the
repository, so no need to do this if you are not going to change
the parser).
Documentation
-------------
Enabling Doxygen builds a [full reference
manual](http://freesasa.github.io/doxygen/), documenting both CLI and
API in the folder `doc/html/doxygen/`, also available on the web at
http://freesasa.github.io/.
After building the package, calling
freesasa -h
explains how the commandline tool can be used.
Compatibility and dependencies
------------------------------
The program has been tested successfully with several versions of GNU
C Compiler and Clang/LLVM. The library can be built using only
standard C and GNU libraries. The standard build depends on
[json-c](https://github.com/json-c/json-c) and
[libxml2](http://xmlsoft.org/). These can be disabled by configuring
with `--disable-json` and `--disable-xml` respectively.
Developers who want to do testing need to install the Check unit
testing framework. Building the full reference manual requires Doxygen
(version > 1.8.8). Building the Python bindings requires
Cython. Changing the selection parser and lexer requires Flex and
Bison. These build options, which add extra dependencies, are disabled
by default to simplify installation for users only interested in the
command line tool and and/or C Library.
Citing FreeSASA
---------------
FreeSASA can be cited using the following publication
* Simon Mitternacht (2016) FreeSASA: An open source C library for
solvent accessible surface area calculations. _F1000Research_
5:189. (doi:
[10.12688/f1000research.7931.1](http://dx.doi.org/10.12688/f1000research.7931.1))
The [DOI numbers from Zenodo](https://zenodo.org/badge/latestdoi/18467/mittinatten/freesasa)
can be used to cite a specific version of FreeSASA.
| Aggrescan3D | /Aggrescan3D-1.0.2.tar.gz/Aggrescan3D-1.0.2/aggrescan/data/freesasa-2.0.1/doc/README.md | README.md |
Agile-Diamond
=============
**Agile-Diamond** helps initiate and manage a software development project.
Overview
--------
Agile-Diamond contains everything needed to start and control an Agile software project. These files expand into a template with sensible defaults for a small team to start building something. An Agile-Diamond project compiles into PDFs, DOCX, presentations, and a website.
Installation
^^^^^^^^^^^^
::
pip install Agile-Diamond
Documentation
^^^^^^^^^^^^^
http://agile-diamond.readthedocs.org
| Agile-Diamond | /Agile-Diamond-0.1.1.tar.gz/Agile-Diamond-0.1.1/Readme.rst | Readme.rst |
---
title: "Diamond Agile Project Management"
---
# overview
This project is a clone of the Diamond Agile Project Management template. The template provides a starter set of documents that generally adhere to the agile methodology. A project can be planned and managed by filling out the documents in this template.
# getting started
The steps required to complete the project are delineated in the Checklist. Open up that file and take it from there.
open assets/agile/*Checklist.oo3
# using this documentation
The Checklist is an ordered path through the documents. Editing the documents in the order specified by the Checklist will ensure the right questions are asked at the right time and the answers are written down for everybody to see.
At a certain point, the Timeline becomes a more important document for planning the completion of the project, but the Checklist addresses this.
# representations of the project
The basic agile project management process involves editing the documentation in order to generate the proper representation of project ideas for communication with various audiences.
For example: the Charter document is important for starting the project. Stakeholders might edit the document, so a .docx file might be the best representation for them. Meanwhile, team members should benefit most from a full-screen presentation so that they can engage in a discussion.
This project documentation can be folded into multiple representation states for consumption by different audiences:
- **managing state**, which is typically Markdown; this is stored in version control and all other states are derived from it
- **team discussion state**, which is a series of several PDFs that have lots of pages and very few lines per page; intended for team consumption
- **using state**, which is an HTML-based website starting with the Project Guide that pulls together all of the project artifacts
- **archival state**, which is a single "Complete Project" PDF that contains every document used in the project
- **migrated managing state**, which is typically contained within a wiki; at this point, it is difficult to convert the project into any other state
## to facilitate management
The files in this very folder are the management files. In their raw format, these files are typically Markdown or an OmniGroup format (e.g. OmniGraffle). It is easy to edit and version control these files.
## to facilitate team discussion
Presentations are a good way to communicate an idea to lots of people. Many of the documents in this project can be easily rendered as a presentation. The resulting presentations are PDF files that can be displayed in full-screen on a big display so everybody can see.
make presentations
## to facilitate use
This project's documentation is designed to be rendered as a website. The main page of the site is the Project Guide, so it already links through to the rest of the documents in the project. This site is designed to be mirrored onto a local web server so the team can easily refer to it to perform routine tasks.
make
open output/index.html
## to facilitate archival and sharing
The project documentation can be consolidated into a single PDF file. The resulting file is easy to archive and share externally (e.g. via email). It has all the same information as the website and presentations, but it is self-contained and has no dependencies.
make pdf
# Diamond
This template is closely tied to the Diamond ecosystem (Flask-Diamond and Domo-Diamond). Flask-Diamond is a Python application platform for building software with a Model-View-Controller pattern. Domo-Diamond is a Puppet configuration environment based on Ubuntu Linux LTS that provides a consistent deployment target for Flask-Diamond applications.
Despite this underlying assumption, most of the Diamond Agile Project Management template will generalize to any software engineering project.
| Agile-Diamond | /Agile-Diamond-0.1.1.tar.gz/Agile-Diamond-0.1.1/skels/agile-software/Readme.md | Readme.md |
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
#from selenium import webdriver
#from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
#import selenium.webdriver as driver
class Agile:
def __init__(self,driver):
"""
This specially designed for Automating the Agile PLM Web application.
developed by GBS EQ Automation Team.
:Features:
- login(*url,*User_Name,*Password)
- quick_search_part(*Part_Number)
- part_rev_selection(*Part_Number_Revision)
Note: All (*) as arguments need to pass to functions.
For Additional Modules: Contact - [email protected]
"""
self.WebDriverWait=WebDriverWait
self.EC=EC
self.driver=driver
self.By=By
def login(self,url,user_name,Password):
"""
It will navigate to the Agile page and Login with the credential ID & switch to main window.
:Args:
- url: hyper link on Test or Live Environment of Agile 9.3.6
- user_name: Login user_name(Mostly ADID)
- Password: password for login
:Usage:
agile.login(
url,
user_name,
password)
Note: After the login, existing window will be closed default and new window will be enabled.
"""
self.driver.get(url)
window_before = self.driver.window_handles[0]
self.driver.find_element_by_id("j_username").send_keys(user_name)
self.driver.find_element_by_id("j_password").send_keys(Password)
self.driver.find_element_by_id("loginspan").click()
self.WebDriverWait(self.driver, 120).until(self.EC.number_of_windows_to_be(2))
newWindow = [window for window in self.driver.window_handles if window != window_before][0]
self.driver.close()
self.driver.switch_to.window(newWindow)
self.WebDriverWait(self.driver, 120).until(self.EC.visibility_of_element_located((self.By.ID, "preferences")))
self.driver.maximize_window()
def quick_search_part(self,part_number):
"""
To search the part or document number and navigate in the Agile.
:Args:
- part_number: Part Number
:Usage:
quick_search_part(part_number)
Note: No return arguments.
"""
self.driver.find_element_by_id('QUICKSEARCH_STRING').send_keys(part_number)
while self.driver.find_element_by_id('QUICKSEARCH_STRING').get_attribute('value')!=part_number:
self.driver.find_element_by_id('QUICKSEARCH_STRING').clear()
self.driver.find_element_by_id('QUICKSEARCH_STRING').send_keys(part_number)
self.driver.find_element_by_id('top_simpleSearchspan').click()
while True:
try:
if self.driver.find_element_by_id('treegrid_QUICKSEARCH_TABLE').is_displayed() is True:
self.driver.find_element_by_id('top_simpleSearchspan').click()
self.WebDriverWait(self.driver, 120).until(self.EC.visibility_of_element_located((self.By.ID, "searchResult")))
for i in range(len(self.driver.find_elements_by_class_name('GMBodyMid')[0].find_elements_by_class_name('GMDataRow'))):
text1=self.driver.find_elements_by_class_name('GMBodyMid')[0].find_elements_by_class_name('GMDataRow')[i].find_elements_by_tag_name('td')[3].text
if text1.strip()==part_number:
self.driver.find_elements_by_class_name('GMBodyMid')[0].find_elements_by_class_name('GMDataRow')[i].find_elements_by_tag_name('td')[3].click()
try:
self.driver.find_elements_by_class_name('GMBodyMid')[0].find_elements_by_class_name('GMDataRow')[i].find_elements_by_tag_name('td')[3].find_elements_by_tag_name('a')[0].click()
except:
pass
break
self.WebDriverWait(self.driver, 120).until(self.EC.visibility_of_element_located((self.By.ID, "selectedTab")))
break
elif self.driver.find_element_by_id('selectedTab').is_displayed() is True:
break
except:
try:
if self.driver.find_element_by_id('selectedTab').is_displayed() is True:
break
except:
continue
def part_rev_selection(self,rev):
[ele.click() for ele in self.driver.find_element_by_id('revSelectName').find_elements_by_tag_name('option') if rev in ele.text]
while True:
visible=self.driver.find_element_by_id('progress_indicator_global').value_of_css_property('visibility')
if visible=="hidden":
break
#def remove_attachment_by_file_desc(desc_name): | Agile-PLM | /Agile_PLM-1.0.zip/Agile_PLM-1.0/agile_plm/agile.py | agile.py |
# AgileCLU #
AgileCLU is a command line implementation of Limelight Networks Agile Storage cloud platform. It is also a Python library to simplify integrating Python applications with cloud object storage.
The tools and library leverage Agile's JSON-RPC APIs and HTTP ingest and egress capabilities in an easy to use way. To use these tools, you must have:
* An account on Limelight Network's Agile Storage cloud platform. (http://www.limelightnetworks.com)
## Agile Storage Locations ##
As of October 2012, the Agile Storage Cloud has storage capacity in 34 geographies around the world.

## Communication ##
Feel free to send any questions, comments, or patches using the AgileCLU Development at Github page (you'll need to join to send a message):
* [AgileCLU Release Documentation](http:/wylieswanson.github.com/AgileCLU)
* [AgileCLU Development at GitHub](https://github.com/wylieswanson/AgileCLU)
* [AgileCLU at Python Package Index](http://pypi.python.org/pypi/AgileCLU)
# Basic Installation #
If you already have Python and [Python Package Index](http://pypi.python.org/pypi/setuptools) (PyPI) installed on your machine, the installation of AgileCLU is simple and straightfoward. Simply execute one of the following commands (sudo is usually required on Linux):
easy_install AgileCLU
or,
pip install AgileCLU
If the above method worked for you, you can skip the operating system-specific installation sections and move to Configuration, as you have now completed the installation of AgileCLU. If not, consult the relevant operating system-specific sections in the Advanced Configuration sections.
# Upgrading #
If you are upgrading from a release prior to 0.3.1, you may need to manually delete the files from your Python installation (egg and easy-install.pth) prior to invoking easy_install or pip. For future upgrades, can force to latest version with:
easy_install -U AgileCLU
# Configuration #
Since AgileCLU 0.4.0 the configuration of profiles has been greatly simplified. Configuration profiles are stored in ~/.agileclu (off of active user accounts home directory). After installing AgileCLU, use 'agileprofile create' to configure a default account. You can create as many configuration profiles as you like, with 'agileprofile create profilename'. To use different profiles from the command line tools, specify the -l option for any given command. If you are using Windows, you need to include the .py extension, substituting agileprofile with agileprofile.py.
agileprofile create
Example output:
agileprofile.py (AgileCLU 0.4.0)
CREATE PROFILE: test
Username : testcompany
Password :
Re-enter password :
Egress protocol [http] :
Egress hostname [global.mt.lldns.net] :
Egress base path : /testcompany
Ingest protocol [https] :
Ingest hostname : test-company.api.agile.lldns.net
Profile (test) has been saved. Exiting.
# AgileCLU from Command Line #
The commands that are currently available are:
*agileprofile* - Generate a profile based on account credentials and ingest/egress information
*agilefetch* - Automatically download a file from any URL and place it in your storage in a specified directory
*agilemkdir* - Make a directory
*agilerm* - Remove a file
*agilels* - List a directory
*agilepost* - Upload a file
NOTE: For Windows, add a ".py" extension to the above commands.
# Advanced Installation #
The advanced installation covers installing prerequisites, like Python and Python Setuptools. Specific Python libraries will be installed automaticaly when you run easy_install. If you already have Python and Easysetup installed, you do not need to use the following directions.
## Installation:Linux ##
On most Linux distributions, Python is already installed, you only need to install PyPI. For Debian, Ubuntu and other distributions using APT, install PyPI with the following:
sudo apt-get install python-pip
If you are running another distribution, consult the [Python setuptools](http://pypi.python.org/pypi/setuptools) documentation. After you complete this step, complete Basic Installation and move on to Configuration.
## Installation:Mac OSX ##
Python is already installed by default on modern OS X.
## Installation:Windows 32-bit and 64-bit ##
The Windows 32-bit and 64-bit Installation section covers Windows environment variables, along with Python and Python Setuptools.
### Windows Python ###
Python must be installed on the machine. You can download from http://www.python.org/getit/ or, specifically, for Windows 32 and 64-bit:
* Python 2.7.3 Windows Installer (Windows binary - does not include source)
* http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi
* Python 2.7.3 Windows X86-64 Installer (Windows AMD64 / Intel 64 / X86-64 bainry - does not include source)
* http://www.python.org/ftp/python/2.7.3/python-2.7.3.amd64.msi
### Windows Environment Variables ###
Once Python has been installed, you will want to add setuptools, the mainstream package manager for Python, also known as PyPI.
Next, set the system's PATH variable to include directories that include Python components and packages we'll add later. To do this:
* Click the bottom left Windows icon
* In the search field, type 'system'
* In the Control Panel section of the search results, select "Edit system environment variables"
* Select "Environment Variables"
* In the "System variables" section, scroll down to Path and click "Edit...", and then append the below text to the "Variable Value" field, then select OK.
> ;C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Scripts;
### Windows Python Setuptools ###
* For 32-bit Windows
* Install setuptools using the provided .exe installer.
* http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11.win32-py2.7.exe
* For 64-bit Windows
* Download ez_setup.py and run it; it will download the appropriate .egg file and install it for you. (Currently, the provided .exe installer does not support 64-bit versions of Python for Windows, due to a distutils installer compatibility issue.
* http://peak.telecommunity.com/dist/ez_setup.py
* Run "ez_setup.py"
At this point, you can return to the basic installation method (easy_install) at the top of this document. Note that you will need to place the output of agileprofile in C:\etc\agile\agile.conf, or alternate profiles C:\etc\agile\profileconf (to be used by the -l command line option).
# Libraries used by AgileCLU #
This package leverages the following Python libraries:
* poster by Chris AtLee - used for streaming ingest (http://atlee.ca/software/poster/)
* progressbar by Nilton Volpato - used for console ingest progress bar (http://code.google.com/p/python-progressbar/)
* pydes by Todd Whiteman - used as part of the password encryption scheme for config files (http://twhiteman.netfirms.com/des.html)
* jsonrpclib by John Marshall - an implementation of the JSON-RPC specification (https://github.com/joshmarshall/jsonrpclib)
| AgileCLU | /AgileCLU-0.4.2.tar.gz/AgileCLU-0.4.2/README.md | README.md |
from AgileCLU import AgileCLU
from optparse import OptionParser, OptionGroup
from operator import itemgetter
import sys, os.path, string, urllib
def sizeof_fmt(num):
for x in ['bytes','KB','MB','GB','TB']:
if num < 1024.0: return "%3.1f %s" % (num, x)
num /= 1024.0
def main(*arg):
# parse command line and associated helper
parser = OptionParser( usage= "usage: %prog [options] path", version="%prog (AgileCLU "+AgileCLU.__version__+")")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="be verbose", default=False)
parser.add_option("-l", "--login", dest="username", help="use alternate profile")
parser.add_option("-r", "--recurse", action="store_true", help="recurse directories")
group = OptionGroup(parser, "Output options")
group.add_option("-b", "--bytes", action="store_true", help="include file size bytes")
group.add_option("-s", "--sizes", action="store_true", help="report things like bytes in human-readable format")
group.add_option("-u", "--url", action="store_true", help="include egress URLs")
group.add_option("-f", "--filehide", action="store_true", help="hide file objects")
group.add_option("-d", "--dirhide", action="store_true", help="hide directory objects")
parser.add_option_group(group)
""" Placeholder for using command line for profile information
profile = OptionGroup(parser, "Profile options")
profile.add_option("--username", dest="username", help="Agile username")
profile.add_option("--password", dest="password", help="Agile password")
profile.add_option("--iprotocol", dest="ingest_protocol", help="Agile ingest protocol", default="https")
profile.add_option("--ihostname", dest="ingest_hostname", help="Agile ingest hostname", default="api.agile.lldns.net")
profile.add_option("--eprotocol", dest="egress_protocol", help="Agile egress protocol", default="http")
profile.add_option("--ehostname", dest="egress_hostname", help="Agile egress hostname", default="global.mt.lldns.net")
profile.add_option("--ebase", dest="egress_basepath", help="Agile egress base path" )
parser.add_option_group(profile)
"""
(options, args) = parser.parse_args()
if len(args) != 1 and len(args) != 0: parser.error("Wrong number of arguments. Exiting.")
if len(args) == 0:
path = '/'
else:
path = args[0]
if options.username: agile = AgileCLU( options.username )
else: agile = AgileCLU()
# check that destination path exists
if (not agile.exists(path)):
if options.verbose: print "File or directory object (%s) does not exist. Exiting." % path
agile.logout()
sys.exit(1)
else:
class DirWalker(object):
def walk(self,path,meth):
dir = agile.listDir( path, 1000, 0, 1 )
dir['list'] = sorted(dir['list'], key=str)
for item in dir['list']:
itemurl = os.path.join(path,item['name'])
if not options.dirhide: print "["+itemurl+"]"
if not options.filehide: meth(itemurl)
self.walk(itemurl,meth)
def FileWalker(object):
fl = agile.listFile(object, 1000, 0, 1)
items = fl['list']
items = sorted( items, key=itemgetter('name'))
items = sorted( items, key=lambda x: x['name'].lower())
for item in items:
if options.url:
itemurl = "%s%s" % (agile.mapperurlstr(), urllib.quote(os.path.join( object, item['name'] )))
else:
itemurl = os.path.join(object,item['name'])
if options.bytes:
if options.sizes: itemurl += " "+sizeof_fmt(item['stat']['size'])
else: itemurl += " "+str(item['stat']['size'])+" bytes"
print itemurl
if options.recurse:
DirWalker().walk(path,FileWalker)
else:
dir = agile.listDir( path, 1000, 0, 1 )
dir['list'] = sorted(dir['list'], key=str)
for item in dir['list']:
itemurl = os.path.join(path,item['name'])
if not options.dirhide: print "["+itemurl+"]"
FileWalker(path)
agile.logout()
if __name__ == '__main__':
main() | AgileCLU | /AgileCLU-0.4.2.tar.gz/AgileCLU-0.4.2/bin/agilels.py | agilels.py |
from AgileCLU import AgileCLU
from optparse import OptionParser, OptionGroup
import sys, os.path, urllib, subprocess, time
from poster.encode import multipart_encode, get_body_size
from poster.streaminghttp import register_openers
from urllib2 import Request, urlopen, URLError, HTTPError
def main(*arg):
global fname
# parse command line and associated helper
parser = OptionParser( usage= "usage: %prog [options] object path", version="%prog (AgileCLU "+AgileCLU.__version__+")")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="be verbose", default=False)
parser.add_option("-l", "--login", dest="username", help="use alternate profile")
group = OptionGroup(parser, "Handling Options")
group.add_option("-r", "--rename", dest="filename", help="rename destination file")
group.add_option("-c", "--mimetype", dest="mimetype", help="set MIME content-type")
group.add_option("-t", "--time", dest="mtime", help="set optional mtime")
group.add_option("-e", "--egress", dest="egress", help="set egress policy (PARTIAL, COMPLETE or POLICY)", default="COMPLETE")
group.add_option("-m", "--mkdir", action="store_true", help="create destination path, if it does not exist")
group.add_option("-p", "--progress", action="store_true", help="show transfer progress bar")
parser.add_option_group(group)
config = OptionGroup(parser, "Configuration Option")
config.add_option("--username", dest="username", help="Agile username")
config.add_option("--password", dest="password", help="Agile password")
config.add_option("--mapperurl", dest="mapperurl", help="Agile MT URL base")
config.add_option("--apiurl", dest="apiurl", help="Agile API URL")
config.add_option("--posturl", dest="posturl", help="Agile POST URL")
parser.add_option_group(config)
(options, args) = parser.parse_args()
if len(args) != 2: parser.error("Wrong number of arguments. Exiting.")
object = args[0]
path = args[1]
if (not os.path.isfile(object)):
print "Local file object (%s) does not exist. Exiting." % object
sys.exit(1)
if options.username: agile = AgileCLU( options.username )
else: agile = AgileCLU()
localpath = os.path.dirname(object)
localfile = os.path.basename(object)
# check that destination path exists
if (not agile.exists(path)):
if options.mkdir:
r = agile.mkdir( path, 1 )
if (r):
if options.verbose: print "Destination path (%s) has been created. Continuing..." % path
else:
if options.verbose: print "Destination path (%s) failed to be created. Suggest trying --mkdir option. Exiting." % path
agile.logout()
sys.exit(2)
else:
if options.verbose: print "Destination path (%s) does not exist. Suggest --mkdir option. Exiting." % path
agile.logout()
sys.exit(1)
if options.filename: fname = options.filename
else: fname = localfile
if options.mimetype: mimetype = options.mimetype
else: mimetype = 'auto'
if options.progress: callback = agile.pbar_callback
else: callback = None
result = agile.post( os.path.join(localpath,localfile), path, fname, mimetype, None, options.egress, False, callback )
if options.verbose: print "%s%s" % (agile.mapperurlstr(),urllib.quote(os.path.join(path,fname)))
agile.logout()
if __name__ == '__main__':
main() | AgileCLU | /AgileCLU-0.4.2.tar.gz/AgileCLU-0.4.2/bin/agilepost.py | agilepost.py |
import AgileCLU, ConfigParser, sys, os, getpass, socket
from optparse import OptionParser, OptionGroup
config_path = os.path.expanduser( '~/.agileclu/' )
default_config = os.path.join( config_path, 'default.conf' )
config = ConfigParser.SafeConfigParser()
def delete_profile( profile ):
if not os.path.isfile( os.path.join( config_path, profile+'.conf' ) ):
print "The (%s) profile does not exist. Exiting." % ( profile )
else:
try:
os.unlink( os.path.join( config_path, profile+'.conf' ) )
except:
print "Failed to remove (%s) profile. Exiting." % (profile)
else:
print "The (%s) profile has been removed. Exiting." % (profile)
def view_profile( profile ):
if not os.path.isfile( os.path.join( config_path, profile+'.conf' ) ):
print "The (%s) profile does not exist. Exiting." % ( profile )
else:
with open ( os.path.join( config_path, profile+'.conf' ), 'r' ) as f:
read_data = f.read()
print read_data
def prompt( str, default, command, password=False ):
width=50
#if command=='modify':
if default<>'' and not password:
str += ' [%s]' % default
if password:
str += ' '
value = getpass.getpass(' '+str.rjust(width)+': ')
else:
print str.rjust(width),
value = raw_input(': ')
if value=='': value=default
return value
def edit_profile( profile, command ):
width = 50
if command=='modify':
if not os.path.isfile( os.path.join( config_path, profile+'.conf' ) ):
print "Profile (%s) does not exist. Try 'agileprofile create' first. Exiting." % (profile)
sys.exit(1)
if command=='create':
if os.path.isfile( os.path.join( config_path, profile+'.conf' ) ):
print "Profile (%s) already exists. You must use delete first, or use modify. Exiting." % (profile)
sys.exit(1)
username='' ; password=''
egress_protocol='http' ; egress_port='80' ; egress_hostname='global.mt.lldns.net' ; egress_basepath='' ;
ingest_protocol='https' ; ingest_port='443' ; ingest_hostname='api.agile.lldns.net'
elif command=='modify':
config.read( os.path.join( config_path, profile+'.conf' ) )
username=config.get( "Identity", "username" )
password=config.get( "Identity", "password" )
egress_protocol=config.get( "Egress", "protocol" )
egress_hostname=config.get( "Egress", "hostname" )
egress_port=config.get( "Egress", "port" )
egress_basepath=config.get( "Egress", "basepath" )
ingest_protocol=config.get( "Ingest", "protocol" )
ingest_hostname=config.get( "Ingest", "hostname" )
ingest_port=config.get( "Ingest", "port" )
ciphered = 0
print command.upper()+ " PROFILE: "+profile
try:
ok=0
while not ok:
username = prompt( 'Username', username, command )
ok = len(username)>=2
if not ok: print "Username has to be at least 3 characters."
if command=='modify':
password2 = password
password = prompt( 'Password', password, command, True )
if ( password != password2 ):
while (password != password2 ):
password = prompt( 'Password', '', command, True )
password2 = prompt( "Re-enter password", '', command, True )
else: ciphered=1
else:
password = "1" ; password2 = "2"
while (password != password2 ):
password = prompt( 'Password', password, command, True )
password2 = prompt( "Re-enter password", password2, command, True )
egress_port = "80"
egress_protocol = 'http'
""" Temporarily leave off https, since MTs are not presently configured for https, default http will be used
ok=0
while not ok:
egress_protocol = prompt( 'Egress protocol', egress_protocol, command ).lower()
ok = egress_protocol in ['http','https']
if not ok:
print "Supported protocols are 'http' and 'https'."
egress_protocol = 'http'
"""
ok=0
while not ok:
egress_hostname = prompt( 'Egress hostname', egress_hostname, command )
try:
addrinfo = socket.getaddrinfo( egress_hostname, egress_port )
ok = 1
except:
print "Egress hostname (%s) does not resolve correctly." % (egress_hostname)
ok = 0
egress_basepath = prompt( "Egress base path", egress_basepath, command )
ingest_protocol = 'https'
# ingest_protocol = prompt( 'Ingest protocol', ingest_protocol, command )
ingest_port = '80'
# ingest_port = prompt( 'Ingest port', ingest_port, command )
ok=0
while not ok:
ingest_hostname = prompt( 'Ingest hostname', ingest_hostname, command )
try:
addrinfo = socket.getaddrinfo( ingest_hostname, ingest_port )
ok = 1
except:
print "Ingest hostname (%s) does not resolve correctly." % (ingest_hostname)
ok = 0
if not ciphered:
cipher = AgileCLU.e_pw_hash( password, username, egress_protocol, egress_hostname, egress_basepath )
else:
cipher = password
except (KeyboardInterrupt, SystemExit):
print "\nAborting..."
sys.exit(1)
if command=='modify':
try:
os.unlink( os.path.join( config_path, profile+'.conf' ) )
except:
print "Failed to remove (%s) profile. Exiting." % (profile)
sys.exit(1)
config.remove_section('AgileCLU')
config.remove_section('Identity')
config.remove_section('Egress')
config.remove_section('Ingest')
config.remove_section('Logging')
config.add_section("AgileCLU")
config.set("AgileCLU", "version", AgileCLU.AgileCLU.__version__ )
config.add_section("Identity")
config.set("Identity", "username", username )
config.set("Identity", "password", cipher )
config.add_section("Egress")
config.set("Egress", "protocol", egress_protocol )
config.set("Egress", "port", egress_port )
config.set("Egress", "hostname", egress_hostname )
config.set("Egress", "basepath", egress_basepath )
config.add_section("Ingest")
config.set("Ingest", "port", ingest_port )
config.set("Ingest", "protocol", ingest_protocol )
config.set("Ingest", "hostname", ingest_hostname )
config.add_section("Logging")
config.set("Logging", "enabled", "no" )
config.set("Logging", "logfile", "/var/log/agileclu.log" )
config.set("Logging", "level", "info" )
config.write( open( os.path.join( config_path, profile+'.conf' ) , "w"))
print "\nProfile (%s) has been" % (profile),
if command=='modify':
print "updated.",
else:
print "saved.",
print " Exiting.\n"
def list_profile():
print "List Profiles\n-------------"
profiles = os.listdir( os.path.expanduser(config_path) )
if len(profiles)==0:
print "You do not have any profiles. Use \"create\" to make one.\n"
for profile in profiles:
print profile.replace('.conf','')
def main(*arg):
parser = OptionParser(
usage= "usage: %prog create|delete|modify|list [profile]",
version="%prog (AgileCLU "+AgileCLU.AgileCLU.__version__+")")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="be verbose", default=False)
(options, args) = parser.parse_args()
if len(args) < 1 or len(args) > 2: parser.error("Wrong number of arguments. Use -h for more information.")
command = args[0].lower()
if len(args)==2:
profile = args[1].lower()
else:
profile = 'default'
if not os.path.isdir( config_path):
try:
os.mkdir( config_path, 0700 )
except OSError:
print "Failed to create profile directory (%s). Please check permissions." % (config_path)
print "\n" + os.path.basename(__file__) + " (AgileCLU "+AgileCLU.AgileCLU.__version__+")\n"
if not command in ['create','delete','modify','list', 'view' ]:
parser.error("You must use create, delete, modify or list. Exiting.")
if command=='list': list_profile()
if command=='view': view_profile( profile )
if command=='create': edit_profile( profile, command )
if command=='modify': edit_profile( profile, command )
if command=='delete': delete_profile( profile )
if __name__ == '__main__':
main() | AgileCLU | /AgileCLU-0.4.2.tar.gz/AgileCLU-0.4.2/bin/agileprofile.py | agileprofile.py |
# Agilize
[](https://badge.fury.io/py/Agilize)
[](https://coveralls.io/github/lucasrcezimbra/agilize?branch=master)
Unofficial client to access [Agilize](https://www.agilize.com.br/).
## Installation
```bash
pip install agilize
```
## How to Use
High-level API
```python
from agilize import Agilize, Competence
agilize = Agilize(username='11222333000160', password='p4ssw0rd')
companies = agilize.companies()
for company in companies:
print(company)
company = companies[0]
competence = Competence(year=2022, month=5)
prolabore = company.prolabores.get(competence)
print(prolabore)
with open(f'./prolabore_{competence}.pdf', 'wb') as f:
f.write(prolabore.download())
```
Low-level API
```python
from agilize import Client
agilize = Client(username='11222333000160', password='p4ssw0rd')
print(agilize.info)
company_id = agilize.info['party']['companies'][0]['__identity']
agilize.prolabores(company_id=company_id, year=2022)
```
## Contributing
Contributions are welcome, feel free to open an Issue or Pull Request.
Pull requests must be for the `develop` branch.
```bash
git clone https://github.com/lucasrcezimbra/agilize
cd agilize
git checkout develop
python -m venv .venv
pip install -r requirements-dev.txt
pre-commit install
pytest
```
| Agilize | /Agilize-0.0.4.tar.gz/Agilize-0.0.4/README.md | README.md |
# Changelog
## 0.0.4 (2022-07-15)
- BREAKING CHANGE: Rename Client.download_paycheck to download_prolabore
- BREAKING CHANGE: Update Client.PATH_*
- Add taxes with download
- Add Client.invoices
- Add script to help fixture generation
- Update dev dependencies
- faker 13.14.0 ~> 13.15.0
- pre-commit 2.19.0 ~> 2.20.0
- pytest-mock 3.8.1 ~> 3.8.2
## 0.0.3 (2022-06-25)
- Add pro-labore download
* add Client.download_paycheck
- Create high-level API
- Update requirements-dev
## 0.0.2 (2022-04-17)
- First version - authentication and prolabores
| Agilize | /Agilize-0.0.4.tar.gz/Agilize-0.0.4/CHANGELOG.md | CHANGELOG.md |
import requests
from agilize.keycloak import Keycloak
class Client:
AUTH_URL = 'https://sso.agilize.com.br/auth/'
CLIENT_ID = 'agilize-legacy-client'
REALM_NAME = 'AgilizeAPPs'
URL_API = 'https://app.agilize.com.br/api/v1/'
PATH_DOWNLOAD_PROLABORE = 'companies/{company_id}/prolabore-anual/download'
PATH_DOWNLOAD_TAX = 'companies/{company_id}/taxes/{tax_id}/billet'
PATH_INFO = 'companies/security-user/info'
PATH_INVOICES = 'companies/{company_id}/invoices'
PATH_PARTNERS = 'companies/{company_id}/partners'
PATH_PROLABORE = 'companies/{company_id}/prolabore-anual'
PATH_TAXES = 'companies/{company_id}/taxes'
def __init__(self, username, password, keycloak=None):
self.username = username
self.password = password
self.keycloak = keycloak or Keycloak(self.AUTH_URL, self.CLIENT_ID, self.REALM_NAME)
self._access_token = None
self._info = None
@property
def access_token(self):
if not self._access_token:
token = self.keycloak.token(self.username, self.password)
self._access_token = token['access_token']
return self._access_token
@property
def info(self):
if not self._info:
response = requests.get(
url=self.url(self.PATH_INFO),
headers=self.headers,
)
self._info = response.json()
return self._info
@property
def headers(self):
return {'Authorization': f'Bearer {self.access_token}'}
def partners(self, company_id):
response = requests.get(
url=self.url(self.PATH_PARTNERS, company_id=company_id),
headers=self.headers,
)
return response.json()
def prolabores(self, company_id, year):
response = requests.get(
url=self.url(self.PATH_PROLABORE, company_id=company_id),
params={'anoReferencia': f'{year}-01-01T00:00:00P'},
headers=self.headers,
)
return response.json()
def download_prolabore(self, company_id, partner_id, year, month):
response = requests.get(
url=self.url(self.PATH_DOWNLOAD_PROLABORE, company_id=company_id),
params={
'competence': f'{year}-{month}-01T00:00:00-0300',
'partner': partner_id,
},
headers=self.headers,
)
return response.content
def taxes(self, company_id, year):
response = requests.get(
url=self.url(self.PATH_TAXES, company_id=company_id),
params={
'blocking': True,
'closed': True,
'count': 3000,
'direction': 'desc',
'onlyTaxesNotProvisionedByRh': True,
'page': 1,
'sort': 'companyTax.competence',
'year': year,
},
headers=self.headers,
)
return response.json()
def download_tax(self, company_id, tax_id):
response = requests.get(
url=self.url(self.PATH_DOWNLOAD_TAX, company_id=company_id, tax_id=tax_id),
headers=self.headers,
)
file_url = response.json()['url']
return requests.get(file_url).content
def invoices(self, company_id, year):
response = requests.get(
url=self.url(self.PATH_INVOICES, company_id=company_id),
params={
'count': 3000,
'page': 1,
'year': year,
},
headers=self.headers,
)
return response.json()
@classmethod
def url(cls, path, **kwargs):
return cls.URL_API + path.format(**kwargs) | Agilize | /Agilize-0.0.4.tar.gz/Agilize-0.0.4/agilize/client.py | client.py |
from collections import defaultdict
from decimal import Decimal
from typing import Optional
from attrs import define, field
from agilize.client import Client
class Agilize:
def __init__(self, username, password, client=None):
self.client = client or Client(username, password)
def companies(self):
return [
Company.from_data(c, self.client)
for c in self.client.info['party']['companies']
]
@define(kw_only=True)
class Prolabores:
client: Client
company_id: str
_prolabores: dict = field(factory=dict)
def get(self, competence):
if competence not in self._prolabores:
self.fetch(competence.year)
return self._prolabores[competence]
def fetch(self, year):
# TODO: implement multiple partners
data_by_date = self.client.prolabores(self.company_id, year)
for datas in data_by_date.values():
if not isinstance(datas, list):
continue
for d in datas:
if not d['contraCheque']:
continue
prolabore = Prolabore.from_data(d, self.company_id, self.client)
self._prolabores[prolabore.competence] = prolabore
def __iter__(self):
yield from self._prolabores.values()
@define(kw_only=True)
class Taxes:
client: Client
company_id: str
_taxes_by_competence: defaultdict = field(factory=lambda: defaultdict(dict))
def get(self, abbreviation, competence):
if competence not in self._taxes_by_competence:
self.fetch(competence.year)
return self._taxes_by_competence[competence][abbreviation]
def fetch(self, year):
data = self.client.taxes(self.company_id, year)
for d in data:
tax = Tax.from_data(d, self.company_id, self.client)
self._taxes_by_competence[tax.competence][tax.abbreviation] = tax
def filter(self, competence):
if competence not in self._taxes_by_competence:
self.fetch(competence.year)
return list(self._taxes_by_competence[competence].values())
def __iter__(self):
for t in self._taxes_by_competence.values():
yield from t.values()
@define
class Company:
id: str
cnpj: str
name: str
client: Client
_prolabores: Optional[Prolabores] = None
_taxes: Optional[Taxes] = None
@classmethod
def from_data(cls, data, client):
return cls(
id=data['__identity'],
cnpj=data['cnpj'],
name=data['name'],
client=client,
)
@property
def prolabores(self):
if not self._prolabores:
self._prolabores = Prolabores(client=self.client, company_id=self.id)
return self._prolabores
@property
def taxes(self):
if not self._taxes:
self._taxes = Taxes(client=self.client, company_id=self.id)
return self._taxes
@define(hash=True)
class Competence:
year: int
month: int
@classmethod
def from_data(cls, data):
year, month, *_ = data.split('-')
return cls(year=int(year), month=int(month))
def __str__(self):
return f'{self.year:04d}{self.month:02d}'
@define
class Prolabore:
client: Client
company_id: str
competence: Competence
inss: Decimal
irpf: Decimal
net_value: Decimal
partner_id: str
paycheck_id: str
total_value: Decimal
@classmethod
def from_data(cls, data, company_id, client):
return cls(
client=client,
company_id=company_id,
competence=Competence.from_data(data['competence']),
inss=data['iNSS'],
irpf=data['iRPJFolha'],
net_value=data['valorLiquido'],
partner_id=data['partner']['__identity'],
paycheck_id=data['contraCheque']['__identity'],
total_value=data['valor'],
)
def download(self):
return self.client.download_prolabore(
self.company_id,
self.partner_id,
self.competence.year,
self.competence.month,
)
@define
class Tax:
client: Client
abbreviation: str
company_id: str
competence: Competence
id: str
@classmethod
def from_data(cls, data, company_id, client):
return cls(
abbreviation=data['taxAbbreviation'],
client=client,
company_id=company_id,
competence=Competence.from_data(data['competence']),
id=data['__identity'],
)
def download(self):
return self.client.download_tax(self.company_id, self.id) | Agilize | /Agilize-0.0.4.tar.gz/Agilize-0.0.4/agilize/agilize.py | agilize.py |
# Aglyph - Dependency Injection for Python
http://ninthtest.info/aglyph-python-dependency-injection/
[](https://pypi.python.org/pypi/Aglyph)



[](https://pypi.python.org/pypi/Aglyph)
## Introduction
Aglyph is a Dependency Injection framework for Python that...
* supports type 2 (setter) and type 3 (constructor) dependency injection
* can assemble *prototype*, *singleton*, *borg*, and *weakref* components
* supports templates (i.e. component inheritance) and lifecycle methods
* works with any kind of object creation pattern you'll encounter:
* constructor
* factory function or method
* object creation hidden behind attribute or property access
* is configured declaratively, either programmatically through a fluent API or
using a simple XML syntax (see the [Aglyph DTD](
https://github.com/mzipay/Aglyph/blob/master/resources/aglyph-context.dtd))
* is non-intrusive:
* only one dependency ([Autologging](
http://ninthtest.info/python-autologging/)) beyond the Python standard
library
* does not require modification of existing source code (i.e. no
decorators, specific naming conventions, or any other kind of
syntactic "magic" necessary)
* can inject not only 3rd-party dependencies, but also **dependents**
* runs on Python 2.7 and 3.4+ using the same codebase
* is proactively tested on [CPython](https://www.python.org/),
[Jython](http://www.jython.org/), [IronPython](http://ironpython.net/),
[PyPy](http://pypy.org/>), and
[Stackless Python](https://github.com/stackless-dev/stackless)
* is fully logged *and traced* for ease of troubleshooting (note: tracing is
disabled by default, and can be activated by setting an environment variable)
## Installation
The easiest way to install Aglyph is to use [pip](https://pip.pypa.io/):
```bash
$ pip install Aglyph
```
To verify that an installation was successful:
```python
>>> import aglyph
>>> aglyph.__version__
'3.0.0'
```
After installing, take a look at [Getting started with Aglyph](
http://aglyph.readthedocs.io/en/latest/get-started.html) and the
[Aglyph cookbook](http://aglyph.readthedocs.io/en/latest/cookbook.html).
Alternative source and binary installation options are described below.
### Source installation
Clone or fork the repository:
```bash
$ git clone https://github.com/mzipay/Aglyph.git
```
Alternatively, download and extract a source _.zip_ or _.tar.gz_ archive
from https://github.com/mzipay/Aglyph/releases,
https://pypi.python.org/pypi/Aglyph/ or
https://sourceforge.net/projects/aglyph/files/aglyph/.
Run the test suite and install the `aglyph` package:
```bash
$ cd Aglyph
$ python setup.py test
$ python setup.py install
```
### Binary installation
Download the Python wheel (_.whl_) or _.exe_/_.msi_ Windows installer
from https://pypi.python.org/pypi/Aglyph/ or
https://sourceforge.net/projects/aglyph/files/aglyph/.
Use [pip](https://pip.pypa.io/) or
[wheel](https://pypi.python.org/pypi/wheel) to install the _.whl_, or
run the Windows installer.
| Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/README.md | README.md |
Search.setIndex({docnames:["aglyph","aglyph.assembler","aglyph.component","aglyph.context","aglyph.integration.cherrypy","api-ref","context-fluent-api","cookbook","cookbook-common","cookbook-configuration","cookbook-integration","cookbook-notable","cookbook-templating","cookbook-understanding","get-started","index","roadmap","testing","testing-1_1_0","testing-1_1_1","testing-2_0_0","testing-2_1_0","testing-2_1_1","whats-new","whats-new-1_1_0","whats-new-1_1_1","whats-new-2_0_0","whats-new-2_1_0","whats-new-2_1_1"],envversion:53,filenames:["aglyph.rst","aglyph.assembler.rst","aglyph.component.rst","aglyph.context.rst","aglyph.integration.cherrypy.rst","api-ref.rst","context-fluent-api.rst","cookbook.rst","cookbook-common.rst","cookbook-configuration.rst","cookbook-integration.rst","cookbook-notable.rst","cookbook-templating.rst","cookbook-understanding.rst","get-started.rst","index.rst","roadmap.rst","testing.rst","testing-1_1_0.rst","testing-1_1_1.rst","testing-2_0_0.rst","testing-2_1_0.rst","testing-2_1_1.rst","whats-new.rst","whats-new-1_1_0.rst","whats-new-1_1_1.rst","whats-new-2_0_0.rst","whats-new-2_1_0.rst","whats-new-2_1_1.rst"],objects:{"":{Context:[6,0,1,""],_ComponentBuilder:[6,0,1,""],_TemplateBuilder:[6,0,1,""],aglyph:[0,1,0,"-"]},"aglyph.assembler":{Assembler:[1,0,1,""]},"aglyph.assembler.Assembler":{__contains__:[1,3,1,""],assemble:[1,3,1,""],clear_borgs:[1,3,1,""],clear_singletons:[1,3,1,""],clear_weakrefs:[1,3,1,""],init_borgs:[1,3,1,""],init_singletons:[1,3,1,""]},"aglyph.component":{Component:[2,0,1,""],Evaluator:[2,0,1,""],LifecycleState:[2,5,1,""],Reference:[2,0,1,""],Strategy:[2,5,1,""],Template:[2,0,1,""]},"aglyph.component.Component":{dotted_name:[2,4,1,""],factory_name:[2,4,1,""],member_name:[2,4,1,""],strategy:[2,4,1,""]},"aglyph.component.Evaluator":{__call__:[2,3,1,""],factory:[2,4,1,""]},"aglyph.component.Template":{after_inject:[2,4,1,""],before_clear:[2,4,1,""],parent_id:[2,4,1,""],unique_id:[2,4,1,""]},"aglyph.context":{Context:[3,0,1,""],XMLContext:[3,0,1,""]},"aglyph.context.Context":{borg:[3,3,1,""],component:[3,3,1,""],get_component:[3,3,1,""],iter_components:[3,3,1,""],prototype:[3,3,1,""],register:[3,3,1,""],singleton:[3,3,1,""],template:[3,3,1,""],weakref:[3,3,1,""]},"aglyph.context.XMLContext":{default_encoding:[3,4,1,""]},"aglyph.context._ContextBuilder":{borg:[6,3,1,""],component:[6,3,1,""],prototype:[6,3,1,""],singleton:[6,3,1,""],template:[6,3,1,""],weakref:[6,3,1,""]},"aglyph.context._CreationBuilderMixin":{create:[6,3,1,""]},"aglyph.context._InjectionBuilderMixin":{init:[6,3,1,""],set:[6,3,1,""]},"aglyph.context._LifecycleBuilderMixin":{call:[6,3,1,""]},"aglyph.context._RegistrationMixin":{register:[6,3,1,""]},"aglyph.integration":{cherrypy:[4,1,0,"-"]},"aglyph.integration.cherrypy":{AglyphDIPlugin:[4,0,1,""]},"aglyph.integration.cherrypy.AglyphDIPlugin":{assemble:[4,3,1,""],clear_borgs:[4,3,1,""],clear_singletons:[4,3,1,""],clear_weakrefs:[4,3,1,""],eager_init:[4,4,1,""],init_borgs:[4,3,1,""],init_singletons:[4,3,1,""],start:[4,3,1,""],stop:[4,3,1,""]},aglyph:{AglyphError:[0,2,1,""],assembler:[1,1,0,"-"],component:[2,1,0,"-"],context:[3,1,0,"-"],format_dotted_name:[0,6,1,""],resolve_dotted_name:[0,6,1,""]}},objnames:{"0":["py","class","Python class"],"1":["py","module","Python module"],"2":["py","exception","Python exception"],"3":["py","method","Python method"],"4":["py","attribute","Python attribute"],"5":["py","data","Python data"],"6":["py","function","Python function"]},objtypes:{"0":"py:class","1":"py:module","2":"py:exception","3":"py:method","4":"py:attribute","5":"py:data","6":"py:function"},terms:{"0_05":21,"0_161":17,"0_162":17,"0_17":[19,20],"0_25":21,"0_26":18,"0_27":18,"0_43":19,"0_51":22,"0_55":21,"0_65":20,"0b2":17,"0x000000000000002b":11,"1b3":[17,19,20,21,22],"32bit":[17,19,20,21,22],"3rd":[7,8],"64bit":[17,18,19,20,21,22],"\u03b1\u03c6\u03b4":9,"abstract":2,"break":6,"byte":[3,9],"case":[2,3,6,8,11,12,14],"class":[0,1,2,3,4,6,7,9,10,12,13,14,15,23,26,27],"default":[0,1,2,3,6,9,11,12,14,20,21,23,26],"final":[6,8,14],"float":12,"function":[0,2,3,4,7,11,12,14,23,26,27],"import":[0,2,4,6,8,9,10,11,12,13,14,15,26],"int":[8,9,11,12],"long":[1,2,15],"new":[0,1,2,3,4,6,9,13,14,15],"public":[23,26,27],"return":[0,1,2,3,4,6,8,11,12,14,15],"short":[6,9],"static":7,"super":2,"true":[1,2,4,11,12],"try":14,"var":8,"while":[1,8,12,14],AND:1,Adding:13,And:[8,9],Bus:[4,10],But:[2,6,11],EXE:14,For:[1,2,3,6,8,9,10,11,14],IDs:[1,3,4,8,11],Into:14,Its:2,NOT:6,OPE:8,One:9,Such:[2,14],That:9,The:[0,2,3,4,5,8,9,10,11,12,13,14,15,16,17,19,20,21,22,23,24,26,27,28],There:[6,8,11,14,16],These:[6,11,12,14,16],Use:[7,9,26],Using:[7,15],With:[1,11],_20:[19,20],_23:[19,20],_24:21,_25:[17,21,22],_64:[17,19,20,21,22],__builtin__:8,__call__:2,__class__:11,__contains__:1,__del__:14,__dict__:[1,2],__init__:[14,15],__name__:0,__qualname__:0,__setitem__:3,__slots__:[1,2],__version__:[14,15],_apple_inc:[19,20],_bind:26,_client_vm:[19,20,21,22],_compat:[0,11,23],_componentbuild:6,_contextbuild:[3,6],_creationbuildermixin:6,_db:14,_dependencysupport:2,_finder:14,_genuineintel:17,_import:[2,6],_initializationsupport:2,_injectionbuildermixin:6,_lifecyclebuildermixin:6,_movi:14,_oracle_corpor:[17,19,20,21,22],_registrationmixin:6,_templatebuild:6,abil:2,abl:14,about:[11,13,14,16],abov:[2,3,9,14],absolut:[0,13,14],acal:11,accept:[8,11,14],access:[2,6,8,11,13],accommod:2,accompani:26,accomplish:[8,12,14],accord:[0,2,4,13,14,24],accordingli:[1,8],account:9,achiev:2,acquir:[1,14],across:[8,13],act:13,activ:[0,14,23,26,27,28],activest:14,actual:[1,2,6,8,9,11,14,26],adapt:13,add:[3,6,9,15],added:[2,6,14,25,27],addhandl:8,adding:14,addit:[12,14],addition:8,addrefer:11,address:[8,11,12],advantag:14,affect:9,aforement:26,after:[1,2,3,4,6,7,12,14,27],after_inject:[2,3,6,8,12],again:[2,6,11],against:[9,17,20,21,22,28],aglpyh:27,aglyph:[8,12,16,24,25,26,27,28],aglyph_trac:[0,23],aglyphdeprecationwarn:27,aglyphdiplugin:[4,7],aglypherror:[0,1,2,3,8],agre:16,alex:[14,15],algpyh:10,alia:2,all:[0,1,2,3,4,6,8,9,14,15,23,24,26],allow:[2,8,10,11,12,14,28],almost:[8,9,16],along:[5,14],alreadi:[1,2,3,10,14],also:[2,6,8,9,11,12,14],altern:[3,8,9,10,15,16],althoug:9,although:[3,8],alwai:[1,2,9,14,15],ambigu:9,amd64:[17,21],america:14,american:14,ani:[1,2,6,7,9,11,12,14,16,26],anoth:[2,3,6,7,11,13,14],anotherobject:8,anti:16,anyth:[2,26],api:[3,4,7,13,14,15,23,26],app:[11,14],app_fluent:14,app_xml:14,appconfig:11,appear:8,append:[2,9,12,14],appl:[9,17,19,20,21,22],appli:[2,8,14],applic:[1,2,4,7,8,9,11,12,15,25,26],approach:[3,7,8,14,15,24,25,26],appropri:[2,8,14],apr:21,arbitrarili:2,archiv:14,arg:[2,6,8,10,11,12,14],argument:[1,2,3,6,8,11,12,14,26],articl:[11,14],ascii:[2,9],asctim:8,ask:[11,14],aspect:[6,14],assemb:4,assembl:[2,3,4,5,6,7,9,10,11,12,13,15,27],assign:[1,2,6,8,10],assmebl:2,assum:[1,2,6,8,12,14],ast:23,attempt:[0,1,2,3],attribut:[0,1,2,3,6,8,9,10,11,12,13,14,26],autolog:[0,23],automat:[1,2,4,6,7,8,11,14],avail:[0,1,11,14],avoid:[7,9,26],awar:[1,7],b01:[19,20],b02:21,b03:[21,22],b04:20,b14:17,back:14,backupcount:8,base:[0,1,2,3,4,12,14,16,17,20,21,22],basehttprequesthandl:11,basi:[2,6],basic:14,becaus:[1,2,8,9,11,13,14],becom:23,been:[1,2,3,4,6,7,12,14,15,23,26,27],befor:[2,3,4,6,7,9,11,12,14,27],before_clear:[1,2,3,6,8,12],begin:[6,14,26],behalf:2,behav:12,behavior:[1,2,8,9,12,14,23],being:[6,8,14,17,20,21,22],belong:[8,26],below:[2,5,8,11,12,13],benefit:14,besid:12,best:14,better:26,between:[8,11,12,13],beyond:14,bind:[8,9,10,11,12],binder:[4,11,23,24,26],bit:[9,16,17,19,20,21,22],bit_server_vm:[17,19,20,21,22],block:1,bool:4,bootstrap:10,borg:[1,2,3,4,6,7,10,15],both:[2,9,11,13,14,27],bound:[14,16],breakfast:14,brief:15,brows:14,bucket:16,bueller:14,build:[11,14,17,19,20],builder:3,built:[0,23],builtin:[1,2,7,28],bus:[4,10],busi:13,bypass:2,c856cc204b1c:21,cach:[1,2,3,4,6,7,12,23,27],calibr:12,call:[1,2,3,6,7,9,11,12,14,26],callabl:[2,6,8,11,14],caller:[1,2,6,8,12],can:[1,2,3,4,6,7,8,9,10,11,12,14,15,23],candl:14,cannot:[1,2,6,8,12],capabl:[6,8,14],capacitor:11,capacitor_dr:11,capacitordr:11,care:8,carefulli:14,caught:[1,2],caus:[0,1,2,8],cea13d5e707f:21,certain:3,certainli:9,cgi:12,cgi_serv:12,cgihttprequesthandl:12,chain:[6,9,14],chang:[2,7,8,9,15,17,19,20,21,22,26],channel:[0,2,4,9,10],charact:[2,3,7],check:14,cherrypi:[5,7,15,27],child:[7,14],choos:[7,11,14,15],circular:[1,7],clang:[9,17,21,22],clariti:9,classmethod:[2,11,26],classnam:6,classpath:11,clear:[1,2,3,4,7,10,12,27],clear_borg:[1,2,4,11],clear_singleton:[1,2,4,11,12],clear_weakref:[1,2,4,8,11],cli:[17,19,20,21,22],client:[2,8,19,20,21],clo:8,close:[8,14],clr:11,clrxmlparser:11,club:14,code:[6,7,9,10,11,14,24,26],codec:9,collect:[2,3,11,14],collector:[1,2],colon:14,colossu:14,com:14,combin:[2,6,14],come:16,command:14,comment:[14,15,24],commit:[14,16,17,20,21,22],common:[2,7,15],commun:16,comon:8,compar:14,compat:[8,9,13,17,21,22,23,25,26],complet:[1,4,14,15],compon:[4,5,7,9,14,15,26,27,28],component_id:[2,3,9,13],component_id_spec:[3,6],component_spec:[1,4],compoon:14,concept:11,conceptu:13,concis:24,concret:14,condit:[0,3],config:[0,10,11],configpars:16,configur:[0,2,3,4,6,7,14,15,16,23,24,26],configut:14,conform:[3,9,14],conn:14,connect:14,consequ:[11,14],consid:[2,6,8,9,11],consist:[2,5,6],constraint:3,constructor:[1,2,14,15],contain:[2,12,14,15],content:[3,9],context:[1,2,4,5,7,8,10,11,12,13,14,15,23,26,27],context_id:3,continu:2,control:[1,10,13,14,15],convers:7,convert:[1,6,14],conx:8,cookbook:[6,8,9,11,12,14,15,26],coookbook:12,copi:8,copyright:[9,14],corpor:[17,19,20,21],correct:9,correspond:[2,9,14],cost:[8,14],could:[6,8,9,10,14],coupl:10,cours:14,cover:14,cpython:[2,7,15],creat:[1,2,3,8,9,10,11,12,14,15,26],creation:[2,16],credit:[9,14],cross:[8,26],crucial:6,cumul:[6,23,26],current:[1,4,23],cursor:14,custom:[0,7,8,10,12],custom_serv:12,dai:14,danger:23,darwin:[9,17,18,19,20,21,22],data1:9,data2:9,data:[3,9,14,27],databas:14,date:8,dbm:8,dbname:14,deactiv:0,deal:9,debat:9,dec:9,decid:14,declar:[3,7,14,15,26,27],declat:1,def:[11,12,14],default_encod:[3,9],default_serv:12,defer:[7,9],defin:[0,1,5,8,9,11,14,15,27],definit:[1,2,3,6,8,12,14,15],delim:14,delimit:14,delorean:11,demonstr:[6,8,11,14,25,26],depdend:[6,14],depend:[1,3,4,5,7,9,11,13],deprec:[23,26,27],depth:12,descib:2,describ:[0,2,7,13,14],descript:[2,14],design:[8,14],desir:[8,14],desktop:21,destroi:[1,2],detail:[1,2,8,9,10,11,13,14,23,24],detect:[8,26],determin:[1,2,6,8,12,14],develop:[9,11,12,14],dict:[2,3,6,8,9],dictionari:[2,6,11],did:14,differ:[2,6,8,11,12,14],direct:[11,14],directli:[1,2,3,6,11,14],director:14,directori:[3,14],disabl:23,disappear:1,discard:2,discuss:14,disdain:16,disengag:12,disk:8,dispatch:10,dispos:2,distribut:[3,13],dive:14,doc:26,document:[1,2,3,8,9,10,11,12,14,24,25,26,28],doe:[0,1,2,3,7,11,12,14,16,17,20,21,22],doesn:[6,13,14],domain:14,don:[13,14],dot:[0,1,2,3,4,8,10,11,12,13,14,15,19,20,26],dotnet:11,dotted_nam:[0,2,6,11,13,14],download:15,drive:11,dtd:[3,9,11,14,15,27],dtdprocess:11,dure:[1,3,8,9,12,14],dynam:2,each:[2,6,8,9,11,12,14,17,20,21,22],eager:4,eager_init:4,eagerli:1,earlier:[6,14],easi:[9,13],easier:[3,14],easiest:6,easili:14,edg:3,effect:[2,6,10,14,26],egg:8,either:[1,2,4,6,8,9,11,12,13,14],element:[3,8,9,11,14,26],elementtre:[3,11,26],els:[1,3,11],embrac:9,emit:[2,9],empti:[0,1,2],enabl:[0,2,11,23],encod:[2,3,8,10,11,12,14],encount:[2,3,8,11,16],encourag:9,end:[17,19,20,21,22,23,26,27,28],enforc:3,engin:[4,10],ensur:27,entir:9,entri:[1,3,14],environ:[0,10,23],equipmentfoundri:11,equival:[2,6,11,14],error:[0,2,9,14],etre:[3,11,26],eval:[23,26],evalu:[2,3,7,9],even:[1,2,11,13,16],event:4,everi:[8,9,14,15],everyth:14,evict:[1,4,6,8,11],examin:[2,14],exampl:[1,2,4,6,7,8,9,10,12,14,25,26,27],example1:9,example2:9,exampleobject:6,except:[0,1,2,6,14],exclus:[2,6,16],execut:[11,13,14,17,19,20,21,22],exercis:[1,14],exhibit:[1,2],exist:[2,3,8,13,14],expand:26,expat:11,expect:[3,14],experiment:11,expicit:6,explain:[11,14],explan:[1,2,6],explicit:[1,2,6,8],explicitli:[2,6,8,9,10,11,26],explor:14,expos:[2,6],extend:[6,7],extern:14,extinguish:12,extract:15,extrem:[3,8],fact:14,factori:[2,6,7,11,14,16],factory_nam:[1,2,11,13,26],fail:[0,17,20,21,22],fair:9,fals:1,familiar:14,fanci:9,fast:8,favor:23,fc24:22,fc27:17,featur:[7,14,15],feb:20,fedora:[17,22],feel:14,ferri:14,ff29dd4f67de:21,fictiti:11,field:11,file:[8,10,11,14],filenam:[3,14,15],filesystemload:10,filter:3,find:[2,6,14],find_al:14,finder:14,finer:14,first:[2,9,14],fix:28,flag:4,flexibl:[8,14],fluent:[3,4,7,14,15,23],flux_capacitor_with_dr:11,flux_capacitor_without_dr:11,fluxcapacitor:11,fly:8,focus:14,follow:[0,1,2,3,4,6,8,9,11,12,14,15],food:8,forc:9,forget:9,form:[12,27],format_dotted_nam:[0,1,26],formatt:8,former:8,found:[2,14],framework:[0,7,11,15],free:[1,2],fresh:9,from:[0,1,2,3,4,6,7,9,10,11,12,13,16,17,20,21,22],frown:8,frozen:2,frozenset:8,full:14,fulli:[0,8,11,12,14,23],func:[2,8,11],functool:[2,8,9,12],further:[6,14],fuss:13,futur:15,garbag:[1,2],gcc:[9,14,17,19,20,21,22],gdbm:8,gener:[2,3,7,8,15,25],georg:14,get:[8,9,15,26],get_compon:3,get_default_capacitor_dr:11,getdefaultencod:[3,9],getlogg:8,getrespons:8,git:14,give:[8,14],given:[6,8,11,12],gnu:8,goal:14,graffiti:14,grammar:14,great:9,guarante:[1,2,8],guard:9,guidelin:[14,15],hand:14,handl:[4,9,23],handler:[0,8,11,12],happili:13,has:[1,2,3,6,9,10,11,12,14,15,17,19,20,21,22,23,26,27,28],has_importable_dotted_nam:26,hash:11,hat:[14,17,22],have:[0,1,2,3,4,6,7,9,11,12,14,16,23,26,27],header:15,held:1,help:[9,11,14],here:[6,8,11,14,16],hierarchi:6,hold:14,holder:14,home:[8,17],homogen:14,hotspot:[17,19,20,21],how:[1,2,8,9,10,11,12,14],howev:[0,2,9,11,12,14],http:[2,3,8,11,12,14],httpconnect:[2,8],httpd:11,httpserver:[11,12],hugh:14,hydrospann:12,hyperlink:28,i386:[17,18,19,20,21,22],ident:[6,14],identifi:[0,1,2,3,6,8,11,14],identify_by_spec:26,ignit:12,ignor:[2,6,9,11],ignorecom:11,ignoreprocessinginstruct:11,ignorewhitespac:11,illustr:[9,11],immedi:[2,3,6],immut:28,impl:14,implement:[2,3,6,7,8,9,12,13,14,17,20,21,22,23,26,27],impli:[8,14,17,20,21,22],implicitli:[2,6],importantli:14,improv:[8,15,25,26],inc:[19,20],incendiari:12,includ:[2,3,9,11,14,15,16,24,26],increas:8,index:15,indic:3,individu:11,infinit:8,influenc:11,info:[2,8],inform:[9,13,14],inherit:[1,2,6,7,8,15,27],init:[4,6,8,10,11,12,14,26],init_borg:[1,4],init_singleton:[1,4],initi:[1,2,3,4,6,8,11,12,14],initil:12,inject:[1,2,3,4,5,6,7,9,11,12,13,27],insert:[11,14],instal:15,instanc:[1,2,3,6,8,9,10,11,14,15],instanti:6,instead:[0,2,3,6,8,9,11,14],instruct:[2,9],integr:[5,7,15,27],intel64_family_6_model_94_stepping_3:17,intel:[20,21,22],intend:[2,9],interest:14,intern:[1,2,6,8,15,23],interpret:[9,14],interven:1,introduc:27,introduct:15,introspect:15,intrus:14,invers:[0,14,15],invert:14,ipyetre:26,ironpython:[7,15,26],iso:[8,9],issu:[1,2,27,28],item:[2,8,16],iter_compon:3,its:[1,2,4,6,7,11,12,14,17,20,21,22],itself:[2,9,11,14],jan:[20,21],jar:11,java1:[17,21],java9:17,java:[7,13,16,17,18,19,20,21,22],java_hotspot:[17,19,20,21,22],jinja2:10,jinja2tool:10,jinja:10,john:14,json:16,jul:21,just:[8,9,10,11,14],jython:[7,14,15,16],kei:[1,8,11,14],keyerror:1,keyword:[1,2,6,8,11,12,14],kind:[6,8],know:[6,9,13],languag:13,last:9,later:6,latest:14,latter:8,layer:13,lazi:2,lazili:3,lead:[8,9],leak:8,least:[1,2,3,14,15,16],left:3,leon:14,let:[14,15],level:[0,2,5,8,9,26,27],levelnam:8,librari:[7,8,11],licens:[9,14],life:[17,20,21,22],lifecycl:[1,2,7,8,11,27],lifecyclest:2,lifecyl:2,lifecylc:2,lifespan:[17,19,20,21,22,23,26,27,28],lifetim:[1,12],like:[2,3,6,8,9,10,11,13,14],limit:[11,12],line:[6,14],link:1,linkedhashmap:7,linux:[14,17,21,22],list:[1,2,4,5,6,8,9,11,13,15,16],lister:14,literal_ev:23,live:[1,2,15],llvm:[9,17,21,22],load:[2,11],loader:10,localhost:[11,12],locat:14,lock:[1,27],log:[0,1,2,8,9,23,25,27],logger:[0,8],logic:[3,9,13],longer:[1,2,14,17,19,20,21,22,23,26,27,28],look:[2,9,11,14],lookup:[2,8,11,12],lower:14,luca:14,mac:[17,18],mac_os_x:[19,20,21,22],macrofus:12,made:[6,14],mai:[1,2,8,10,11,12,14,16,20,27],main:10,mainten:[8,14],make:[1,8,15],manag:[7,14,27],mani:[6,14,26],manner:14,manual:[3,14],map:[1,3,6,9,11],mar:20,martelli:[14,15],matter:14,maxbyt:8,mean:[1,2,6,8,11,14,17,20,21,22],mechan:[8,9,12],member:[1,2,6,7,9,10,12,14,15,27],member_nam:[1,2,11,13,26],memori:[7,8,14],mention:3,merit:9,messag:[0,2,4,8,9,10],method:[0,1,2,3,4,7,9,14,15,16,26,27],microthread:11,might:16,minim:14,miss:9,mixin:6,mock:14,mode:8,modif:[1,14],modifi:[2,6,9,13],modul:[0,1,2,3,4,5,6,7,8,10,12,14,15,23],module2:6,moment:[1,2,14,16],monkei:13,more:[1,2,3,6,8,9,14,24,25,26],most:[2,3,8,9,23],movi:14,movie_field:14,moviefind:14,movielist:14,movielisterapp:15,movies_directed_bi:14,msc:[17,19,20,21,22],msi:14,mull:16,multipl:[2,3,6,8,14,26],must:[0,1,2,6,8,11,13,14],mutabl:[7,8],mutual:[2,6],my_app_context:9,my_context:1,my_obj:[4,10],my_singleton:6,myapp:10,mzipai:14,name:[0,1,2,3,4,8,9,10,11,12,13,14,15,26],name_of:0,namespac:[6,11],natur:[1,2,8,11],navig:14,necessari:[2,6,8],necessarili:[17,20,21,22],need:[2,6,8,9,11,14,16,26],neither:[9,14],nervesplic:12,nest:[2,7,26],net:[7,13,17,18,19,20,21,22],never:6,newli:2,next:[6,15,16],ninthtest:[2,8],ninthtest_info:8,ninthtest_url:8,nodriv:11,non:[0,2,3,9,12,14,16,23,26],none:[0,2,3,6,12],nor:[9,14],notabl:[7,15,23],notat:11,note:[8,10,11,14,26],noth:[8,11,16],notic:[6,9,14],notimplementederror:14,nov:9,now:[4,6,8,9,10,11,14,23,25,26,27],nullhandl:0,number:[6,14],nutshel:8,obejct:2,obj:0,object:[1,2,3,4,7,12,14,16,26,27],obtain:[2,11],oct:14,off:14,offici:[17,20,21,22],often:14,onc:[2,3,9,11,14],one:[1,2,3,6,8,9,11,12,14,15],onli:[0,1,2,3,6,11,12,13,14],onto:6,open:[8,9,14],openjdk:[17,21],openjdk_64:[17,21],oper:[0,1,11],opinion:9,oppos:[2,11],option:[3,6,8,11,13,14,16,26],oracl:[17,19,20,21],order:[2,11,14],ordereddict:2,ordin:9,org:[3,8],origin:14,other:[1,2,6,7,8,9,10,14,15,27],otherwis:[1,2,8,11,14],our:[10,11,14],out:14,over:[1,2,9,12,16],overrid:12,overview:15,own:[8,9,13,14],packag:[5,6,17,20,21,22,23,24,27],page:[8,14,15],pair:6,paramet:[0,1,2,3,4,6],parent:[2,3,6,7,8,14],parent_id:2,pars:[3,9,11,14],parser:[3,7,9,26],part:[8,14,23],parti:[7,8],partial:[2,3,7,9,12],particular:[2,14,17,20,21,22],particularli:[9,11],pass:[2,6,11,14,26],patch:[13,26,27],path:8,pattern:[14,15],pdf:[14,15],pend:8,pep:[0,2,24],per:14,perform:2,permit:[3,9],person:16,perspect:11,philosophi:9,pip:14,place:[2,8,11,16],placehold:2,platform:[11,13,17,18,19,20,21,22],pleas:[1,2,8,9,11,12,14],plenti:9,plugin:[4,10],point:[1,2,3,9,14],pop:[4,10],popul:[3,9,14],posit:[2,6,8,9,12,14],possibl:[2,8,11,12,14,16,27],postion:14,power:8,practic:[1,14],pre:4,preced:[2,12],prefer:[6,8,9,14],prepar:[8,12],preparableobjecta:8,preparableobjectb:8,preparableobjectc:8,present:[9,11,14],prete:14,prevent:8,previou:[11,15],previous:26,primarili:9,prime:1,print:8,prior:[11,17,20,21,22],problem:[8,9,14],problemat:9,process:[2,4,8,10,11,12,14],produc:[2,9,14],product:[0,13,14],programmat:[3,6,7,8,11,15,16,23,24],project:[14,27],properli:9,properti:[1,2,6,11,14],protocol:3,prototyp:[1,2,3,4,6,8,9,14,15],provid:[1,2,4,6,7,9,11,13,14,24,26],provis:8,proxi:13,publish:[4,10,17,20,21,22],pure:[3,15],purpos:8,put:13,pypi:[7,15],python2:9,python3:9,python:[1,2,3,5,7,16,23,25,26,27,28],python_org:8,question:8,queue:12,quit:16,rais:[0,1,2,3,8,14],rang:[8,9],rather:[6,14,26],reach:[17,20,21,22],reachabl:13,read:[2,3,14,26],readabl:6,reader:11,readi:8,real:[11,16],realiti:16,realli:[14,23,26],reason:8,rec:3,recal:[11,14],recent:[9,15],recip:[9,11,14,26],recogn:[2,8],recommend:[3,14],record:[2,14,16],recurs:[1,8],red:[14,17,22],redefin:12,ref:[6,8,10,11,12,14],refer:[1,2,3,7,9,10,11,12,14,15,26,27],referenc:[2,8,11,26],reformat:24,regardless:[8,9,14,16],regist:[0,2,3,8,9,10,11,12,14],reinvent:3,rel:11,relat:[2,3],relationship:[8,12],releas:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,20,21,22],relev:6,remain:[1,2],rememb:[2,6,11,14],remov:[1,2,6,23],repeatedli:2,replac:[3,8,23,26],repons:14,repres:[0,2,4,6,9,11,12,13,14],represent:[9,27],request:[1,2,8,11,12,14],request_queue_s:12,requesthandlerclass:[11,12],requir:[3,4,7,8,11,12,14],resid:[13,26],resist:14,resolut:[7,9,14],resolv:[0,1,2,4,6,8,14],resolve_dotted_nam:[0,2],resourc:3,respect:[1,2,8,11,26],respons:[8,14],restrict:2,result:[8,9,10,12,14,17,20,21,22],retriev:[1,14],revamp:[25,26],review:14,revisit:6,rhode:14,roadmap:15,roll:9,rotatingfilehandl:8,row:14,rule:2,run:[0,2,9,11,15,26,27],runtim:[1,2,3,7,10,11,14],runtimewarn:[1,2],safe:[1,7,11,27],safer:23,sake:[6,14],same:[1,2,3,6,8,9,12,14,15],sampl:[11,14,24,26],scaffold:13,scenario:[4,7,15,16],scienc:14,script:14,search:15,second:11,section:[11,14],see:[0,2,8,9,11,12,14,15,23],select:14,self:[6,12,14],semant:[11,15],semver:15,sens:2,sensibl:26,sensit:27,sentiment:16,separ:[2,14],sequenc:[2,6,8,14],sergio:14,serv:[2,6,8,12,13],server:[11,12,17,19,20,21],server_address:12,set:[0,2,3,6,7,8,10,11,12,14,16,23],set_debuglevel:2,setformatt:8,setter:[1,2,6,11,14,15],setup:[11,14,25],sever:[0,5,8,12,14,16,17,20,21,22],share:[1,2,4,8,9,11,15],shell:14,shorthand:6,should:[2,3,6,8,9,12,14,23],show:[2,8,10,12],shown:[8,12,14],signatur:[2,8],signific:14,significantli:9,similar:[2,7,9,11,14],similarli:12,simpl:[2,7,11,12,14],simple_serv:12,simplehttprequesthandl:12,simpleplugin:[4,10],simpler:[8,14],simplest:[1,2,8],simpli:[2,10,11,14,16,17,20,21,22],simplifi:2,sinc:[2,6],singl:[5,9,13],singleton:[1,2,3,4,6,7,10,12,15],sit:13,site:[4,10],six:6,sixteen:14,size:12,slightli:6,slp:21,smaller:14,socket:12,softwar:8,solut:[8,9,14],some:[8,11,15],someth:8,sometim:8,somewhat:14,sort:2,sourc:[0,1,2,3,4,6,9,13],sp0:17,sp1:[18,19,20,21,22],spam:8,speak:[1,11],special:[2,6,8,11,12,14],specif:[2,4,6,7,10,14],specifi:[1,2,3,6,8,9,11,14,26],sphinx:[2,25,26],split:[11,14],sqlite3:14,sqlite:14,stackless:[7,15],standalon:12,standard:[0,3,7,8,11,14],start:[4,9,15,26],state:[1,2,4,8,11,12,15,27],statement:[0,11,13,14],staticmethod:[2,11,26],statu:8,stdout:14,step:15,steril:12,still:[1,2,6,8,9,10,14],stock:12,stone:16,stop:4,store:[2,6,8,14],str:[0,2,3,8,9,10,11,12,14],strategi:[1,2,3,6,8,11,12,16],stream:3,strength:9,strict:[2,3],strictli:11,string:[0,1,2,4,6,9,13,14],strip:14,strive:9,strongli:8,structur:[3,11],stub:14,style:6,sub:11,subclass:[3,6,9,11,14],subpackag:5,subscrib:[4,10],subsect:11,subsequ:[1,2],subset:2,substant:26,success:[6,14],successfulli:3,suffici:[0,3],suggest:[8,15,16],suit:[9,13,14,17,19,20,21,22],summar:9,summari:[13,15],support:[1,2,4,6,7,8,11,12,15,16,23,26,27],suppress:0,suse:21,synchron:8,synchronizedmap:11,syntax:[3,15],sys:[2,3,9,14],system:[3,11,14],tabl:[9,14],tag:[17,20,21,22],take:[2,12,14],talk:14,target:17,task:[11,13],tasklet:7,tell:[1,2,6],tempalt:6,templat:[1,2,3,4,7,8,10,15,27],template_id_spec:[3,6],template_spec:[3,6],temporari:14,term:[1,2,6],termin:[1,6,14],test:[3,9,13,14,15,25,26,28],text:[9,14,16],text_and_data:9,textanddata:9,textbook:8,than:[2,3,8,14,26],thei:[1,2,3,6,8,11,14],them:8,theme:[25,26],theoret:12,thereof:11,thi:[0,1,2,3,4,6,8,9,10,11,12,14,16,17,19,20,21,22,26],thing:[1,2,6,9,11,14],those:[1,2,3,6,8,10,11,12,14,23],though:[2,6,8,16],thought:16,thread:[1,11],threadsaf:11,three:14,through:[1,2,11,27],thx:14,tightli:10,time:[1,2,3,7,9,14,15],timeout:[8,12],titl:14,togeth:12,tool:[10,12],top:5,tour:14,trace:[0,23],traceback:[2,9],treat:[6,9],trigger:8,truli:2,tupl:[2,6,8,9,11,12],turn:[8,9],tutori:[14,26],tutpl:12,twenty_four:22,twenty_seven:17,twist:11,two:[1,2,8,9,11,12,14],txt:[8,14],type:[0,1,2,3,4,7,9,11,14,15,27],typic:9,u0391:9,u0394:9,u03a6:9,ultim:18,una:8,unassign:8,unbound:[7,11],under:[2,3,9,13,14,17,19,20,21,22],understand:[7,8,9,12,14,15],unexpect:3,unfortun:11,unicod:[2,7],unicodeencodeerror:9,uniqu:[1,2,3,4,6,8,13,14],unique_id:[1,2],unit:[13,17,20,21,22],unless:6,unlik:[2,8,14],unnecessari:[6,10],unpack:14,unrel:3,unspecifi:3,unsubscrib:4,until:[1,6,7,9],unzip:14,updat:[6,24,25,26,27,28],upon:[8,9,11,14],url:8,urllib:8,urlopen:8,usabl:2,usag:[7,15,25],use:[0,2,3,4,6,8,9,10,11,12,25],used:[0,1,2,3,6,7,8,9,11,14,27,28],useful:14,usefulness:8,user:[2,9,14],userwarn:2,uses:[0,3,8,9,11,13,14,26],using:[0,1,2,3,4,6,7,8,11,14,15,24,26,27],usual:[8,14],utf:[3,8,9,10,11,12,14],util:[0,4,11],v1709:17,valid:[0,2,3,9,11,13,14],validationtyp:11,valu:[0,2,3,4,6,7,9,11,12,14],valueerror:2,vari:9,variabl:[0,14,23],variant:[15,25,26],variat:11,variou:[26,28],veri:[8,9,15],verifi:[14,26],version:[0,1,2,3,4,6,8,9,10,11,12,13,14,17,18,19,20,21,22,23,25,26],via:[2,6,9,10,11,12,13,23,26],vibrotorch:12,virtualenv:14,vista:19,wai:[2,6,8,9,10,11,13],want:[8,11,13],warn:[2,9],warrant:[6,16],weak:[1,2,8,9],weakref:[1,2,3,4,6,7,10,14,15],web:[4,10],weird:14,well:[2,6,9,11,14,26],were:[1,8,9,11],west:14,what:[8,9,14,15],wheel:3,when:[0,1,2,3,4,6,8,11,12,14,17,20,21,22],whenev:[8,9],where:[8,11,26],wherev:8,whether:[1,8,13,16],which:[0,1,2,3,6,8,9,10,11,12,13,14,15,16,26,27],whirlwind:14,whose:[1,3,4,6,11],why:[9,14],wide:[9,14],wiki:11,window:[14,17,18,19,20,21,22],windows_10:17,windows_7:[19,20,21,22],wire:[1,2,14],wish:[6,8,11,14],with_capacitor_dr:11,withdriv:11,withhold:[17,20,21,22],within:[2,8,13,14],without:[2,8,9,14,26,27],word:[2,14],work:[8,11,25],workflowmanag:8,world:16,would:[2,6,8,9,11,14],wrapper:11,write:[8,14],written:[8,14],wspbu:4,www:[3,8],x86:[19,20,21,22],x86_64:[17,19,20,21,22],x91:9,x94:9,xa6:9,xc1:9,xc4:9,xce:9,xd6:9,xml:[2,3,4,7,14,15,16,26,27],xmlcontext:[3,4,7,8,10,12,14,26],xmlparser:[3,11],xmlreader:7,xmlreaderset:11,xmlreadertreebuild:26,xmlvalidatingreaderimpl:11,yaml:16,yet:12,yield:[3,14],you:[2,4,6,8,9,11,13,14],your:[1,2,4,7,8,9,14],zip:14},titles:["<code class=\"docutils literal\"><span class=\"pre\">aglyph</span></code> \u2014 Dependency Injection for Python","<code class=\"docutils literal\"><span class=\"pre\">aglyph.assembler</span></code> \u2014 The Aglyph component assembler","<code class=\"docutils literal\"><span class=\"pre\">aglyph.component</span></code> \u2014 Defining components and their dependencies","<code class=\"docutils literal\"><span class=\"pre\">aglyph.context</span></code> \u2014 Defining component contexts","<code class=\"docutils literal\"><span class=\"pre\">aglyph.integration.cherrypy</span></code> \u2014 Integrating Aglyph with CherryPy","Aglyph API reference","The Aglyph Context fluent API","Aglyph cookbook","Common usage scenarios","Choose a configuration approach for Aglyph","Integrating Aglyph","Other notable usage scenarios","Component inheritance using templates","Understand the general features of Aglyph","Getting started with Aglyph","Aglyph \u2014 Dependency Injection for Python","Roadmap for future releases","Aglyph 3.0.0 testing summary","Aglyph 1.1.0 testing summary","Aglyph 1.1.1 testing summary","Aglyph 2.0.0 testing summary","Aglyph 2.1.0 testing summary","Aglyph 2.1.1 testing summary","What\u2019s new in release 3.0.0?","What\u2019s new in release 1.1.0?","What\u2019s new in release 1.1.1?","What\u2019s new in release 2.0.0?","What\u2019s new in release 2.1.0?","What\u2019s new in release 2.1.1?"],titleterms:{"3rd":13,"class":[8,11],"function":8,"new":[23,24,25,26,27,28],"static":11,The:[1,6],Use:[8,10,11,12],Using:[6,8,10,11,12],add:14,after:8,again:14,aglyph:[0,1,2,3,4,5,6,7,9,10,11,13,14,15,17,18,19,20,21,22,23],aglyphdiplugin:10,ani:[8,13],anoth:[8,12],api:[5,6,8,9,10,11,12],applic:[10,13,14],approach:9,assembl:[1,8,14],automat:9,avoid:8,awar:9,been:8,befor:8,between:9,borg:[8,11,14],brief:14,builder:6,built:14,builtin:[8,9],cach:[8,11],call:8,can:13,chang:[13,14],charact:9,cherrypi:[4,10],child:12,choos:9,circular:8,clear:[8,11],clone:14,code:13,colondelimitedmoviefind:14,common:[8,12],compon:[1,2,3,6,8,10,11,12,13],configur:[8,9,10,11,12],content:15,context:[3,6,9],convers:9,cookbook:7,cpython:[13,17,18,19,20,21,22],creat:6,creation:6,custom:[9,11],declar:[8,9,10,11,12],defer:8,defin:[2,3,6],depend:[0,2,6,8,10,12,14,15],describ:[6,8,11],differ:9,distribut:14,doe:13,dot:6,download:14,encod:9,entri:6,environ:14,evalu:8,exampl:11,extend:12,extract:14,factori:8,featur:13,fluent:[6,8,9,10,11,12],framework:13,from:[8,14],futur:16,gener:[13,14],get:14,github:14,have:8,implement:11,improv:14,index:14,indic:15,inherit:12,inject:[0,8,10,14,15],instal:14,integr:[4,10],introduc:14,introduct:[6,14],introspect:6,ironpython:[11,13,17,18,19,20,21,22],its:8,java:11,jython:[11,13,17,18,19,20,21,22],let:6,librari:13,lifecycl:[6,10,12],linkedhashmap:11,make:14,manag:10,member:11,memori:11,method:[6,8,11,12],modifi:14,modul:11,movielisterapp:14,mutabl:9,name:6,nest:11,net:11,next:14,notabl:11,note:6,object:[6,8,9,11,13],other:11,overview:6,packag:14,parent:12,parser:11,parti:13,partial:8,point:6,previou:[17,23],programmat:9,provid:10,pypi:[11,13,14,17,18,19,20,21,22],python:[0,8,9,11,13,14,15,17,18,19,20,21,22],refer:[5,6,8],regard:6,regist:6,releas:[16,17,23,24,25,26,27,28],repositori:14,requir:13,resolut:8,roadmap:16,run:14,runtim:8,safe:9,scenario:[8,11],set:9,similar:12,simpl:8,singleton:[8,11,14],some:14,sourc:14,sourceforg:14,specif:[11,12,13],sqlmoviefind:14,stackless:[11,13,17,18,19,20,21,22],standard:13,start:14,step:14,strategi:14,suggest:14,summari:[17,18,19,20,21,22],support:[9,10,13,14],tabl:15,tasklet:11,templat:[6,12],test:[17,18,19,20,21,22],time:8,type:8,unbound:8,understand:13,unicod:9,until:8,usag:[8,11],use:14,used:12,using:[9,10,12],valu:8,veri:14,version:15,virtual:14,weakref:[8,11],what:[23,24,25,26,27,28],xml:[8,9,10,11,12],xmlcontext:[9,11],xmlreader:11,your:[10,13]}}) | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/doc/build/html/searchindex.js | searchindex.js |
* select a different prefix for underscore
*/
$u = _.noConflict();
/**
* make the code below compatible with browsers without
* an installed firebug like debugger
if (!window.console || !console.firebug) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir",
"dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace",
"profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i)
window.console[names[i]] = function() {};
}
*/
/**
* small helper function to urldecode strings
*/
jQuery.urldecode = function(x) {
return decodeURIComponent(x).replace(/\+/g, ' ');
};
/**
* small helper function to urlencode strings
*/
jQuery.urlencode = encodeURIComponent;
/**
* This function returns the parsed url parameters of the
* current request. Multiple values per key are supported,
* it will always return arrays of strings for the value parts.
*/
jQuery.getQueryParameters = function(s) {
if (typeof s === 'undefined')
s = document.location.search;
var parts = s.substr(s.indexOf('?') + 1).split('&');
var result = {};
for (var i = 0; i < parts.length; i++) {
var tmp = parts[i].split('=', 2);
var key = jQuery.urldecode(tmp[0]);
var value = jQuery.urldecode(tmp[1]);
if (key in result)
result[key].push(value);
else
result[key] = [value];
}
return result;
};
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node, addItems) {
if (node.nodeType === 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) {
var span;
var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg");
if (isInSVG) {
span = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
} else {
span = document.createElement("span");
span.className = className;
}
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
if (isInSVG) {
var bbox = span.getBBox();
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.x.baseVal.value = bbox.x;
rect.y.baseVal.value = bbox.y;
rect.width.baseVal.value = bbox.width;
rect.height.baseVal.value = bbox.height;
rect.setAttribute('class', className);
var parentOfText = node.parentNode.parentNode;
addItems.push({
"parent": node.parentNode,
"target": rect});
}
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this, addItems);
});
}
}
var addItems = [];
var result = this.each(function() {
highlight(this, addItems);
});
for (var i = 0; i < addItems.length; ++i) {
jQuery(addItems[i].parent).before(addItems[i].target);
}
return result;
};
/*
* backward compatibility for jQuery.browser
* This will be supported until firefox bug is fixed.
*/
if (!jQuery.browser) {
jQuery.uaMatch = function(ua) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
/(webkit)[ \/]([\w.]+)/.exec(ua) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
/(msie) ([\w.]+)/.exec(ua) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
jQuery.browser = {};
jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true;
}
/**
* Small JavaScript module for the documentation.
*/
var Documentation = {
init : function() {
this.fixFirefoxAnchorBug();
this.highlightSearchWords();
this.initIndexTable();
},
/**
* i18n support
*/
TRANSLATIONS : {},
PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; },
LOCALE : 'unknown',
// gettext and ngettext don't access this so that the functions
// can safely bound to a different name (_ = Documentation.gettext)
gettext : function(string) {
var translated = Documentation.TRANSLATIONS[string];
if (typeof translated === 'undefined')
return string;
return (typeof translated === 'string') ? translated : translated[0];
},
ngettext : function(singular, plural, n) {
var translated = Documentation.TRANSLATIONS[singular];
if (typeof translated === 'undefined')
return (n == 1) ? singular : plural;
return translated[Documentation.PLURALEXPR(n)];
},
addTranslations : function(catalog) {
for (var key in catalog.messages)
this.TRANSLATIONS[key] = catalog.messages[key];
this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')');
this.LOCALE = catalog.locale;
},
/**
* add context elements like header anchor links
*/
addContextElements : function() {
$('div[id] > :header:first').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this headline')).
appendTo(this);
});
$('dt[id]').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this definition')).
appendTo(this);
});
},
/**
* workaround a firefox stupidity
* see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075
*/
fixFirefoxAnchorBug : function() {
if (document.location.hash && $.browser.mozilla)
window.setTimeout(function() {
document.location.href += '';
}, 10);
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
if (!body.length) {
body = $('body');
}
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlighted');
});
}, 10);
$('<p class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>')
.appendTo($('#searchbox'));
}
},
/**
* init the domain index toggle buttons
*/
initIndexTable : function() {
var togglers = $('img.toggler').click(function() {
var src = $(this).attr('src');
var idnum = $(this).attr('id').substr(7);
$('tr.cg-' + idnum).toggle();
if (src.substr(-9) === 'minus.png')
$(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
else
$(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
}).css('display', '');
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
togglers.click();
}
},
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('#searchbox .highlight-link').fadeOut(300);
$('span.highlighted').removeClass('highlighted');
},
/**
* make the url absolute
*/
makeURL : function(relativeURL) {
return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;
},
/**
* get the current relative url
*/
getCurrentURL : function() {
var path = document.location.pathname;
var parts = path.split(/\//);
$.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() {
if (this === '..')
parts.pop();
});
var url = parts.join('/');
return path.substring(url.lastIndexOf('/') + 1, path.length - 1);
},
initOnKeyListeners: function() {
$(document).keyup(function(event) {
var activeElementType = document.activeElement.tagName;
// don't navigate when in search box or textarea
if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') {
switch (event.keyCode) {
case 37: // left
var prevHref = $('link[rel="prev"]').prop('href');
if (prevHref) {
window.location.href = prevHref;
return false;
}
case 39: // right
var nextHref = $('link[rel="next"]').prop('href');
if (nextHref) {
window.location.href = nextHref;
return false;
}
}
}
});
}
};
// quick alias for translations
_ = Documentation.gettext;
$(document).ready(function() {
Documentation.init();
}); | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/doc/build/html/_static/doctools.js | doctools.js |
(function(){function q(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return a==String(c);case "[object Number]":return a!=+a?c!=+c:a==0?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source==
c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&q(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(b.has(a,h)&&(f++,!(g=b.has(c,h)&&q(a[h],c[h],d))))break;if(g){for(h in c)if(b.has(c,
h)&&!f--)break;g=!f}}d.pop();return g}var r=this,G=r._,n={},k=Array.prototype,o=Object.prototype,i=k.slice,H=k.unshift,l=o.toString,I=o.hasOwnProperty,w=k.forEach,x=k.map,y=k.reduce,z=k.reduceRight,A=k.filter,B=k.every,C=k.some,p=k.indexOf,D=k.lastIndexOf,o=Array.isArray,J=Object.keys,s=Function.prototype.bind,b=function(a){return new m(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else r._=b;b.VERSION="1.3.1";var j=b.each=
b.forEach=function(a,c,d){if(a!=null)if(w&&a.forEach===w)a.forEach(c,d);else if(a.length===+a.length)for(var e=0,f=a.length;e<f;e++){if(e in a&&c.call(d,a[e],e,a)===n)break}else for(e in a)if(b.has(a,e)&&c.call(d,a[e],e,a)===n)break};b.map=b.collect=function(a,c,b){var e=[];if(a==null)return e;if(x&&a.map===x)return a.map(c,b);j(a,function(a,g,h){e[e.length]=c.call(b,a,g,h)});if(a.length===+a.length)e.length=a.length;return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var f=arguments.length>2;a==
null&&(a=[]);if(y&&a.reduce===y)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(z&&a.reduceRight===z)return e&&(c=b.bind(c,e)),f?a.reduceRight(c,d):a.reduceRight(c);var g=b.toArray(a).reverse();e&&!f&&(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.find=b.detect=
function(a,c,b){var e;E(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(A&&a.filter===A)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(B&&a.every===B)return a.every(c,b);j(a,function(a,g,h){if(!(e=
e&&c.call(b,a,g,h)))return n});return e};var E=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(C&&a.some===C)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return n});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return p&&a.indexOf===p?a.indexOf(c)!=-1:b=E(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d)})};b.pluck=
function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b<e.computed&&(e={value:a,computed:b})});
return e.value};b.shuffle=function(a){var b=[],d;j(a,function(a,f){f==0?b[0]=a:(d=Math.floor(Math.random()*(f+1)),b[f]=b[d],b[d]=a)});return b};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,g){return{value:a,criteria:c.call(d,a,b,g)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,b){var c=e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedIndex=function(a,
c,d){d||(d=b.identity);for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){return!a?[]:a.toArray?a.toArray():b.isArray(a)?i.call(a):b.isArguments(a)?i.call(a):b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?i.call(a,0,b):a[0]};b.initial=function(a,b,d){return i.call(a,0,a.length-(b==null||d?1:b))};b.last=function(a,b,d){return b!=null&&!d?i.call(a,Math.max(a.length-b,0)):a[a.length-1]};b.rest=
b.tail=function(a,b,d){return i.call(a,b==null||d?1:b)};b.compact=function(a){return b.filter(a,function(a){return!!a})};b.flatten=function(a,c){return b.reduce(a,function(a,e){if(b.isArray(e))return a.concat(c?e:b.flatten(e));a[a.length]=e;return a},[])};b.without=function(a){return b.difference(a,i.call(arguments,1))};b.uniq=b.unique=function(a,c,d){var d=d?b.map(a,d):a,e=[];b.reduce(d,function(d,g,h){if(0==h||(c===true?b.last(d)!=g:!b.include(d,g)))d[d.length]=g,e[e.length]=a[h];return d},[]);
return e};b.union=function(){return b.uniq(b.flatten(arguments,true))};b.intersection=b.intersect=function(a){var c=i.call(arguments,1);return b.filter(b.uniq(a),function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1));return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=function(a,c,
d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(p&&a.indexOf===p)return a.indexOf(c);for(d=0,e=a.length;d<e;d++)if(d in a&&a[d]===c)return d;return-1};b.lastIndexOf=function(a,b){if(a==null)return-1;if(D&&a.lastIndexOf===D)return a.lastIndexOf(b);for(var d=a.length;d--;)if(d in a&&a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);for(var d=arguments[2]||1,e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g};
var F=function(){};b.bind=function(a,c){var d,e;if(a.bind===s&&s)return s.apply(a,i.call(arguments,1));if(!b.isFunction(a))throw new TypeError;e=i.call(arguments,2);return d=function(){if(!(this instanceof d))return a.apply(c,e.concat(i.call(arguments)));F.prototype=a.prototype;var b=new F,g=a.apply(b,e.concat(i.call(arguments)));return Object(g)===g?g:b}};b.bindAll=function(a){var c=i.call(arguments,1);c.length==0&&(c=b.functions(a));j(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a,
c){var d={};c||(c=b.identity);return function(){var e=c.apply(this,arguments);return b.has(d,e)?d[e]:d[e]=a.apply(this,arguments)}};b.delay=function(a,b){var d=i.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(i.call(arguments,1)))};b.throttle=function(a,c){var d,e,f,g,h,i=b.debounce(function(){h=g=false},c);return function(){d=this;e=arguments;var b;f||(f=setTimeout(function(){f=null;h&&a.apply(d,e);i()},c));g?h=true:
a.apply(d,e);i();g=true}};b.debounce=function(a,b){var d;return function(){var e=this,f=arguments;clearTimeout(d);d=setTimeout(function(){d=null;a.apply(e,f)},b)}};b.once=function(a){var b=false,d;return function(){if(b)return d;b=true;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(i.call(arguments,0));return b.apply(this,d)}};b.compose=function(){var a=arguments;return function(){for(var b=arguments,d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}};
b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=J||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var c=[],d;for(d in a)b.has(a,d)&&(c[c.length]=d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]=b[d]});return a};b.defaults=function(a){j(i.call(arguments,
1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return q(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(b.has(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=o||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){return a===Object(a)};
b.isArguments=function(a){return l.call(a)=="[object Arguments]"};if(!b.isArguments(arguments))b.isArguments=function(a){return!(!a||!b.has(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a)=="[object Date]"};
b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.has=function(a,b){return I.call(a,b)};b.noConflict=function(){r._=G;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.escape=function(a){return(""+a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")};b.mixin=function(a){j(b.functions(a),
function(c){K(c,b[c]=a[c])})};var L=0;b.uniqueId=function(a){var b=L++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var t=/.^/,u=function(a){return a.replace(/\\\\/g,"\\").replace(/\\'/g,"'")};b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape||t,function(a,b){return"',_.escape("+
u(b)+"),'"}).replace(d.interpolate||t,function(a,b){return"',"+u(b)+",'"}).replace(d.evaluate||t,function(a,b){return"');"+u(b).replace(/[\r\n\t]/g," ")+";__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e.call(this,a,b)}};b.chain=function(a){return b(a).chain()};var m=function(a){this._wrapped=a};b.prototype=m.prototype;var v=function(a,c){return c?b(a).chain():a},K=function(a,c){m.prototype[a]=
function(){var a=i.call(arguments);H.call(a,this._wrapped);return v(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];m.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return v(d,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];m.prototype[a]=function(){return v(b.apply(this._wrapped,arguments),this._chain)}});m.prototype.chain=function(){this._chain=
true;return this};m.prototype.value=function(){return this._wrapped}}).call(this); | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/doc/build/html/_static/underscore.js | underscore.js |
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
unshift = ArrayProto.unshift,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root['_'] = _;
}
// Current version.
_.VERSION = '1.3.1';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
if (obj.length === +obj.length) results.length = obj.length;
return results;
};
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError('Reduce of empty array with no initial value');
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var reversed = _.toArray(obj).reverse();
if (context && !initial) iterator = _.bind(iterator, context);
return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
each(obj, function(value, index, list) {
if (!iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if a given value is included in the array or object using `===`.
// Aliased as `contains`.
_.include = _.contains = function(obj, target) {
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
found = any(obj, function(value) {
return value === target;
});
return found;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Return the maximum element or (element-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array.
_.shuffle = function(obj) {
var shuffled = [], rand;
each(obj, function(value, index, list) {
if (index == 0) {
shuffled[0] = value;
} else {
rand = Math.floor(Math.random() * (index + 1));
shuffled[index] = shuffled[rand];
shuffled[rand] = value;
}
});
return shuffled;
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = function(obj, val) {
var result = {};
var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
});
return result;
};
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator) {
iterator || (iterator = _.identity);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >> 1;
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
if (_.isArray(iterable)) return slice.call(iterable);
if (_.isArguments(iterable)) return slice.call(iterable);
return _.values(iterable);
};
// Return the number of elements in an object.
_.size = function(obj) {
return _.toArray(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head`. The **guard** check allows it to work
// with `_.map`.
_.first = _.head = function(array, n, guard) {
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the last entry of the array. Especcialy useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
// Returns everything but the first entry of the array. Aliased as `tail`.
// Especially useful on the arguments object. Passing an **index** will return
// the rest of the values in the array from that index onward. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = function(array, index, guard) {
return slice.call(array, (index == null) || guard ? 1 : index);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator) {
var initial = iterator ? _.map(array, iterator) : array;
var result = [];
_.reduce(initial, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
memo[memo.length] = el;
result[result.length] = array[i];
}
return memo;
}, []);
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays. (Aliased as "intersect" for back-compat.)
_.intersection = _.intersect = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = _.flatten(slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.include(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
return results;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i, l;
if (isSorted) {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item) {
if (array == null) return -1;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
var i = array.length;
while (i--) if (i in array && array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
_.bind = function bind(func, context) {
var bound, args;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length == 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(func, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
var context, args, timeout, throttling, more;
var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
return function() {
context = this; args = arguments;
var later = function() {
timeout = null;
if (more) func.apply(context, args);
whenDone();
};
if (!timeout) timeout = setTimeout(later, wait);
if (throttling) {
more = true;
} else {
func.apply(context, args);
}
whenDone();
throttling = true;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
_.debounce = function(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func].concat(slice.call(arguments, 0));
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) { return func.apply(this, arguments); }
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
return _.map(obj, _.identity);
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
obj[prop] = source[prop];
}
});
return obj;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function.
function eq(a, b, stack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
// Invoke a custom `isEqual` method if one is provided.
if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = stack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (stack[length] == a) return true;
}
// Add the first object to the stack of traversed objects.
stack.push(a);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
// Ensure commutative equality for sparse arrays.
if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
}
}
} else {
// Objects with different constructors are not equivalent.
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
stack.pop();
return result;
}
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Is a given variable an arguments object?
_.isArguments = function(obj) {
return toString.call(obj) == '[object Arguments]';
};
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Is a given value a function?
_.isFunction = function(obj) {
return toString.call(obj) == '[object Function]';
};
// Is a given value a string?
_.isString = function(obj) {
return toString.call(obj) == '[object String]';
};
// Is a given value a number?
_.isNumber = function(obj) {
return toString.call(obj) == '[object Number]';
};
// Is the given value `NaN`?
_.isNaN = function(obj) {
// `NaN` is the only value for which `===` is not reflexive.
return obj !== obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value a date?
_.isDate = function(obj) {
return toString.call(obj) == '[object Date]';
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return toString.call(obj) == '[object RegExp]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Has own property?
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function (n, iterator, context) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
// Escape a string for HTML interpolation.
_.escape = function(string) {
return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
};
// Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
addToWrapper(name, _[name] = obj[name]);
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /.^/;
// Within an interpolation, evaluation, or escaping, remove HTML escaping
// that had been previously added.
var unescape = function(code) {
return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(str, data) {
var c = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.escape || noMatch, function(match, code) {
return "',_.escape(" + unescape(code) + "),'";
})
.replace(c.interpolate || noMatch, function(match, code) {
return "'," + unescape(code) + ",'";
})
.replace(c.evaluate || noMatch, function(match, code) {
return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', '_', tmpl);
if (data) return func(data, _);
return function(data) {
return func.call(this, data, _);
};
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// The OOP Wrapper
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
var wrapper = function(obj) { this._wrapped = obj; };
// Expose `wrapper.prototype` as `_.prototype`
_.prototype = wrapper.prototype;
// Helper function to continue chaining intermediate results.
var result = function(obj, chain) {
return chain ? _(obj).chain() : obj;
};
// A method to easily add functions to the OOP wrapper.
var addToWrapper = function(name, func) {
wrapper.prototype[name] = function() {
var args = slice.call(arguments);
unshift.call(args, this._wrapped);
return result(func.apply(_, args), this._chain);
};
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
var wrapped = this._wrapped;
method.apply(wrapped, arguments);
var length = wrapped.length;
if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
return result(wrapped, this._chain);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
return result(method.apply(this._wrapped, arguments), this._chain);
};
});
// Start chaining a wrapped Underscore object.
wrapper.prototype.chain = function() {
this._chain = true;
return this;
};
// Extracts the result from a wrapped and chained object.
wrapper.prototype.value = function() {
return this._wrapped;
};
}).call(this); | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/doc/build/html/_static/underscore-1.3.1.js | underscore-1.3.1.js |
(function($) {
$.fn.autogrow = function() {
return this.each(function() {
var textarea = this;
$.fn.autogrow.resize(textarea);
$(textarea)
.focus(function() {
textarea.interval = setInterval(function() {
$.fn.autogrow.resize(textarea);
}, 500);
})
.blur(function() {
clearInterval(textarea.interval);
});
});
};
$.fn.autogrow.resize = function(textarea) {
var lineHeight = parseInt($(textarea).css('line-height'), 10);
var lines = textarea.value.split('\n');
var columns = textarea.cols;
var lineCount = 0;
$.each(lines, function() {
lineCount += Math.ceil(this.length / columns) || 1;
});
var height = lineHeight * (lineCount + 1);
$(textarea).css('height', height);
};
})(jQuery);
(function($) {
var comp, by;
function init() {
initEvents();
initComparator();
}
function initEvents() {
$(document).on("click", 'a.comment-close', function(event) {
event.preventDefault();
hide($(this).attr('id').substring(2));
});
$(document).on("click", 'a.vote', function(event) {
event.preventDefault();
handleVote($(this));
});
$(document).on("click", 'a.reply', function(event) {
event.preventDefault();
openReply($(this).attr('id').substring(2));
});
$(document).on("click", 'a.close-reply', function(event) {
event.preventDefault();
closeReply($(this).attr('id').substring(2));
});
$(document).on("click", 'a.sort-option', function(event) {
event.preventDefault();
handleReSort($(this));
});
$(document).on("click", 'a.show-proposal', function(event) {
event.preventDefault();
showProposal($(this).attr('id').substring(2));
});
$(document).on("click", 'a.hide-proposal', function(event) {
event.preventDefault();
hideProposal($(this).attr('id').substring(2));
});
$(document).on("click", 'a.show-propose-change', function(event) {
event.preventDefault();
showProposeChange($(this).attr('id').substring(2));
});
$(document).on("click", 'a.hide-propose-change', function(event) {
event.preventDefault();
hideProposeChange($(this).attr('id').substring(2));
});
$(document).on("click", 'a.accept-comment', function(event) {
event.preventDefault();
acceptComment($(this).attr('id').substring(2));
});
$(document).on("click", 'a.delete-comment', function(event) {
event.preventDefault();
deleteComment($(this).attr('id').substring(2));
});
$(document).on("click", 'a.comment-markup', function(event) {
event.preventDefault();
toggleCommentMarkupBox($(this).attr('id').substring(2));
});
}
/**
* Set comp, which is a comparator function used for sorting and
* inserting comments into the list.
*/
function setComparator() {
// If the first three letters are "asc", sort in ascending order
// and remove the prefix.
if (by.substring(0,3) == 'asc') {
var i = by.substring(3);
comp = function(a, b) { return a[i] - b[i]; };
} else {
// Otherwise sort in descending order.
comp = function(a, b) { return b[by] - a[by]; };
}
// Reset link styles and format the selected sort option.
$('a.sel').attr('href', '#').removeClass('sel');
$('a.by' + by).removeAttr('href').addClass('sel');
}
/**
* Create a comp function. If the user has preferences stored in
* the sortBy cookie, use those, otherwise use the default.
*/
function initComparator() {
by = 'rating'; // Default to sort by rating.
// If the sortBy cookie is set, use that instead.
if (document.cookie.length > 0) {
var start = document.cookie.indexOf('sortBy=');
if (start != -1) {
start = start + 7;
var end = document.cookie.indexOf(";", start);
if (end == -1) {
end = document.cookie.length;
by = unescape(document.cookie.substring(start, end));
}
}
}
setComparator();
}
/**
* Show a comment div.
*/
function show(id) {
$('#ao' + id).hide();
$('#ah' + id).show();
var context = $.extend({id: id}, opts);
var popup = $(renderTemplate(popupTemplate, context)).hide();
popup.find('textarea[name="proposal"]').hide();
popup.find('a.by' + by).addClass('sel');
var form = popup.find('#cf' + id);
form.submit(function(event) {
event.preventDefault();
addComment(form);
});
$('#s' + id).after(popup);
popup.slideDown('fast', function() {
getComments(id);
});
}
/**
* Hide a comment div.
*/
function hide(id) {
$('#ah' + id).hide();
$('#ao' + id).show();
var div = $('#sc' + id);
div.slideUp('fast', function() {
div.remove();
});
}
/**
* Perform an ajax request to get comments for a node
* and insert the comments into the comments tree.
*/
function getComments(id) {
$.ajax({
type: 'GET',
url: opts.getCommentsURL,
data: {node: id},
success: function(data, textStatus, request) {
var ul = $('#cl' + id);
var speed = 100;
$('#cf' + id)
.find('textarea[name="proposal"]')
.data('source', data.source);
if (data.comments.length === 0) {
ul.html('<li>No comments yet.</li>');
ul.data('empty', true);
} else {
// If there are comments, sort them and put them in the list.
var comments = sortComments(data.comments);
speed = data.comments.length * 100;
appendComments(comments, ul);
ul.data('empty', false);
}
$('#cn' + id).slideUp(speed + 200);
ul.slideDown(speed);
},
error: function(request, textStatus, error) {
showError('Oops, there was a problem retrieving the comments.');
},
dataType: 'json'
});
}
/**
* Add a comment via ajax and insert the comment into the comment tree.
*/
function addComment(form) {
var node_id = form.find('input[name="node"]').val();
var parent_id = form.find('input[name="parent"]').val();
var text = form.find('textarea[name="comment"]').val();
var proposal = form.find('textarea[name="proposal"]').val();
if (text == '') {
showError('Please enter a comment.');
return;
}
// Disable the form that is being submitted.
form.find('textarea,input').attr('disabled', 'disabled');
// Send the comment to the server.
$.ajax({
type: "POST",
url: opts.addCommentURL,
dataType: 'json',
data: {
node: node_id,
parent: parent_id,
text: text,
proposal: proposal
},
success: function(data, textStatus, error) {
// Reset the form.
if (node_id) {
hideProposeChange(node_id);
}
form.find('textarea')
.val('')
.add(form.find('input'))
.removeAttr('disabled');
var ul = $('#cl' + (node_id || parent_id));
if (ul.data('empty')) {
$(ul).empty();
ul.data('empty', false);
}
insertComment(data.comment);
var ao = $('#ao' + node_id);
ao.find('img').attr({'src': opts.commentBrightImage});
if (node_id) {
// if this was a "root" comment, remove the commenting box
// (the user can get it back by reopening the comment popup)
$('#ca' + node_id).slideUp();
}
},
error: function(request, textStatus, error) {
form.find('textarea,input').removeAttr('disabled');
showError('Oops, there was a problem adding the comment.');
}
});
}
/**
* Recursively append comments to the main comment list and children
* lists, creating the comment tree.
*/
function appendComments(comments, ul) {
$.each(comments, function() {
var div = createCommentDiv(this);
ul.append($(document.createElement('li')).html(div));
appendComments(this.children, div.find('ul.comment-children'));
// To avoid stagnating data, don't store the comments children in data.
this.children = null;
div.data('comment', this);
});
}
/**
* After adding a new comment, it must be inserted in the correct
* location in the comment tree.
*/
function insertComment(comment) {
var div = createCommentDiv(comment);
// To avoid stagnating data, don't store the comments children in data.
comment.children = null;
div.data('comment', comment);
var ul = $('#cl' + (comment.node || comment.parent));
var siblings = getChildren(ul);
var li = $(document.createElement('li'));
li.hide();
// Determine where in the parents children list to insert this comment.
for(i=0; i < siblings.length; i++) {
if (comp(comment, siblings[i]) <= 0) {
$('#cd' + siblings[i].id)
.parent()
.before(li.html(div));
li.slideDown('fast');
return;
}
}
// If we get here, this comment rates lower than all the others,
// or it is the only comment in the list.
ul.append(li.html(div));
li.slideDown('fast');
}
function acceptComment(id) {
$.ajax({
type: 'POST',
url: opts.acceptCommentURL,
data: {id: id},
success: function(data, textStatus, request) {
$('#cm' + id).fadeOut('fast');
$('#cd' + id).removeClass('moderate');
},
error: function(request, textStatus, error) {
showError('Oops, there was a problem accepting the comment.');
}
});
}
function deleteComment(id) {
$.ajax({
type: 'POST',
url: opts.deleteCommentURL,
data: {id: id},
success: function(data, textStatus, request) {
var div = $('#cd' + id);
if (data == 'delete') {
// Moderator mode: remove the comment and all children immediately
div.slideUp('fast', function() {
div.remove();
});
return;
}
// User mode: only mark the comment as deleted
div
.find('span.user-id:first')
.text('[deleted]').end()
.find('div.comment-text:first')
.text('[deleted]').end()
.find('#cm' + id + ', #dc' + id + ', #ac' + id + ', #rc' + id +
', #sp' + id + ', #hp' + id + ', #cr' + id + ', #rl' + id)
.remove();
var comment = div.data('comment');
comment.username = '[deleted]';
comment.text = '[deleted]';
div.data('comment', comment);
},
error: function(request, textStatus, error) {
showError('Oops, there was a problem deleting the comment.');
}
});
}
function showProposal(id) {
$('#sp' + id).hide();
$('#hp' + id).show();
$('#pr' + id).slideDown('fast');
}
function hideProposal(id) {
$('#hp' + id).hide();
$('#sp' + id).show();
$('#pr' + id).slideUp('fast');
}
function showProposeChange(id) {
$('#pc' + id).hide();
$('#hc' + id).show();
var textarea = $('#pt' + id);
textarea.val(textarea.data('source'));
$.fn.autogrow.resize(textarea[0]);
textarea.slideDown('fast');
}
function hideProposeChange(id) {
$('#hc' + id).hide();
$('#pc' + id).show();
var textarea = $('#pt' + id);
textarea.val('').removeAttr('disabled');
textarea.slideUp('fast');
}
function toggleCommentMarkupBox(id) {
$('#mb' + id).toggle();
}
/** Handle when the user clicks on a sort by link. */
function handleReSort(link) {
var classes = link.attr('class').split(/\s+/);
for (var i=0; i<classes.length; i++) {
if (classes[i] != 'sort-option') {
by = classes[i].substring(2);
}
}
setComparator();
// Save/update the sortBy cookie.
var expiration = new Date();
expiration.setDate(expiration.getDate() + 365);
document.cookie= 'sortBy=' + escape(by) +
';expires=' + expiration.toUTCString();
$('ul.comment-ul').each(function(index, ul) {
var comments = getChildren($(ul), true);
comments = sortComments(comments);
appendComments(comments, $(ul).empty());
});
}
/**
* Function to process a vote when a user clicks an arrow.
*/
function handleVote(link) {
if (!opts.voting) {
showError("You'll need to login to vote.");
return;
}
var id = link.attr('id');
if (!id) {
// Didn't click on one of the voting arrows.
return;
}
// If it is an unvote, the new vote value is 0,
// Otherwise it's 1 for an upvote, or -1 for a downvote.
var value = 0;
if (id.charAt(1) != 'u') {
value = id.charAt(0) == 'u' ? 1 : -1;
}
// The data to be sent to the server.
var d = {
comment_id: id.substring(2),
value: value
};
// Swap the vote and unvote links.
link.hide();
$('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id)
.show();
// The div the comment is displayed in.
var div = $('div#cd' + d.comment_id);
var data = div.data('comment');
// If this is not an unvote, and the other vote arrow has
// already been pressed, unpress it.
if ((d.value !== 0) && (data.vote === d.value * -1)) {
$('#' + (d.value == 1 ? 'd' : 'u') + 'u' + d.comment_id).hide();
$('#' + (d.value == 1 ? 'd' : 'u') + 'v' + d.comment_id).show();
}
// Update the comments rating in the local data.
data.rating += (data.vote === 0) ? d.value : (d.value - data.vote);
data.vote = d.value;
div.data('comment', data);
// Change the rating text.
div.find('.rating:first')
.text(data.rating + ' point' + (data.rating == 1 ? '' : 's'));
// Send the vote information to the server.
$.ajax({
type: "POST",
url: opts.processVoteURL,
data: d,
error: function(request, textStatus, error) {
showError('Oops, there was a problem casting that vote.');
}
});
}
/**
* Open a reply form used to reply to an existing comment.
*/
function openReply(id) {
// Swap out the reply link for the hide link
$('#rl' + id).hide();
$('#cr' + id).show();
// Add the reply li to the children ul.
var div = $(renderTemplate(replyTemplate, {id: id})).hide();
$('#cl' + id)
.prepend(div)
// Setup the submit handler for the reply form.
.find('#rf' + id)
.submit(function(event) {
event.preventDefault();
addComment($('#rf' + id));
closeReply(id);
})
.find('input[type=button]')
.click(function() {
closeReply(id);
});
div.slideDown('fast', function() {
$('#rf' + id).find('textarea').focus();
});
}
/**
* Close the reply form opened with openReply.
*/
function closeReply(id) {
// Remove the reply div from the DOM.
$('#rd' + id).slideUp('fast', function() {
$(this).remove();
});
// Swap out the hide link for the reply link
$('#cr' + id).hide();
$('#rl' + id).show();
}
/**
* Recursively sort a tree of comments using the comp comparator.
*/
function sortComments(comments) {
comments.sort(comp);
$.each(comments, function() {
this.children = sortComments(this.children);
});
return comments;
}
/**
* Get the children comments from a ul. If recursive is true,
* recursively include childrens' children.
*/
function getChildren(ul, recursive) {
var children = [];
ul.children().children("[id^='cd']")
.each(function() {
var comment = $(this).data('comment');
if (recursive)
comment.children = getChildren($(this).find('#cl' + comment.id), true);
children.push(comment);
});
return children;
}
/** Create a div to display a comment in. */
function createCommentDiv(comment) {
if (!comment.displayed && !opts.moderator) {
return $('<div class="moderate">Thank you! Your comment will show up '
+ 'once it is has been approved by a moderator.</div>');
}
// Prettify the comment rating.
comment.pretty_rating = comment.rating + ' point' +
(comment.rating == 1 ? '' : 's');
// Make a class (for displaying not yet moderated comments differently)
comment.css_class = comment.displayed ? '' : ' moderate';
// Create a div for this comment.
var context = $.extend({}, opts, comment);
var div = $(renderTemplate(commentTemplate, context));
// If the user has voted on this comment, highlight the correct arrow.
if (comment.vote) {
var direction = (comment.vote == 1) ? 'u' : 'd';
div.find('#' + direction + 'v' + comment.id).hide();
div.find('#' + direction + 'u' + comment.id).show();
}
if (opts.moderator || comment.text != '[deleted]') {
div.find('a.reply').show();
if (comment.proposal_diff)
div.find('#sp' + comment.id).show();
if (opts.moderator && !comment.displayed)
div.find('#cm' + comment.id).show();
if (opts.moderator || (opts.username == comment.username))
div.find('#dc' + comment.id).show();
}
return div;
}
/**
* A simple template renderer. Placeholders such as <%id%> are replaced
* by context['id'] with items being escaped. Placeholders such as <#id#>
* are not escaped.
*/
function renderTemplate(template, context) {
var esc = $(document.createElement('div'));
function handle(ph, escape) {
var cur = context;
$.each(ph.split('.'), function() {
cur = cur[this];
});
return escape ? esc.text(cur || "").html() : cur;
}
return template.replace(/<([%#])([\w\.]*)\1>/g, function() {
return handle(arguments[2], arguments[1] == '%' ? true : false);
});
}
/** Flash an error message briefly. */
function showError(message) {
$(document.createElement('div')).attr({'class': 'popup-error'})
.append($(document.createElement('div'))
.attr({'class': 'error-message'}).text(message))
.appendTo('body')
.fadeIn("slow")
.delay(2000)
.fadeOut("slow");
}
/** Add a link the user uses to open the comments popup. */
$.fn.comment = function() {
return this.each(function() {
var id = $(this).attr('id').substring(1);
var count = COMMENT_METADATA[id];
var title = count + ' comment' + (count == 1 ? '' : 's');
var image = count > 0 ? opts.commentBrightImage : opts.commentImage;
var addcls = count == 0 ? ' nocomment' : '';
$(this)
.append(
$(document.createElement('a')).attr({
href: '#',
'class': 'sphinx-comment-open' + addcls,
id: 'ao' + id
})
.append($(document.createElement('img')).attr({
src: image,
alt: 'comment',
title: title
}))
.click(function(event) {
event.preventDefault();
show($(this).attr('id').substring(2));
})
)
.append(
$(document.createElement('a')).attr({
href: '#',
'class': 'sphinx-comment-close hidden',
id: 'ah' + id
})
.append($(document.createElement('img')).attr({
src: opts.closeCommentImage,
alt: 'close',
title: 'close'
}))
.click(function(event) {
event.preventDefault();
hide($(this).attr('id').substring(2));
})
);
});
};
var opts = {
processVoteURL: '/_process_vote',
addCommentURL: '/_add_comment',
getCommentsURL: '/_get_comments',
acceptCommentURL: '/_accept_comment',
deleteCommentURL: '/_delete_comment',
commentImage: '/static/_static/comment.png',
closeCommentImage: '/static/_static/comment-close.png',
loadingImage: '/static/_static/ajax-loader.gif',
commentBrightImage: '/static/_static/comment-bright.png',
upArrow: '/static/_static/up.png',
downArrow: '/static/_static/down.png',
upArrowPressed: '/static/_static/up-pressed.png',
downArrowPressed: '/static/_static/down-pressed.png',
voting: false,
moderator: false
};
if (typeof COMMENT_OPTIONS != "undefined") {
opts = jQuery.extend(opts, COMMENT_OPTIONS);
}
var popupTemplate = '\
<div class="sphinx-comments" id="sc<%id%>">\
<p class="sort-options">\
Sort by:\
<a href="#" class="sort-option byrating">best rated</a>\
<a href="#" class="sort-option byascage">newest</a>\
<a href="#" class="sort-option byage">oldest</a>\
</p>\
<div class="comment-header">Comments</div>\
<div class="comment-loading" id="cn<%id%>">\
loading comments... <img src="<%loadingImage%>" alt="" /></div>\
<ul id="cl<%id%>" class="comment-ul"></ul>\
<div id="ca<%id%>">\
<p class="add-a-comment">Add a comment\
(<a href="#" class="comment-markup" id="ab<%id%>">markup</a>):</p>\
<div class="comment-markup-box" id="mb<%id%>">\
reStructured text markup: <i>*emph*</i>, <b>**strong**</b>, \
<code>``code``</code>, \
code blocks: <code>::</code> and an indented block after blank line</div>\
<form method="post" id="cf<%id%>" class="comment-form" action="">\
<textarea name="comment" cols="80"></textarea>\
<p class="propose-button">\
<a href="#" id="pc<%id%>" class="show-propose-change">\
Propose a change ▹\
</a>\
<a href="#" id="hc<%id%>" class="hide-propose-change">\
Propose a change ▿\
</a>\
</p>\
<textarea name="proposal" id="pt<%id%>" cols="80"\
spellcheck="false"></textarea>\
<input type="submit" value="Add comment" />\
<input type="hidden" name="node" value="<%id%>" />\
<input type="hidden" name="parent" value="" />\
</form>\
</div>\
</div>';
var commentTemplate = '\
<div id="cd<%id%>" class="sphinx-comment<%css_class%>">\
<div class="vote">\
<div class="arrow">\
<a href="#" id="uv<%id%>" class="vote" title="vote up">\
<img src="<%upArrow%>" />\
</a>\
<a href="#" id="uu<%id%>" class="un vote" title="vote up">\
<img src="<%upArrowPressed%>" />\
</a>\
</div>\
<div class="arrow">\
<a href="#" id="dv<%id%>" class="vote" title="vote down">\
<img src="<%downArrow%>" id="da<%id%>" />\
</a>\
<a href="#" id="du<%id%>" class="un vote" title="vote down">\
<img src="<%downArrowPressed%>" />\
</a>\
</div>\
</div>\
<div class="comment-content">\
<p class="tagline comment">\
<span class="user-id"><%username%></span>\
<span class="rating"><%pretty_rating%></span>\
<span class="delta"><%time.delta%></span>\
</p>\
<div class="comment-text comment"><#text#></div>\
<p class="comment-opts comment">\
<a href="#" class="reply hidden" id="rl<%id%>">reply ▹</a>\
<a href="#" class="close-reply" id="cr<%id%>">reply ▿</a>\
<a href="#" id="sp<%id%>" class="show-proposal">proposal ▹</a>\
<a href="#" id="hp<%id%>" class="hide-proposal">proposal ▿</a>\
<a href="#" id="dc<%id%>" class="delete-comment hidden">delete</a>\
<span id="cm<%id%>" class="moderation hidden">\
<a href="#" id="ac<%id%>" class="accept-comment">accept</a>\
</span>\
</p>\
<pre class="proposal" id="pr<%id%>">\
<#proposal_diff#>\
</pre>\
<ul class="comment-children" id="cl<%id%>"></ul>\
</div>\
<div class="clearleft"></div>\
</div>\
</div>';
var replyTemplate = '\
<li>\
<div class="reply-div" id="rd<%id%>">\
<form id="rf<%id%>">\
<textarea name="comment" cols="80"></textarea>\
<input type="submit" value="Add reply" />\
<input type="button" value="Cancel" />\
<input type="hidden" name="parent" value="<%id%>" />\
<input type="hidden" name="node" value="" />\
</form>\
</div>\
</li>';
$(document).ready(function() {
init();
});
})(jQuery);
$(document).ready(function() {
// add comment anchors for all paragraphs that are commentable
$('.sphinx-has-comment').comment();
// highlight search words in search results
$("div.context").each(function() {
var params = $.getQueryParameters();
var terms = (params.q) ? params.q[0].split(/\s+/) : [];
var result = $(this);
$.each(terms, function() {
result.highlightText(this.toLowerCase(), 'highlighted');
});
});
// directly open comment window if requested
var anchor = document.location.hash;
if (anchor.substring(0, 9) == '#comment-') {
$('#ao' + anchor.substring(9)).click();
document.location.hash = '#s' + anchor.substring(9);
}
}); | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/doc/build/html/_static/websupport.js | websupport.js |
* Porter Stemmer
*/
var Stemmer = function() {
var step2list = {
ational: 'ate',
tional: 'tion',
enci: 'ence',
anci: 'ance',
izer: 'ize',
bli: 'ble',
alli: 'al',
entli: 'ent',
eli: 'e',
ousli: 'ous',
ization: 'ize',
ation: 'ate',
ator: 'ate',
alism: 'al',
iveness: 'ive',
fulness: 'ful',
ousness: 'ous',
aliti: 'al',
iviti: 'ive',
biliti: 'ble',
logi: 'log'
};
var step3list = {
icate: 'ic',
ative: '',
alize: 'al',
iciti: 'ic',
ical: 'ic',
ful: '',
ness: ''
};
var c = "[^aeiou]"; // consonant
var v = "[aeiouy]"; // vowel
var C = c + "[^aeiouy]*"; // consonant sequence
var V = v + "[aeiou]*"; // vowel sequence
var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
var s_v = "^(" + C + ")?" + v; // vowel in stem
this.stemWord = function (w) {
var stem;
var suffix;
var firstch;
var origword = w;
if (w.length < 3)
return w;
var re;
var re2;
var re3;
var re4;
firstch = w.substr(0,1);
if (firstch == "y")
w = firstch.toUpperCase() + w.substr(1);
// Step 1a
re = /^(.+?)(ss|i)es$/;
re2 = /^(.+?)([^s])s$/;
if (re.test(w))
w = w.replace(re,"$1$2");
else if (re2.test(w))
w = w.replace(re2,"$1$2");
// Step 1b
re = /^(.+?)eed$/;
re2 = /^(.+?)(ed|ing)$/;
if (re.test(w)) {
var fp = re.exec(w);
re = new RegExp(mgr0);
if (re.test(fp[1])) {
re = /.$/;
w = w.replace(re,"");
}
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
re2 = new RegExp(s_v);
if (re2.test(stem)) {
w = stem;
re2 = /(at|bl|iz)$/;
re3 = new RegExp("([^aeiouylsz])\\1$");
re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re2.test(w))
w = w + "e";
else if (re3.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
else if (re4.test(w))
w = w + "e";
}
}
// Step 1c
re = /^(.+?)y$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(s_v);
if (re.test(stem))
w = stem + "i";
}
// Step 2
re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step2list[suffix];
}
// Step 3
re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step3list[suffix];
}
// Step 4
re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
re2 = /^(.+?)(s|t)(ion)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
if (re.test(stem))
w = stem;
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1] + fp[2];
re2 = new RegExp(mgr1);
if (re2.test(stem))
w = stem;
}
// Step 5
re = /^(.+?)e$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
re2 = new RegExp(meq1);
re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
w = stem;
}
re = /ll$/;
re2 = new RegExp(mgr1);
if (re.test(w) && re2.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
// and turn initial Y back to y
if (firstch == "y")
w = firstch.toLowerCase() + w.substr(1);
return w;
}
}
/**
* Simple result scoring code.
*/
var Scorer = {
// Implement the following function to further tweak the score for each result
// The function takes a result array [filename, title, anchor, descr, score]
// and returns the new score.
/*
score: function(result) {
return result[4];
},
*/
// query matches the full name of an object
objNameMatch: 11,
// or matches in the last dotted part of the object name
objPartialMatch: 6,
// Additive scores depending on the priority of the object
objPrio: {0: 15, // used to be importantResults
1: 5, // used to be objectResults
2: -5}, // used to be unimportantResults
// Used when the priority is not in the mapping.
objPrioDefault: 0,
// query found in title
title: 15,
// query found in terms
term: 5
};
var splitChars = (function() {
var result = {};
var singles = [96, 180, 187, 191, 215, 247, 749, 885, 903, 907, 909, 930, 1014, 1648,
1748, 1809, 2416, 2473, 2481, 2526, 2601, 2609, 2612, 2615, 2653, 2702,
2706, 2729, 2737, 2740, 2857, 2865, 2868, 2910, 2928, 2948, 2961, 2971,
2973, 3085, 3089, 3113, 3124, 3213, 3217, 3241, 3252, 3295, 3341, 3345,
3369, 3506, 3516, 3633, 3715, 3721, 3736, 3744, 3748, 3750, 3756, 3761,
3781, 3912, 4239, 4347, 4681, 4695, 4697, 4745, 4785, 4799, 4801, 4823,
4881, 5760, 5901, 5997, 6313, 7405, 8024, 8026, 8028, 8030, 8117, 8125,
8133, 8181, 8468, 8485, 8487, 8489, 8494, 8527, 11311, 11359, 11687, 11695,
11703, 11711, 11719, 11727, 11735, 12448, 12539, 43010, 43014, 43019, 43587,
43696, 43713, 64286, 64297, 64311, 64317, 64319, 64322, 64325, 65141];
var i, j, start, end;
for (i = 0; i < singles.length; i++) {
result[singles[i]] = true;
}
var ranges = [[0, 47], [58, 64], [91, 94], [123, 169], [171, 177], [182, 184], [706, 709],
[722, 735], [741, 747], [751, 879], [888, 889], [894, 901], [1154, 1161],
[1318, 1328], [1367, 1368], [1370, 1376], [1416, 1487], [1515, 1519], [1523, 1568],
[1611, 1631], [1642, 1645], [1750, 1764], [1767, 1773], [1789, 1790], [1792, 1807],
[1840, 1868], [1958, 1968], [1970, 1983], [2027, 2035], [2038, 2041], [2043, 2047],
[2070, 2073], [2075, 2083], [2085, 2087], [2089, 2307], [2362, 2364], [2366, 2383],
[2385, 2391], [2402, 2405], [2419, 2424], [2432, 2436], [2445, 2446], [2449, 2450],
[2483, 2485], [2490, 2492], [2494, 2509], [2511, 2523], [2530, 2533], [2546, 2547],
[2554, 2564], [2571, 2574], [2577, 2578], [2618, 2648], [2655, 2661], [2672, 2673],
[2677, 2692], [2746, 2748], [2750, 2767], [2769, 2783], [2786, 2789], [2800, 2820],
[2829, 2830], [2833, 2834], [2874, 2876], [2878, 2907], [2914, 2917], [2930, 2946],
[2955, 2957], [2966, 2968], [2976, 2978], [2981, 2983], [2987, 2989], [3002, 3023],
[3025, 3045], [3059, 3076], [3130, 3132], [3134, 3159], [3162, 3167], [3170, 3173],
[3184, 3191], [3199, 3204], [3258, 3260], [3262, 3293], [3298, 3301], [3312, 3332],
[3386, 3388], [3390, 3423], [3426, 3429], [3446, 3449], [3456, 3460], [3479, 3481],
[3518, 3519], [3527, 3584], [3636, 3647], [3655, 3663], [3674, 3712], [3717, 3718],
[3723, 3724], [3726, 3731], [3752, 3753], [3764, 3772], [3774, 3775], [3783, 3791],
[3802, 3803], [3806, 3839], [3841, 3871], [3892, 3903], [3949, 3975], [3980, 4095],
[4139, 4158], [4170, 4175], [4182, 4185], [4190, 4192], [4194, 4196], [4199, 4205],
[4209, 4212], [4226, 4237], [4250, 4255], [4294, 4303], [4349, 4351], [4686, 4687],
[4702, 4703], [4750, 4751], [4790, 4791], [4806, 4807], [4886, 4887], [4955, 4968],
[4989, 4991], [5008, 5023], [5109, 5120], [5741, 5742], [5787, 5791], [5867, 5869],
[5873, 5887], [5906, 5919], [5938, 5951], [5970, 5983], [6001, 6015], [6068, 6102],
[6104, 6107], [6109, 6111], [6122, 6127], [6138, 6159], [6170, 6175], [6264, 6271],
[6315, 6319], [6390, 6399], [6429, 6469], [6510, 6511], [6517, 6527], [6572, 6592],
[6600, 6607], [6619, 6655], [6679, 6687], [6741, 6783], [6794, 6799], [6810, 6822],
[6824, 6916], [6964, 6980], [6988, 6991], [7002, 7042], [7073, 7085], [7098, 7167],
[7204, 7231], [7242, 7244], [7294, 7400], [7410, 7423], [7616, 7679], [7958, 7959],
[7966, 7967], [8006, 8007], [8014, 8015], [8062, 8063], [8127, 8129], [8141, 8143],
[8148, 8149], [8156, 8159], [8173, 8177], [8189, 8303], [8306, 8307], [8314, 8318],
[8330, 8335], [8341, 8449], [8451, 8454], [8456, 8457], [8470, 8472], [8478, 8483],
[8506, 8507], [8512, 8516], [8522, 8525], [8586, 9311], [9372, 9449], [9472, 10101],
[10132, 11263], [11493, 11498], [11503, 11516], [11518, 11519], [11558, 11567],
[11622, 11630], [11632, 11647], [11671, 11679], [11743, 11822], [11824, 12292],
[12296, 12320], [12330, 12336], [12342, 12343], [12349, 12352], [12439, 12444],
[12544, 12548], [12590, 12592], [12687, 12689], [12694, 12703], [12728, 12783],
[12800, 12831], [12842, 12880], [12896, 12927], [12938, 12976], [12992, 13311],
[19894, 19967], [40908, 40959], [42125, 42191], [42238, 42239], [42509, 42511],
[42540, 42559], [42592, 42593], [42607, 42622], [42648, 42655], [42736, 42774],
[42784, 42785], [42889, 42890], [42893, 43002], [43043, 43055], [43062, 43071],
[43124, 43137], [43188, 43215], [43226, 43249], [43256, 43258], [43260, 43263],
[43302, 43311], [43335, 43359], [43389, 43395], [43443, 43470], [43482, 43519],
[43561, 43583], [43596, 43599], [43610, 43615], [43639, 43641], [43643, 43647],
[43698, 43700], [43703, 43704], [43710, 43711], [43715, 43738], [43742, 43967],
[44003, 44015], [44026, 44031], [55204, 55215], [55239, 55242], [55292, 55295],
[57344, 63743], [64046, 64047], [64110, 64111], [64218, 64255], [64263, 64274],
[64280, 64284], [64434, 64466], [64830, 64847], [64912, 64913], [64968, 65007],
[65020, 65135], [65277, 65295], [65306, 65312], [65339, 65344], [65371, 65381],
[65471, 65473], [65480, 65481], [65488, 65489], [65496, 65497]];
for (i = 0; i < ranges.length; i++) {
start = ranges[i][0];
end = ranges[i][1];
for (j = start; j <= end; j++) {
result[j] = true;
}
}
return result;
})();
function splitQuery(query) {
var result = [];
var start = -1;
for (var i = 0; i < query.length; i++) {
if (splitChars[query.charCodeAt(i)]) {
if (start !== -1) {
result.push(query.slice(start, i));
start = -1;
}
} else if (start === -1) {
start = i;
}
}
if (start !== -1) {
result.push(query.slice(start));
}
return result;
}
/**
* Search Module
*/
var Search = {
_index : null,
_queued_query : null,
_pulse_status : -1,
init : function() {
var params = $.getQueryParameters();
if (params.q) {
var query = params.q[0];
$('input[name="q"]')[0].value = query;
this.performSearch(query);
}
},
loadIndex : function(url) {
$.ajax({type: "GET", url: url, data: null,
dataType: "script", cache: true,
complete: function(jqxhr, textstatus) {
if (textstatus != "success") {
document.getElementById("searchindexloader").src = url;
}
}});
},
setIndex : function(index) {
var q;
this._index = index;
if ((q = this._queued_query) !== null) {
this._queued_query = null;
Search.query(q);
}
},
hasIndex : function() {
return this._index !== null;
},
deferQuery : function(query) {
this._queued_query = query;
},
stopPulse : function() {
this._pulse_status = 0;
},
startPulse : function() {
if (this._pulse_status >= 0)
return;
function pulse() {
var i;
Search._pulse_status = (Search._pulse_status + 1) % 4;
var dotString = '';
for (i = 0; i < Search._pulse_status; i++)
dotString += '.';
Search.dots.text(dotString);
if (Search._pulse_status > -1)
window.setTimeout(pulse, 500);
}
pulse();
},
/**
* perform a search for something (or wait until index is loaded)
*/
performSearch : function(query) {
// create the required interface elements
this.out = $('#search-results');
this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
this.dots = $('<span></span>').appendTo(this.title);
this.status = $('<p style="display: none"></p>').appendTo(this.out);
this.output = $('<ul class="search"/>').appendTo(this.out);
$('#search-progress').text(_('Preparing search...'));
this.startPulse();
// index already loaded, the browser was quick!
if (this.hasIndex())
this.query(query);
else
this.deferQuery(query);
},
/**
* execute search (requires search index to be loaded)
*/
query : function(query) {
var i;
var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"];
// stem the searchterms and add them to the correct list
var stemmer = new Stemmer();
var searchterms = [];
var excluded = [];
var hlterms = [];
var tmp = splitQuery(query);
var objectterms = [];
for (i = 0; i < tmp.length; i++) {
if (tmp[i] !== "") {
objectterms.push(tmp[i].toLowerCase());
}
if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
tmp[i] === "") {
// skip this "word"
continue;
}
// stem the word
var word = stemmer.stemWord(tmp[i].toLowerCase());
// prevent stemmer from cutting word smaller than two chars
if(word.length < 3 && tmp[i].length >= 3) {
word = tmp[i];
}
var toAppend;
// select the correct list
if (word[0] == '-') {
toAppend = excluded;
word = word.substr(1);
}
else {
toAppend = searchterms;
hlterms.push(tmp[i].toLowerCase());
}
// only add if not already in the list
if (!$u.contains(toAppend, word))
toAppend.push(word);
}
var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
// console.debug('SEARCH: searching for:');
// console.info('required: ', searchterms);
// console.info('excluded: ', excluded);
// prepare search
var terms = this._index.terms;
var titleterms = this._index.titleterms;
// array of [filename, title, anchor, descr, score]
var results = [];
$('#search-progress').empty();
// lookup as object
for (i = 0; i < objectterms.length; i++) {
var others = [].concat(objectterms.slice(0, i),
objectterms.slice(i+1, objectterms.length));
results = results.concat(this.performObjectSearch(objectterms[i], others));
}
// lookup as search terms in fulltext
results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));
// let the scorer override scores with a custom scoring function
if (Scorer.score) {
for (i = 0; i < results.length; i++)
results[i][4] = Scorer.score(results[i]);
}
// now sort the results by score (in opposite order of appearance, since the
// display function below uses pop() to retrieve items) and then
// alphabetically
results.sort(function(a, b) {
var left = a[4];
var right = b[4];
if (left > right) {
return 1;
} else if (left < right) {
return -1;
} else {
// same score: sort alphabetically
left = a[1].toLowerCase();
right = b[1].toLowerCase();
return (left > right) ? -1 : ((left < right) ? 1 : 0);
}
});
// for debugging
//Search.lastresults = results.slice(); // a copy
//console.info('search results:', Search.lastresults);
// print the results
var resultCount = results.length;
function displayNextItem() {
// results left, load the summary and display it
if (results.length) {
var item = results.pop();
var listItem = $('<li style="display:none"></li>');
if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
// dirhtml builder
var dirname = item[0] + '/';
if (dirname.match(/\/index\/$/)) {
dirname = dirname.substring(0, dirname.length-6);
} else if (dirname == 'index/') {
dirname = '';
}
listItem.append($('<a/>').attr('href',
DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
highlightstring + item[2]).html(item[1]));
} else {
// normal html builders
listItem.append($('<a/>').attr('href',
item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
highlightstring + item[2]).html(item[1]));
}
if (item[3]) {
listItem.append($('<span> (' + item[3] + ')</span>'));
Search.output.append(listItem);
listItem.slideDown(5, function() {
displayNextItem();
});
} else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
var suffix = DOCUMENTATION_OPTIONS.SOURCELINK_SUFFIX;
if (suffix === undefined) {
suffix = '.txt';
}
$.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + (item[5].slice(-suffix.length) === suffix ? '' : suffix),
dataType: "text",
complete: function(jqxhr, textstatus) {
var data = jqxhr.responseText;
if (data !== '' && data !== undefined) {
listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
}
Search.output.append(listItem);
listItem.slideDown(5, function() {
displayNextItem();
});
}});
} else {
// no source available, just display title
Search.output.append(listItem);
listItem.slideDown(5, function() {
displayNextItem();
});
}
}
// search finished, update title and status message
else {
Search.stopPulse();
Search.title.text(_('Search Results'));
if (!resultCount)
Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
else
Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
Search.status.fadeIn(500);
}
}
displayNextItem();
},
/**
* search for object names
*/
performObjectSearch : function(object, otherterms) {
var filenames = this._index.filenames;
var docnames = this._index.docnames;
var objects = this._index.objects;
var objnames = this._index.objnames;
var titles = this._index.titles;
var i;
var results = [];
for (var prefix in objects) {
for (var name in objects[prefix]) {
var fullname = (prefix ? prefix + '.' : '') + name;
if (fullname.toLowerCase().indexOf(object) > -1) {
var score = 0;
var parts = fullname.split('.');
// check for different match types: exact matches of full name or
// "last name" (i.e. last dotted part)
if (fullname == object || parts[parts.length - 1] == object) {
score += Scorer.objNameMatch;
// matches in last name
} else if (parts[parts.length - 1].indexOf(object) > -1) {
score += Scorer.objPartialMatch;
}
var match = objects[prefix][name];
var objname = objnames[match[1]][2];
var title = titles[match[0]];
// If more than one term searched for, we require other words to be
// found in the name/title/description
if (otherterms.length > 0) {
var haystack = (prefix + ' ' + name + ' ' +
objname + ' ' + title).toLowerCase();
var allfound = true;
for (i = 0; i < otherterms.length; i++) {
if (haystack.indexOf(otherterms[i]) == -1) {
allfound = false;
break;
}
}
if (!allfound) {
continue;
}
}
var descr = objname + _(', in ') + title;
var anchor = match[3];
if (anchor === '')
anchor = fullname;
else if (anchor == '-')
anchor = objnames[match[1]][1] + '-' + fullname;
// add custom score for some objects according to scorer
if (Scorer.objPrio.hasOwnProperty(match[2])) {
score += Scorer.objPrio[match[2]];
} else {
score += Scorer.objPrioDefault;
}
results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
}
}
}
return results;
},
/**
* search for full-text terms in the index
*/
performTermsSearch : function(searchterms, excluded, terms, titleterms) {
var docnames = this._index.docnames;
var filenames = this._index.filenames;
var titles = this._index.titles;
var i, j, file;
var fileMap = {};
var scoreMap = {};
var results = [];
// perform the search on the required terms
for (i = 0; i < searchterms.length; i++) {
var word = searchterms[i];
var files = [];
var _o = [
{files: terms[word], score: Scorer.term},
{files: titleterms[word], score: Scorer.title}
];
// no match but word was a required one
if ($u.every(_o, function(o){return o.files === undefined;})) {
break;
}
// found search word in contents
$u.each(_o, function(o) {
var _files = o.files;
if (_files === undefined)
return
if (_files.length === undefined)
_files = [_files];
files = files.concat(_files);
// set score for the word in each file to Scorer.term
for (j = 0; j < _files.length; j++) {
file = _files[j];
if (!(file in scoreMap))
scoreMap[file] = {}
scoreMap[file][word] = o.score;
}
});
// create the mapping
for (j = 0; j < files.length; j++) {
file = files[j];
if (file in fileMap)
fileMap[file].push(word);
else
fileMap[file] = [word];
}
}
// now check if the files don't contain excluded terms
for (file in fileMap) {
var valid = true;
// check if all requirements are matched
if (fileMap[file].length != searchterms.length)
continue;
// ensure that none of the excluded terms is in the search result
for (i = 0; i < excluded.length; i++) {
if (terms[excluded[i]] == file ||
titleterms[excluded[i]] == file ||
$u.contains(terms[excluded[i]] || [], file) ||
$u.contains(titleterms[excluded[i]] || [], file)) {
valid = false;
break;
}
}
// if we have still a valid result we can add it to the result list
if (valid) {
// select one (max) score for the file.
// for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
}
}
return results;
},
/**
* helper function to return a node containing the
* search summary for a given text. keywords is a list
* of stemmed words, hlwords is the list of normal, unstemmed
* words. the first one is used to find the occurrence, the
* latter for highlighting it.
*/
makeSearchSummary : function(text, keywords, hlwords) {
var textLower = text.toLowerCase();
var start = 0;
$.each(keywords, function() {
var i = textLower.indexOf(this.toLowerCase());
if (i > -1)
start = i;
});
start = Math.max(start - 120, 0);
var excerpt = ((start > 0) ? '...' : '') +
$.trim(text.substr(start, 240)) +
((start + 240 - text.length) ? '...' : '');
var rv = $('<div class="context"></div>').text(excerpt);
$.each(hlwords, function() {
rv = rv.highlightText(this, 'highlighted');
});
return rv;
}
};
$(document).ready(function() {
Search.init();
}); | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/doc/build/html/_static/searchtools.js | searchtools.js |
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"sphinx-rtd-theme":[function(require,module,exports){
var jQuery = (typeof(window) != 'undefined') ? window.jQuery : require('jquery');
// Sphinx theme nav state
function ThemeNav () {
var nav = {
navBar: null,
win: null,
winScroll: false,
winResize: false,
linkScroll: false,
winPosition: 0,
winHeight: null,
docHeight: null,
isRunning: false
};
nav.enable = function () {
var self = this;
if (!self.isRunning) {
self.isRunning = true;
jQuery(function ($) {
self.init($);
self.reset();
self.win.on('hashchange', self.reset);
// Set scroll monitor
self.win.on('scroll', function () {
if (!self.linkScroll) {
self.winScroll = true;
}
});
setInterval(function () { if (self.winScroll) self.onScroll(); }, 25);
// Set resize monitor
self.win.on('resize', function () {
self.winResize = true;
});
setInterval(function () { if (self.winResize) self.onResize(); }, 25);
self.onResize();
});
};
};
nav.init = function ($) {
var doc = $(document),
self = this;
this.navBar = $('div.wy-side-scroll:first');
this.win = $(window);
// Set up javascript UX bits
$(document)
// Shift nav in mobile when clicking the menu.
.on('click', "[data-toggle='wy-nav-top']", function() {
$("[data-toggle='wy-nav-shift']").toggleClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
})
// Nav menu link click operations
.on('click', ".wy-menu-vertical .current ul li a", function() {
var target = $(this);
// Close menu when you click a link.
$("[data-toggle='wy-nav-shift']").removeClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
// Handle dynamic display of l3 and l4 nav lists
self.toggleCurrent(target);
self.hashChange();
})
.on('click', "[data-toggle='rst-current-version']", function() {
$("[data-toggle='rst-versions']").toggleClass("shift-up");
})
// Make tables responsive
$("table.docutils:not(.field-list)")
.wrap("<div class='wy-table-responsive'></div>");
// Add expand links to all parents of nested ul
$('.wy-menu-vertical ul').not('.simple').siblings('a').each(function () {
var link = $(this);
expand = $('<span class="toctree-expand"></span>');
expand.on('click', function (ev) {
self.toggleCurrent(link);
ev.stopPropagation();
return false;
});
link.prepend(expand);
});
};
nav.reset = function () {
// Get anchor from URL and open up nested nav
var anchor = encodeURI(window.location.hash);
if (anchor) {
try {
var link = $('.wy-menu-vertical')
.find('[href="' + anchor + '"]');
// If we didn't find a link, it may be because we clicked on
// something that is not in the sidebar (eg: when using
// sphinxcontrib.httpdomain it generates headerlinks but those
// aren't picked up and placed in the toctree). So let's find
// the closest header in the document and try with that one.
if (link.length === 0) {
var doc_link = $('.document a[href="' + anchor + '"]');
var closest_section = doc_link.closest('div.section');
// Try again with the closest section entry.
link = $('.wy-menu-vertical')
.find('[href="#' + closest_section.attr("id") + '"]');
}
$('.wy-menu-vertical li.toctree-l1 li.current')
.removeClass('current');
link.closest('li.toctree-l2').addClass('current');
link.closest('li.toctree-l3').addClass('current');
link.closest('li.toctree-l4').addClass('current');
}
catch (err) {
console.log("Error expanding nav for anchor", err);
}
}
};
nav.onScroll = function () {
this.winScroll = false;
var newWinPosition = this.win.scrollTop(),
winBottom = newWinPosition + this.winHeight,
navPosition = this.navBar.scrollTop(),
newNavPosition = navPosition + (newWinPosition - this.winPosition);
if (newWinPosition < 0 || winBottom > this.docHeight) {
return;
}
this.navBar.scrollTop(newNavPosition);
this.winPosition = newWinPosition;
};
nav.onResize = function () {
this.winResize = false;
this.winHeight = this.win.height();
this.docHeight = $(document).height();
};
nav.hashChange = function () {
this.linkScroll = true;
this.win.one('hashchange', function () {
this.linkScroll = false;
});
};
nav.toggleCurrent = function (elem) {
var parent_li = elem.closest('li');
parent_li.siblings('li.current').removeClass('current');
parent_li.siblings().find('li.current').removeClass('current');
parent_li.find('> ul li.current').removeClass('current');
parent_li.toggleClass('current');
}
return nav;
};
module.exports.ThemeNav = ThemeNav();
if (typeof(window) != 'undefined') {
window.SphinxRtdTheme = { StickyNav: module.exports.ThemeNav };
}
},{"jquery":"jquery"}]},{},["sphinx-rtd-theme"]); | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/doc/build/html/_static/js/theme.js | theme.js |
;window.Modernizr=function(a,b,c){function D(a){j.cssText=a}function E(a,b){return D(n.join(a+";")+(b||""))}function F(a,b){return typeof a===b}function G(a,b){return!!~(""+a).indexOf(b)}function H(a,b){for(var d in a){var e=a[d];if(!G(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function I(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:F(f,"function")?f.bind(d||b):f}return!1}function J(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return F(b,"string")||F(b,"undefined")?H(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),I(e,b,c))}function K(){e.input=function(c){for(var d=0,e=c.length;d<e;d++)u[c[d]]=c[d]in k;return u.list&&(u.list=!!b.createElement("datalist")&&!!a.HTMLDataListElement),u}("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")),e.inputtypes=function(a){for(var d=0,e,f,h,i=a.length;d<i;d++)k.setAttribute("type",f=a[d]),e=k.type!=="text",e&&(k.value=l,k.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(f)&&k.style.WebkitAppearance!==c?(g.appendChild(k),h=b.defaultView,e=h.getComputedStyle&&h.getComputedStyle(k,null).WebkitAppearance!=="textfield"&&k.offsetHeight!==0,g.removeChild(k)):/^(search|tel)$/.test(f)||(/^(url|email)$/.test(f)?e=k.checkValidity&&k.checkValidity()===!1:e=k.value!=l)),t[a[d]]=!!e;return t}("search tel url email datetime date month week time datetime-local number range color".split(" "))}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k=b.createElement("input"),l=":)",m={}.toString,n=" -webkit- -moz- -o- -ms- ".split(" "),o="Webkit Moz O ms",p=o.split(" "),q=o.toLowerCase().split(" "),r={svg:"http://www.w3.org/2000/svg"},s={},t={},u={},v=[],w=v.slice,x,y=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["­",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return y("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},A=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=F(e[d],"function"),F(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),B={}.hasOwnProperty,C;!F(B,"undefined")&&!F(B.call,"undefined")?C=function(a,b){return B.call(a,b)}:C=function(a,b){return b in a&&F(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return J("flexWrap")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.canvastext=function(){return!!e.canvas&&!!F(b.createElement("canvas").getContext("2d").fillText,"function")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.websqldatabase=function(){return!!a.openDatabase},s.indexedDB=function(){return!!J("indexedDB",a)},s.hashchange=function(){return A("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},s.history=function(){return!!a.history&&!!history.pushState},s.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return D("background-color:rgba(150,255,150,.5)"),G(j.backgroundColor,"rgba")},s.hsla=function(){return D("background-color:hsla(120,40%,100%,.5)"),G(j.backgroundColor,"rgba")||G(j.backgroundColor,"hsla")},s.multiplebgs=function(){return D("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.backgroundsize=function(){return J("backgroundSize")},s.borderimage=function(){return J("borderImage")},s.borderradius=function(){return J("borderRadius")},s.boxshadow=function(){return J("boxShadow")},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return E("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return J("animationName")},s.csscolumns=function(){return J("columnCount")},s.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return D((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),G(j.backgroundImage,"gradient")},s.cssreflections=function(){return J("boxReflect")},s.csstransforms=function(){return!!J("transform")},s.csstransforms3d=function(){var a=!!J("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return J("transition")},s.fontface=function(){var a;return y('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect},s.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==r.svg},s.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(m.call(b.createElementNS(r.svg,"animate")))},s.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(m.call(b.createElementNS(r.svg,"clipPath")))};for(var L in s)C(s,L)&&(x=L.toLowerCase(),e[x]=s[L](),v.push((e[x]?"":"no-")+x));return e.input||K(),e.addTest=function(a,b){if(typeof a=="object")for(var d in a)C(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},D(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.mq=z,e.hasEvent=A,e.testProp=function(a){return H([a])},e.testAllProps=J,e.testStyles=y,e.prefixed=function(a,b,c){return b?J(a,b,c):J(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+v.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))}; | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/doc/build/html/_static/js/modernizr.min.js | modernizr.min.js |
# Copyright (c) 2006, 2011, 2013-2017 Matthew Zipay.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""This module defines "dummy" classes and functions for Aglyph unit and
functional tests.
All keywords and class members use the module constant ``DEFAULT`` as a
default value in order to differentiate them from ``None`` (for easier
testing).
"""
__author__ = "Matthew Zipay <[email protected]>"
from aglyph import __version__
__all__ = [
"DEFAULT",
"factory_function",
"MODULE_MEMBER",
"ModuleClass",
"outer_function",
]
#: used as a default value (instead of ``None``; makes tests more explicit)
DEFAULT = object()
#: A sentinel value to force exceptions to be raised.
RAISE = object()
#PYVER: extending object is implicit in Python >= 3.0
class _LifecycleMethodsMixin(object):
def reset_lifecycle_counts(self):
self.called_context_after_inject = 0
self.called_template_after_inject = 0
self.called_component_after_inject = 0
self.called_component_before_clear = 0
self.called_template_before_clear = 0
self.called_context_before_clear = 0
def context_after_inject(self):
self.called_context_after_inject += 1
def template_after_inject(self):
self.called_template_after_inject += 1
def component_after_inject(self):
self.called_component_after_inject += 1
def component_before_clear(self):
self.called_component_before_clear += 1
def template_before_clear(self):
self.called_template_before_clear += 1
def context_before_clear(self):
self.called_context_before_clear += 1
class ModuleClass(_LifecycleMethodsMixin):
class NestedClass(_LifecycleMethodsMixin):
@staticmethod
def staticmethod_factory():
return ModuleClass.NestedClass(DEFAULT, keyword=DEFAULT)
@classmethod
def classmethod_factory(cls, keyword=DEFAULT):
return cls(DEFAULT, keyword=keyword)
def __init__(self, arg, keyword=DEFAULT):
self.arg = arg
self.keyword = keyword
self.attr = DEFAULT
self._prop = DEFAULT
self.__value = DEFAULT
self.reset_lifecycle_counts()
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
self._prop = value
def get_value(self):
return self.__value
def set_value(self, value):
self.__value = value
CLASS_MEMBER = NestedClass("module-level class member")
@staticmethod
def staticmethod_factory(arg):
return ModuleClass(arg, keyword=DEFAULT)
@classmethod
def classmethod_factory(cls, arg, keyword=DEFAULT):
return cls(arg, keyword=keyword)
def __init__(self, arg, keyword=DEFAULT):
if arg is RAISE:
raise RuntimeError("__init__ RAISE")
self.arg = arg
self.keyword = keyword
self.attr = DEFAULT
self._prop = DEFAULT
self.__value = DEFAULT
self.reset_lifecycle_counts()
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
if value is RAISE:
raise RuntimeError("@prop.setter RAISE")
self._prop = value
def get_value(self):
return self.__value
def set_value(self, value):
if value is RAISE:
raise RuntimeError("set_value RAISE")
self.__value = value
def method(self):
pass
MODULE_MEMBER = ModuleClass("dummy module member")
def factory_function(arg, keyword=DEFAULT):
if arg is RAISE:
raise RuntimeError("factory_function RAISE")
return ModuleClass(arg, keyword=keyword)
def outer_function():
def nested_function():
return DEFAULT
return nested_function | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/test/dummy.py | dummy.py |
# Copyright (c) 2006, 2011, 2013-2017 Matthew Zipay.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""Utilities and common setup for all unit test modules."""
__author__ = "Matthew Zipay <[email protected]>"
import codecs
from inspect import getsourcefile
import logging
import logging.config
import os
import unittest
from aglyph._compat import DataType, is_python_3
# always force tracing when running test suite
os.environ["AUTOLOGGING_TRACED_NOOP"] = ""
os.environ["AGLYPH_TRACED"] = "1"
from autologging import TRACE
__all__ = [
"assertRaisesWithMessage",
"find_resource",
"read_resource",
"suite",
]
#PYVER: can use TestCase.assertRaises as a context manager in 3.1+
def assertRaisesWithMessage(
test_case, e_expected, callable_, *args, **keywords):
"""Assert that *callable_* raises a specific exception, whose type
and message must match those of *e_expected*.
"""
try:
callable_(*args, **keywords)
except type(e_expected) as e_actual:
test_case.assertEqual(str(e_expected), str(e_actual))
else:
test_case.fail("did not raise %r" % e_expected)
def find_resource(relname):
"""Locate *relname* relative to the ``test`` package.
Return ``None`` if *relname* is not found.
"""
init_filename = getsourcefile(find_resource)
resource_filename = os.path.join(os.path.dirname(init_filename), relname)
return resource_filename if os.path.isfile(resource_filename) else None
def read_resource(relname, from_encoding="utf-8", to_encoding=None):
"""Return either unicode text or encoded bytes representing
the file system resource identified by *relname* (which must be
relative to the ``test`` package.
Return ``None`` if *relname* is not found.
"""
resource_filename = find_resource(relname)
if resource_filename is not None:
with codecs.open(resource_filename, encoding=from_encoding) as f:
resource = f.read()
return (
resource.encode(to_encoding) if to_encoding is not None
else resource)
def suite():
from test import (
# aglyph
test_format_dotted_name,
test_identify,
test_importable,
test_resolve_dotted_name,
# aglyph._compat
test_compat,
test_is_string,
test_name_of,
test_new_instance,
test_DoctypeTreeBuilder,
test_CLRXMLParser,
test_AglyphDefaultXMLParser,
# aglyph.component
test_Reference,
test_InitializationSupport,
test_Evaluator,
test_DependencySupport,
test_Template,
test_Component,
# aglyph.context
test_CreationBuilderMixin,
test_InjectionBuilderMixin,
test_LifecycleBuilderMixin,
test_RegistrationMixin,
test_TemplateBuilder,
test_ComponentBuilder,
test_ContextBuilder,
test_Context,
test_XMLContext,
# aglyph.assembler
test_ReentrantMutexCache,
test_Assembler,
)
suite = unittest.TestSuite()
# aglyph
suite.addTest(test_importable.suite())
suite.addTest(test_format_dotted_name.suite())
suite.addTest(test_resolve_dotted_name.suite())
suite.addTest(test_identify.suite())
# aglyph._compat
suite.addTest(test_compat.suite())
suite.addTest(test_is_string.suite())
suite.addTest(test_name_of.suite())
suite.addTest(test_new_instance.suite())
suite.addTest(test_DoctypeTreeBuilder.suite())
suite.addTest(test_CLRXMLParser.suite())
suite.addTest(test_AglyphDefaultXMLParser.suite())
# aglyph.component
suite.addTest(test_Reference.suite())
suite.addTest(test_InitializationSupport.suite())
suite.addTest(test_Evaluator.suite())
suite.addTest(test_DependencySupport.suite())
suite.addTest(test_Template.suite())
suite.addTest(test_Component.suite())
# aglyph.context
suite.addTest(test_CreationBuilderMixin.suite())
suite.addTest(test_InjectionBuilderMixin.suite())
suite.addTest(test_LifecycleBuilderMixin.suite())
suite.addTest(test_RegistrationMixin.suite())
suite.addTest(test_TemplateBuilder.suite())
suite.addTest(test_ComponentBuilder.suite())
suite.addTest(test_ContextBuilder.suite())
suite.addTest(test_Context.suite())
suite.addTest(test_XMLContext.suite())
# aglyph.assembler
suite.addTest(test_ReentrantMutexCache.suite())
suite.addTest(test_Assembler.suite())
return suite
logging.config.dictConfig({
"version": 1,
"formatters": {
"with-thread-id": {
"format":
"[%(levelname)-9s %(thread)08x %(name)s %(funcName)s]\n"
"%(message)s",
},
},
"handlers": {
"combined-file": {
"class": "logging.FileHandler",
"formatter": "with-thread-id",
"filename": os.path.normpath(
os.path.join(
os.path.dirname(suite.__code__.co_filename), "..",
"test.log")),
"mode": 'w'
},
},
"loggers": {
"test": {
"level": logging.DEBUG,
"propagate": False,
"handlers": ["combined-file"],
},
"aglyph": {
"level": TRACE,
"propagate": False,
"handlers": ["combined-file"],
}
},
})
# don't use __name__ here; can be run as "__main__"
_log = logging.getLogger("test")
# all the way down here so that the logging configuration is in place before
# anything from the "aglyph" namespace is imported
from aglyph import __version__ | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/test/__init__.py | __init__.py |
# Copyright (c) 2006, 2011, 2013-2018 Matthew Zipay.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""The classes in this module are used to define collections
("contexts") of related components and templates.
A context can be created in pure Python using the following API classes:
* :class:`aglyph.component.Template`
* :class:`aglyph.component.Component`
* :class:`aglyph.component.Reference` (used to indicate that one
component depends on another component)
* :class:`aglyph.component.Evaluator` (used like a partial function to
lazily evaluate component initialization arguments and attributes)
* :class:`aglyph.context.Context` or a subclass
.. versionadded:: 3.0.0
For easier programmatic configuration, refer to
:doc:`context-fluent-api`.
Alternatively, a context can be defined using a declarative XML syntax
that conforms to the :download:`Aglyph context DTD
<../../resources/aglyph-context.dtd>` (included in the *resources/*
directory of the distribution). This approach requires only the
:class:`aglyph.context.XMLContext` class, which parses the XML document
and then uses the API classes mentioned above to populate the context.
"""
__author__ = "Matthew Zipay <[email protected]>"
from ast import literal_eval
from collections import OrderedDict
from functools import partial
import logging
import sys
import xml.etree.ElementTree as ET
from autologging import logged, traced
from aglyph import AglyphError, _identify, __version__
from aglyph._compat import (
AglyphDefaultXMLParser,
DataType,
DoctypeTreeBuilder,
is_python_3,
name_of,
TextType,
)
from aglyph.component import (
Component,
Evaluator as evaluate,
Reference as ref,
Strategy,
Template,
)
__all__ = ["Context", "evaluate", "ref", "XMLContext"]
_log = logging.getLogger(__name__)
@traced
@logged
class _ContextBuilder(object):
"""Entry points for the Aglyph Context fluent API."""
def component(self, component_id_spec, parent=None):
"""Return a fluent :class:`Component` builder for
*component_id_spec*.
:arg component_id_spec:
a context-unique identifier for this component; or the object
whose dotted name will identify this component
:keyword parent:
the context-unique identifier for this component's parent
template or component definition; or the object whose dotted
name identifies this component's parent definition
.. versionadded:: 3.0.0
This method is an entry point into :doc:`context-fluent-api`.
"""
return _ComponentBuilder(
self, component_id_spec, parent=parent)
def prototype(self, component_id_spec, parent=None):
"""Return a :data:`prototype <aglyph.component.Strategy>`
:class:`Component` builder for a component identified by
*component_id_spec*.
:arg component_id_spec:
a context-unique identifier for this component; or the object
whose dotted name will identify this component
:keyword parent:
the context-unique identifier for this component's parent
template or component definition; or the object whose dotted
name identifies this component's parent definition
.. versionadded:: 3.0.0
This method is an entry point into :doc:`context-fluent-api`.
"""
return self.component(
component_id_spec, parent=parent).create(
strategy="prototype")
def singleton(self, component_id_spec, parent=None):
"""Return a :data:`singleton <aglyph.component.Strategy>`
:class:`Component` builder for a component identified by
*component_id_spec*.
:arg component_id_spec:
a context-unique identifier for this component; or the object
whose dotted name will identify this component
:keyword parent:
the context-unique identifier for this component's parent
template or component definition; or the object whose dotted
name identifies this component's parent definition
.. versionadded:: 3.0.0
This method is an entry point into :doc:`context-fluent-api`.
"""
return self.component(
component_id_spec, parent=parent).create(
strategy="singleton")
def borg(self, component_id_spec, parent=None):
"""Return a :data:`borg <aglyph.component.Strategy>`
:class:`Component` builder for a component identified by
*component_id_spec*.
:arg component_id_spec:
a context-unique identifier for this component; or the object
whose dotted name will identify this component
:keyword parent:
the context-unique identifier for this component's parent
template or component definition; or the object whose dotted
name identifies this component's parent definition
.. versionadded:: 3.0.0
This method is an entry point into :doc:`context-fluent-api`.
"""
return self.component(
component_id_spec, parent=parent).create(
strategy="borg")
def weakref(self, component_id_spec, parent=None):
"""Return a :data:`weakref <aglyph.component.Strategy>`
:class:`Component` builder for a component identified by
*component_id_spec*.
:arg component_id_spec:
a context-unique identifier for this component; or the object
whose dotted name will identify this component
:keyword parent:
the context-unique identifier for this component's parent
template or component definition; or the object whose dotted
name identifies this component's parent definition
.. versionadded:: 3.0.0
This method is an entry point into :doc:`context-fluent-api`.
"""
return self.component(
component_id_spec, parent=parent).create(
strategy="weakref")
def template(self, template_id_spec, parent=None):
"""Return a :class:`Template` builder for a template identified
by *template_spec*.
:arg template_id_spec:
a context-unique identifier for this template; or the object
whose dotted name will identify this template
:keyword parent:
the context-unique identifier for this template's parent
template or component definition; or the object whose dotted
name identifies this template's parent definition
.. versionadded:: 3.0.0
This method is an entry point into :doc:`context-fluent-api`.
"""
return _TemplateBuilder(
self, template_id_spec, parent=parent)
@traced
@logged
class _CreationBuilderMixin(object):
"""Methods to describe object creation."""
__slots__ = []
def create(
self, dotted_name=None, factory=None, member=None, strategy=None):
"""Specify the object creation aspects of a component being
defined.
:keyword dotted_name:
an **importable** dotted name or an object whose dotted name
will be introspected
:keyword factory:
names a :obj:`callable` member of the object represented by
the dotted name
:keyword member:
names **any** member of the object represented by the dotted
name
:keyword strategy:
specifies the component assembly strategy
:return:
*self* (to support chained calls)
Any keyword whose value is ``None`` will be ignored (i.e.
``None`` values are not explicitly set).
.. note::
The *member* and *strategy* keywords should be treated as
mutually exclusive. Any component definition that specifies a
*member* is implicitly assigned the special strategy
"_imported".
"""
# do not explicitly assign None values; calls can be chained
if dotted_name is not None:
self._dotted_name_spec = dotted_name
if factory is not None:
self._factory_name = factory
if member is not None:
self._member_name = member
if strategy is not None:
self._strategy = strategy
return self
@traced
@logged
class _InjectionBuilderMixin(object):
"""Methods to describe injected dependencies."""
__slots__ = []
def init(self, *args, **keywords):
"""Specify the initialization arguments (positional and
keyword) for templates and/or components.
:arg tuple args:
the positional initialization arguments
:arg dict keywords:
the keyword initialization arguments
:return:
*self* (to support chained calls)
.. note::
Successive calls to this method on the same instance have a
cumulative effect; the list of positional arguments is
extended, and the dictionary of keyword arguments is updated.
"""
self._args.extend(args)
self._keywords.update(keywords)
return self
def set(self, *pairs, **attributes):
"""Specify the setter (method/attribute/property) depdendencies
for tempaltes and/or components.
:arg pairs:
a sequence of (name, value) 2-tuples (optional)
:arg attributes:
a mapping of name->value dependencies
:return:
*self* (to support chained calls)
.. note::
Successive calls to this method on the same instance have a
cumulative effect (i.e. the attributes mapping is updated).
"""
self._attributes.update(pairs, **attributes)
return self
@traced
@logged
class _LifecycleBuilderMixin(object):
"""Methods to describe lifecyle method names."""
__slots__ = []
def call(self, after_inject=None, before_clear=None):
"""Specify the names of lifecycle methods to be called for
templates and/or components.
:arg after_inject:
the name of the method to call after a component has been
assembled but before it is returned to the caller
:arg before_clear:
the name of the method to call immediately before a
*singleton*, *borg*, or *weakref* object is evicted from
the internal cache
:return:
*self* (to support chained calls)
Any keyword whose value is ``None`` will be ignored (i.e.
``None`` values are not explicitly set).
"""
# do not explicitly assign None values; calls can be chained
if after_inject is not None:
self._after_inject = after_inject
if before_clear is not None:
self._before_clear = before_clear
return self
@traced
@logged
class _RegistrationMixin(object):
"""Methods to handle registering a template or component in a
context.
"""
__slots__ = []
def register(self):
"""Add a component or template definition to a context.
:return:
``None`` (terminates the fluent call sequence)
"""
definition = self._init_definition()
definition._args = self._args
definition._keywords = self._keywords
definition._attributes = self._attributes
self._context.register(definition)
# implicit return None terminates this fluent call sequence
def _init_definition(self):
"""Create the :class:`Component` or :class:`Template` definition
that will be registered in the :class:`Context`
"""
raise NotImplementedError()
@traced
@logged
class _TemplateBuilder(
_InjectionBuilderMixin, _LifecycleBuilderMixin, _RegistrationMixin):
"""Fluent context builder for :class:`Template` definitions."""
__slots__ = [
"_context",
"_unique_id_spec",
"_parent_id_spec",
"_args",
"_keywords",
"_attributes",
"_after_inject",
"_before_clear",
]
def __init__(self, context, unique_id_spec, parent=None):
self._context = context
self._unique_id_spec = unique_id_spec
self._parent_id_spec = parent
self._args = []
self._keywords = {}
self._attributes = OrderedDict()
self._after_inject = None
self._before_clear = None
def _init_definition(self):
return Template(
_identify(self._unique_id_spec),
parent_id=
_identify(self._parent_id_spec)
if self._parent_id_spec is not None
else None,
after_inject=self._after_inject,
before_clear=self._before_clear)
@traced
@logged
class _ComponentBuilder(_CreationBuilderMixin, _TemplateBuilder):
"""Fluent context builder for :class:`Component` definitions."""
__slots__ = [
"_dotted_name_spec",
"_factory_name",
"_member_name",
"_strategy",
]
def __init__(self, context, unique_id_spec, parent=None):
_TemplateBuilder.__init__(
self, context, unique_id_spec, parent=parent)
self._dotted_name_spec = None
self._factory_name = None
self._member_name = None
self._strategy = None
def _init_definition(self):
return Component(
_identify(self._unique_id_spec),
dotted_name=
_identify(self._dotted_name_spec)
if self._dotted_name_spec is not None
else None,
factory_name=self._factory_name,
member_name=self._member_name,
strategy=self._strategy,
parent_id=
_identify(self._parent_id_spec)
if self._parent_id_spec is not None
else None,
after_inject=self._after_inject,
before_clear=self._before_clear)
@traced
@logged
class Context(dict, _ContextBuilder):
"""A mapping of unique IDs to :class:`Component` and
:class:`Template` objects.
"""
def __init__(self, context_id, after_inject=None, before_clear=None):
"""
:arg str context_id:
an identifier for this context
:keyword str after_inject:
specifies the name of the method that will be called (if it
exists) on **all** component objects after all of their
dependencies have been injected
:keyword str before_clear:
specifies the name of the method that will be called (if it
exists) on **all** singleton, borg, and weakref objects
immediately before they are cleared from cache
"""
#PYVER: arguments to super() are implicit under Python 3
super(Context, self).__init__()
if not context_id:
raise AglyphError(
"%s ID must not be None or empty" % name_of(self.__class__))
self._context_id = context_id
self._after_inject = after_inject
self._before_clear = before_clear
@property
def context_id(self):
"""The context identifier *(read-only)*."""
return self._context_id
@property
def after_inject(self):
"""The name of the component object method that will be called
after **all** dependencies have been injected into that
component object *(read-only)*.
"""
return self._after_inject
@property
def before_clear(self):
"""The name of the component object method that will be called
immediately before the object is cleared from cache
*(read-only)*.
.. warning::
This property is not applicable to "prototype" component
objects, or to component objects acquired via
:attr:`Component.member_name`.
The named method is **not guaranteed** to be called for
"weakref" component objects.
"""
return self._before_clear
def register(self, definition):
"""Add a component or template *definition* to this context.
:arg definition:
a :class:`Component` or :class:`Template` object
:raise AglyphError:
if a component or template with the same unique ID is already
registered in this context
.. note::
To **replace** an already-registered component or template
with the same unique ID, use :meth:`dict.__setitem__`
directly.
"""
if definition.unique_id in self:
raise AglyphError(
"%s with ID %r already mapped in %s" % (
name_of(definition.__class__), definition.unique_id, self))
self[definition.unique_id] = definition
def get_component(self, component_id):
"""Return the :class:`Component` identified by *component_id*.
:arg str component_id:
a unique ID that identifies a :class:`Component`
:return:
the :class:`Component` identified by *component_id*
:rtype:
:class:`Component` if *component_id* is mapped, else ``None``
"""
obj = self.get(component_id)
return obj if isinstance(obj, Component) else None
def iter_components(self, strategy=None):
"""Yield all definitions in this context that are instances of
:class:`Component`, optionally filtered by *strategy*.
:keyword str strategy:
only yield component definitions that use this assembly
strategy (by default, **all** component definitions are
yielded)
:return:
a :class:`Component` generator
"""
for obj in self.values():
if (isinstance(obj, Component) and
(strategy in [None, obj.strategy])):
yield obj
def __str__(self):
return "<%s %r @%08x>" % (
name_of(self.__class__), self._context_id, id(self))
def __repr__(self):
return "%s.%s(%r, after_inject=%r, before_clear=%r)" % (
self.__class__.__module__, name_of(self.__class__),
self._context_id, self._after_inject, self._before_clear)
@traced
@logged
class XMLContext(Context):
"""A mapping of unique IDs to :class:`Component` and
:class:`Template` objects.
Components and templates are declared in an XML document that
conforms to the :download:`Aglyph context DTD
<../../resources/aglyph-context.dtd>` (included in the *resources/*
directory of the distribution).
"""
def __init__(
self, source, parser=None,
default_encoding=sys.getdefaultencoding()):
"""
:arg source:
a filename or stream from which XML data is read
:keyword xml.etree.ElementTree.XMLParser parser:
the ElementTree parser to use (instead of Aglyph's default)
:keyword str default_encoding:
the default character set used to encode certain element
content
:raise AglyphError:
if unexpected elements are encountered, or if expected
elements are *not* encountered, in the document structure
In most cases, *parser* should be left unspecified. Aglyph's
default parser will be sufficient for all but extreme edge
cases.
*default_encoding* is the character set used to encode
``<bytes>`` (or ``<str>`` under Python 2) element content when
an **@encoding** attribute is *not* specified on those elements.
It defaults to the system-dependent value of
:func:`sys.getdefaultencoding`. **This is not related to the
document encoding!**
.. note::
Aglyph uses a non-validating XML parser by default, so DTD
conformance is **not** enforced at runtime. It is recommended
that XML contexts be validated at least once (manually)
during testing.
An :class:`AglyphError` *will* be raised under certain
conditions (an unexpected element is encounted, or an
expected element is *not* encountered), but Aglyph does not
"reinvent the wheel" by implementing strict validation in
the parsing logic.
.. warning::
Although Aglyph contexts are :class:`dict` types,
``XMLContext`` does not permit the same unique ID to be
(re-)mapped multiple times.
Attempting to define more than one ``<component>`` or
``<template>`` with the same ID will raise
:class:`AglyphError` when the document is parsed.
**After** an Aglyph ``<context>`` document has been
successfully parsed, a unique component or template ID can be
re-mapped using standard :class:`dict` protocols.
.. seealso::
Validity constraint: ID
https://www.w3.org/TR/REC-xml/#id
"""
if parser is None:
parser = AglyphDefaultXMLParser(target=DoctypeTreeBuilder())
tree = ET.parse(source, parser=parser)
root = tree.getroot()
if root.tag != "context":
raise AglyphError("expected root <context>, not <%s>" % root.tag)
#PYVER: arguments to super() are implicit under Python 3
super(XMLContext, self).__init__(
root.get("id"), after_inject=root.get("after-inject"),
before_clear=root.get("before-clear"))
# alias the correct _parse_str method based on Python version
if is_python_3:
self._parse_str = self.__parse_str_as_text
else:
self._parse_str = self.__parse_str_as_data
self._default_encoding = default_encoding
for element in list(root):
if element.tag == "component":
depsupport = self._create_component(element)
elif element.tag == "template":
depsupport = self._create_template(element)
else:
raise AglyphError(
"unexpected element: /context/%s" % element.tag)
self.register(depsupport)
self._process_dependencies(depsupport, element)
self.__repr = "%s.%s(%r, parser=%r, default_encoding=%r)" % (
self.__class__.__module__, name_of(self.__class__),
source, parser, default_encoding)
@property
def default_encoding(self):
"""The default encoding of ``<bytes>`` (or ``<str>`` under
Python 2) element content when an **@encoding** attribute is
*not* specified.
.. note::
This is **unrelated** to the document encoding!
"""
return self._default_encoding
def _create_template(self, template_element):
"""Create a template object from a ``<template>`` element.
:arg xml.etree.ElementTree.Element template_element:
a ``<template>`` element
:return:
an Aglyph template object
:rtype:
:class:`aglyph.component.Template`
"""
return Template(
template_element.get("id"),
parent_id=template_element.get("parent-id"),
after_inject=template_element.get("after-inject"),
before_clear=template_element.get("before-clear")
)
def _create_component(self, component_element):
"""Create a component object from a ``<component>`` element.
:arg xml.etree.ElementTree.Element component_element:
a ``<component>`` element
:return:
an Aglyph component object
:rtype:
:class:`aglyph.component.Component`
"""
return Component(
component_element.get("id"),
dotted_name=component_element.get("dotted-name"),
factory_name=component_element.get("factory-name"),
member_name=component_element.get("member-name"),
strategy=component_element.get("strategy"),
parent_id=component_element.get("parent-id"),
after_inject=component_element.get("after-inject"),
before_clear=component_element.get("before-clear")
)
def _process_dependencies(self, depsupport, depsupport_element):
"""Parse the child elements of *depsupport_element* to populate
the *depsupport* initialization arguments and attributess.
:arg depsupport:
a :class:`Template` or :class:`Component`
:arg xml.etree.ElementTree.Element depsupport_element:
the ``<template>`` or ``<component>`` that was parsed to
create *depsupport*
"""
children = list(depsupport_element)
child_tags = [elem.tag for elem in children]
if child_tags == ["init"]:
init_element = children[0]
attributes_element = None
elif child_tags == ["init", "attributes"]:
init_element, attributes_element = children
elif child_tags == ["attributes"]:
init_element = None
attributes_element = children[0]
elif not child_tags:
init_element = None
attributes_element = None
else:
dtag = depsupport_element.tag
raise AglyphError(
"unexpected element: %s/%s" %
(depsupport_element.tag, child_tags[0]))
if init_element is not None:
for (keyword, value) in self._process_init(init_element):
if keyword is None:
depsupport.args.append(value)
else:
depsupport.keywords[keyword] = value
if attributes_element is not None:
for (name, value) in self._process_attributes(attributes_element):
depsupport.attributes[name] = value
self.__log.debug(
"%r has args=%r, keywords=%r, attributess=%r",
depsupport, depsupport.args, depsupport.keywords,
depsupport.attributes)
def _process_init(self, init_element):
"""Yield initialization arguments (positional and keyword)
parsed from *init_element*.
:arg xml.etree.ElementTree.Element init_element:
an ``<init>`` element
:return:
an iterator that yields the 2-tuple ``(keyword, value)``
.. note::
Both positional and keyword arguments are yielded by this
method as a 2-tuple ``(keyword, value)``. For positional
arguments, ``keyword`` will be ``None``.
"""
for element in list(init_element):
if element.tag != "arg":
raise AglyphError("unexpected element: init/%s" % element.tag)
keyword = element.get("keyword")
if keyword == "":
raise AglyphError("arg/@keyword cannot be empty")
value = self._unserialize_element_value(element)
yield (keyword, value)
def _process_attributes(self, attributes_element):
"""Yield attributes (fields, setter methods, or properties)
parsed from *attributes_element*.
:arg xml.etree.ElementTree.Element attributes_element:
an ``<attributes>`` element
:return:
an iterator that yields the 2-tuple ``(name, value)``
"""
for element in list(attributes_element):
if element.tag != "attribute":
raise AglyphError(
"unexpected element: attributes/%s" % element.tag)
name = element.get("name")
if not name:
raise AglyphError(
"attribute/@name is required and cannot be empty")
value = self._unserialize_element_value(element)
yield (name, value)
def _unserialize_element_value(self, valuecontainer_element):
"""Return the appropriate object, value, Aglyph reference, or
Aglyph evaluator for *element*.
:arg xml.etree.ElementTree.Element valuecontainer_element:
an element with a single child element that describes a value
:return:
the runtime object that is the result of processing
*valuecontainer_element*
:rtype:
an object of a Python built-in type, a Python built-in
constant, a :class:`Reference`, or an :class:`Evaluator`
*valuecontainer_element* must be an ``<arg>``, ``<attribute>``,
``<key>``, or ``<value>`` element.
"""
component_id = valuecontainer_element.get("reference")
if component_id is not None:
return ref(component_id)
children = list(valuecontainer_element)
if len(children) != 1:
vtag = valuecontainer_element.tag
raise AglyphError(
"<%s> must contain exactly one child element; found %s" % (
vtag,
", ".join("%s/%s" % (vtag, c.tag) for c in children)
if children else "no children"))
return self._process_value_element(
children[0], valuecontainer_element.tag)
def _process_value_element(self, value_element, parent_tag):
"""Create a usable Python object from *value_element*.
:arg xml.etree.ElementTree.Element value_element:
an element that describes a value
:arg str parent_tag:
the name of the *value_element* parent element
:return:
a Python object that is the value of *value_element*
*value_element* must be a ``<False />``, ``<True />``,
``<None />``, ``<bytes>``, ``<str>``, ``<unicode>``, ``<int>``,
``<float>``, ``<tuple>``, ``<list>``, ``<dict>``, or ``<set>``
element.
This method will return one of the following types, dependent
upon the element:
* an object of a Python built-in type
* a Python built-in constant
* an Aglyph :class:`Reference`
* an Aglyph :class:`Evaluator`
"""
parse_value = getattr(self, "_parse_%s" % value_element.tag, None)
if parse_value is None:
raise AglyphError(
"unexpected element: %s/%s" % (parent_tag, value_element.tag))
return parse_value(value_element)
def _parse_False(self, false_element):
"""Return the builtin constant ``False``.
:arg xml.etree.ElementTree.Element false_element:
a ``<False />`` element
"""
return False
def _parse_True(self, true_element):
"""Return the builtin constant ``True``.
:arg xml.etree.ElementTree.Element true_element:
a ``<True />`` element
"""
return True
def _parse_None(self, none_element):
"""Return the builtin constant ``None``.
:arg xml.etree.ElementTree.Element none_element:
a ``<None />`` element
"""
return None
def _parse_bytes(self, bytes_element):
"""Return an encoded bytes object parsed from *bytes_element*.
:arg xml.etree.ElementTree.Element bytes_element:
a ``<bytes>`` element
:rtype:
:obj:`bytes` (Python 3) or :obj:`str` (Python 2)
If the **bytes/@encoding** attribute is set, the text of the
``<bytes>`` element is encoded using the specified character
set; otherwise, the text of the ``<bytes>`` element is encoded
using :attr:`default_encoding`.
Whitespace in the ``<bytes>`` element content is preserved.
If *bytes_element* represents the empty element ``<bytes />``,
``bytes()`` (Python 3) or ``str()`` (Python 2) is returned.
"""
if bytes_element.text is not None:
encoding = bytes_element.get("encoding", self._default_encoding)
# .encode() will return the appropriate type
return bytes_element.text.encode(encoding)
else:
return DataType()
def __parse_str_as_data(self, str_element):
"""Return an encoded bytes object parsed from *str_element*.
:arg xml.etree.ElementTree.Element str_element:
a ``<str>`` element
:rtype:
:obj:`str` (Python 2)
.. note::
This method is aliased as ``_parse_str`` when Aglyph is
running under Python 2.
If the **str/@encoding** attribute has been set, the text of the
``<str>`` element is encoded using the specified character set;
otherwise, the text of the ``<str>`` element is encoded using
:attr:`default_encoding`.
Whitespace in the ``<str>`` element content is preserved.
If *str_element* represents the empty element ``<str />``,
``str()`` is returned.
"""
if str_element.text is not None:
encoding = str_element.get("encoding", self._default_encoding)
return str_element.text.encode(encoding)
else:
return str()
def __parse_str_as_text(self, str_element):
"""Return a Unicode text object parsed from *str_element*.
:arg xml.etree.ElementTree.Element str_element:
a ``<str>`` element
:rtype:
:obj:`str` (Python 3)
.. note::
This method is aliased as ``_parse_str`` when Aglyph is
running under Python 3.
The text of the ``<str>`` element (which is already a Unicode
string) is returned unchanged.
Whitespace in the ``<str>`` element content is preserved.
If *str_element* represents the empty element ``<str />``,
``str()`` is returned.
"""
if str_element.text is not None:
encoding = str_element.get("encoding")
if encoding is not None:
self.__log.warning(
"ignoring str/@encoding attribute %r (Python 3)", encoding)
return str_element.text
else:
return str()
def _parse_unicode(self, unicode_element):
"""Return a Unicode text object parsed from *unicode_element*.
:arg xml.etree.ElementTree.Element unicode_element:
a ``<unicode>`` element
:rtype:
:obj:`str` (Python 3) or :obj:`unicode` (Python 2)
The text of the ``<unicode>`` element (which is already a
Unicode string) is returned unchanged.
Whitespace in the ``<unicode>`` element content is preserved.
If *unicode_element* represents the empty element
``<unicode />``, ``str()`` (Python 3) or ``unicode()``
(Python 2) is returned.
"""
if unicode_element.text is not None:
return unicode_element.text
else:
return TextType()
def _parse_int(self, int_element):
"""Return a builtin integer object parsed from *int_element*.
:arg xml.etree.ElementTree.Element int_element:
an ``<int>`` element
:rtype:
:obj:`int`
The **int/@base** attribute, if specified, is used as the number
base to interpret the content of *int_element*.
If *int_element* represents the empty element ``<int />``,
``int()`` is returned.
.. warning::
This method **may** return :obj:`long` in Python 2!
"""
if int_element.text is not None:
base = int(int_element.get("base", "10"))
#PYVER: IronPython 2.7 does not accept a 'base=' keyword argument
return int(int_element.text, base)
else:
return int()
def _parse_float(self, float_element):
"""Return a builtin floating-point object parsed from
*float_element*.
:arg xml.etree.ElementTree.Element float_element:
a ``<float>`` element
:rtype:
:obj:`float`
If *float_element* represents the empty element ``<float />``,
``float()`` is returned.
"""
if float_element.text is not None:
return float(float_element.text)
else:
return float()
def _parse_list(self, list_element):
"""Return a :obj:`list` evaluator object parsed from
*list_element*.
:arg xml.etree.ElementTree.Element list_element:
a ``<list>`` element
:rtype:
:class:`aglyph.component.Evaluator`
.. note::
The evaluator returned by this method produces a new
:obj:`list` object each time it is called.
"""
process_value_element = self._process_value_element
items = [
process_value_element(child_element, "list")
for child_element in list_element]
return evaluate(list, items)
def _parse_tuple(self, tuple_element):
"""Return a :obj:`tuple` evaluator object parsed from
*tuple_element*.
:arg xml.etree.ElementTree.Element tuple_element:
a ``<tuple>`` element
:rtype:
:class:`aglyph.component.Evaluator` (or :obj:`tuple` if
the ``<tuple>`` element is empty)
.. note::
The evaluator returned by this method produces a new
:obj:`tuple` object each time it is called.
"""
children = list(tuple_element)
if children:
process_value_element = self._process_value_element
items = [
process_value_element(child_element, "tuple")
for child_element in children]
return evaluate(tuple, items)
else:
# a tuple is immutable, so there's no sense in paying the overhead
# of evaluation for an empty tuple
return tuple()
def _parse_set(self, set_element):
"""Return a :obj:`set` evaluator object parsed from
*set_element*.
:arg xml.etree.ElementTree.Element set_element:
a ``<set>`` element
:rtype:
:class:`aglyph.component.Evaluator`
.. note::
The evaluator returned by this method produces a new
:obj:`set` object each time it is called.
"""
process_value_element = self._process_value_element
items = [
process_value_element(child_element, "set")
for child_element in set_element]
return evaluate(set, items)
def _parse_dict(self, dict_element):
"""Return a :obj:`dict` evaluator object parsed from
*dict_element*.
:arg xml.etree.ElementTree.Element dict_element:
a ``<dict>`` element
:rtype:
:class:`aglyph.component.Evaluator`
.. note::
The evaluator returned by this method produces a new
:obj:`dict` object each time it is called.
"""
# a list of 2-tuples, (key, value), used to initialize a dictionary
items = []
for element in list(dict_element):
if element.tag != "item":
raise AglyphError("unexpected element: dict/%s" % element.tag)
children = list(element)
child_tags = [child.tag for child in children]
if child_tags == ["key", "value"]:
key_element, value_element = children
else:
raise AglyphError(
"expected item/key, item/value; found %s" %
", ".join("item/%s" % ctag for ctag in child_tags))
items.append((
self._unserialize_element_value(key_element),
self._unserialize_element_value(value_element)
))
return evaluate(dict, items)
def _parse_reference(self, reference_element):
"""Return a reference to another component in this context.
:arg xml.etree.ElementTree.Element reference_element:
a ``<reference>`` element
:rtype:
an Aglyph :class:`Reference`
The **reference/@id** attribute is required, and will be used as
the value to create an :class:`aglyph.component.Reference`.
"""
component_id = reference_element.attrib["id"]
return ref(component_id)
def _parse_eval(self, eval_element):
"""Return a partial object that will evaluate an expression
parsed from *eval_element*.
:arg xml.etree.ElementTree.Element eval_element:\
an ``<eval>`` element
:rtype: :obj:`functools.partial`
..versionadded:: 3.0.0
The partial object will use Python's :func:`ast.literal_eval`
function to evaluate the expression when it is called. (Prior
versions of Aglyph used the builtin :obj:`eval` function.)
.. seealso::
`Eval really is dangerous
<http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html>`_
Ned Batchelder's insanely thorough discussion of :obj:`eval`
"""
if eval_element.text is None:
raise AglyphError("<eval> cannot be an empty element")
return partial(literal_eval, eval_element.text)
def __repr__(self):
return self.__repr | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/aglyph/context.py | context.py |
# Copyright (c) 2006, 2011, 2013-2018 Matthew Zipay.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""The classes in this module are used to define components and their
dependencies within an Aglyph context (:class:`aglyph.context.Context`).
.. rubric:: Components and Templates
:class:`aglyph.component.Component` tells an
:class:`aglyph.assembler.Assembler` how to create objects of a
particular type. The component defines the initialization and/or
attribute dependencies for objects of that type, as well as the assembly
strategy and any lifecycle methods that should be called.
:class:`aglyph.component.Template` is used to describe dependencies
(initialization and/or attribute) and lifecylce methods that are shared
by multiple components. Templates are similar to abstract classes; they
cannot be assembled, but are instead used as "parents" of other
components (or templates) to achieve a sort of "configuration
inheritance."
.. note::
Both ``Component`` and ``Template`` may serve as the parent of any
other component or template; but only components may be assembled.
.. rubric:: References and Evaluators
A :class:`aglyph.component.Reference` may be used as the value of any
initialization argument (positional or keyword) or attribute in a
component or template. Its value must be the unique ID of a
**component** in the same context. At assembly time, the assembler will
resolve the reference into an object of the component to which it
refers.
An :class:`aglyph.component.Evaluator` is similar to a
:func:`functools.partial` object. It stores a callable factory (function
or class) and related initialization arguments, and can be called
repeatedly to produce new objects. (Unlike a :func:`functools.partial`
object, though, an ``Evaluator`` will resolve any initialization
argument that is a :class:`aglyph.component.Reference`,
:func:`functools.partial`, or ``Evaluator`` **before** calling the
factory.)
.. rubric:: Strategies and Lifecycle methods
:data:`aglyph.component.Strategy` defines the assembly strategies
supported by Aglyph (*"prototype"*, *"singleton"*, *"borg"*,
*"weakref"* and *"_imported"*).
:data:`LifecycleState` defines assmebly states for components at
which Aglyph supports calling named methods on the objects of those
components. (Such methods may be used to perform specialized
initialization or disposal, for example.)
"""
__author__ = "Matthew Zipay <[email protected]>"
from collections import namedtuple, OrderedDict
from functools import partial
from inspect import isclass, ismodule, isroutine
import logging
import warnings
from autologging import logged, traced
from aglyph import AglyphError, _identify, __version__
from aglyph._compat import is_string, name_of, TextType
__all__ = [
"Strategy",
"LifecycleState",
"Reference",
"Evaluator",
"Template",
"Component",
]
_log = logging.getLogger(__name__)
Strategy = namedtuple(
"Strategy", ["PROTOTYPE", "SINGLETON", "BORG", "WEAKREF"])(
"prototype", "singleton", "borg", "weakref")
"""Define the component assembly strategies implemented by Aglyph.
.. rubric:: "prototype"
A new object is always created, initialized, wired, and returned.
.. note::
"prototype" is the default assembly strategy for Aglyph components
that do not specify a member name.
.. rubric:: "singleton"
The cached object is returned if it exists. Otherwise, the object is
created, initialized, wired, cached, and returned.
Singleton component objects are cached by :attr:`Component.unique_id`.
.. rubric:: "borg"
A new instance is always created. The shared-state is assigned to the
new instance's ``__dict__`` if it exists. Otherwise, the new instance is
initialized and wired, its instance ``__dict__`` is cached, and then the
instance is returned.
Borg component instance shared-states are cached by
:attr:`Component.unique_id`.
.. warning::
* The borg assembly strategy is **only** supported for
components that are non-builtin classes.
* The borg assembly strategy is **not** supported for
classes that define or inherit a ``__slots__`` member.
.. rubric:: "weakref"
In the simplest terms, this is a "prototype" that can exhibit
"singleton" behavior: as long as there is at least one "live" reference
to the assembled object in the application runtime, then requests to
assemble this component will return the same (cached) object.
When the only reference to the assembled object that remains is the
cached weak reference, the Python garbage collector is free to destroy
the object, at which point it is automatically removed from the Aglyph
cache.
Subsequent requests to assemble the same component will cause a new
object to be created, initialized, wired, cached (as a weak reference),
and returned.
.. note::
Please refer to the :mod:`weakref` module for a detailed explanation
of weak reference behavior.
.. rubric:: "_imported"
.. versionadded:: 3.0.0
.. note::
The "_imported" strategy is only valid (and is the only allowed
value) when *member_name* is specified for a component.
Since this strategy is implicitly assigned and is intended for
internal use by Aglyph itself, it is not exposed on the
``Strategy`` named tuple.
An already-created (loaded) object is obtained from an imported module
or class (as opposed to creating the object directly).
Such components will always resolve (i.e. be assembled) to the same
objects; but those objects are not cached by Aglyph as they will
exhibit "natural" singleton behavior so long as the containing module
is referenced in :attr:`sys.modules`.
It is not necessary to explicitly set the strategy to "_imported" when
using *member_name* - Aglyph will default to "_imported" when it sees
a non-empty *member_name* defined.
.. warning::
Explicitly setting strategy="_imported" **without** specifying
*member_name* will raise :exc:`AglyphError`.
Specifying *member_name* with any explicit strategy other than
"_imported" will ignore the explicit strategy, change it to
"_imported" internally, and issue a :class:`UserWarning` to that
effect.
"""
LifecycleState = namedtuple(
"LifecycleState", ["AFTER_INJECT", "BEFORE_CLEAR"])(
"after_inject", "before_clear")
"""Define the lifecycle states for which Aglyph will call object methods
on your behalf.
.. _lifecycle-methods:
.. rubric:: Lifecycle methods
Lifecycle methods are called with **no arguments** (positional or
keyword).
If a called lifecycle method raises an exception, the exception is
caught, logged at :attr:`logging.ERROR` level (including a traceback) to
the "aglyph.assembler.Assembler" channel, and a :class:`RuntimeWarning`
is issued.
A method may be registered for a lifecycle state by specifying the
method name at the context (least specific), template, and/or component
(most specific) level.
.. note::
Aglyph only calls **one** method on an object for any lifecycle
state. Refer to **The lifecycle method lookup process** (below) for
details.
Aglyph recognizes the following lifecycle states:
.. rubric:: "after_inject"
A component object is in this state after **all** dependencies (both
initialization arguments and attributes) have been injected into a
newly-created instance, but before the object is cached and/or returned
to the caller.
Aglyph will only call **one** "after_inject" method on any object, and
will determine which method to call by using the lookup process
described below.
.. rubric:: "before_clear"
A component object is in this state after is has been removed from an
internal cache (singleton, borg, or weakref), but before the object
itself is actually discarded.
Aglyph will only call **one** "before_clear" method on any object, and
will determine which method to call by using the lookup process
described below.
.. _lifecycle-method-lookup-process:
.. rubric:: The lifecycle method lookup process
Lifecyle methods may be specified at the context (least specific),
template, and component (most specific) levels.
In order to determine which named method is called for a particular
object, Aglyph looks up the appropriate lifecycle method name in the
following order, using the **first** one found that is not ``None``
*and* is actually defined on the object:
#. The method named by the object's ``Component.<lifecycle-state>``
property.
#. If the object's :attr:`Component.parent_id` is not ``None``, the
method named by the corresponding parent
``Template.<lifecycle-state>`` or ``Component.<lifecycle-state>``
property. (If necessary, lookup continues by examining the
parent-of-the-parent and so on.)
#. The method named by the ``Context.<lifecycle-state>`` property.
When Aglyph finds a named lifecycle method that applies to an object,
but the object itself does not define that method, a
:attr:`logging.WARNING` message is emitted.
.. note::
Either a :class:`Component` or :attr:`Template` may serve as the
parent identified by a ``parent_id``.
However, only a :class:`Component` may actually be assembled into
a usable object. (A :attr:`Template` is like an abstract class -
it defines common dependencies and/or lifecycle methods, but it
cannot be assembled.)
"""
class Reference(TextType):
"""A placeholder used to refer to another :class:`Component`.
A ``Reference`` is used as an alias to identify a component that is
a dependency of another component. The value of a ``Reference`` can
be either a dotted-name or a user-provided unique ID.
A ``Reference`` can be used as an argument for an
:class:`Evaluator`, and can be assembled directly by an
:class:`aglyph.assembler.Assembler`.
.. warning::
A ``Reference`` value MUST correspond to a component ID in the
same context.
.. note::
In Python versions < 3.0, a ``Reference`` representing a
dotted-name *must* consist only of characters in the ASCII
subset of the source encoding (see :pep:`0263`).
But in Python versions >= 3.0, a ``Reference`` representing a
dotted-name *may* contain non-ASCII characters
(see :pep:`3131`).
However, a ``Reference`` may also represent a user-defined
identifier. To accommodate all cases, the super class of
``Reference`` is "dynamic" with respect to the version of Python
under which Aglyph is running (:class:`unicode` under Python 2,
:class:`str` under Python 3). This documentation shows the base
class as ``str`` because the `Sphinx <http://sphinx-doc.org/>`_
documentation generator for Aglyph runs under CPython 3.
"""
def __new__(cls, referent):
"""Create a new reference to *referent*.
:arg referent:
the object that the reference will represent
:raise aglyph.AglyphError:
if *referent* is a class, function, or module but cannot be
imported
If *referent* is a string, it is assumed to be a valid
:attr:`Component.unique_id` and its value is returned as a
``Reference``.
If *referent* is a class, function, or module, its
**importable** dotted name is returned as a ``Reference``.
.. warning::
If *referent* is a class, function, or module, it **must**
be importable.
"""
return TextType.__new__(cls, _identify(referent))
_log.debug("Reference extends %r", TextType)
class _InitializationSupport(object):
"""The base for any class that configures type 2 (constructor)
injection.
"""
__slots__ = ["_args", "_keywords"]
def __init__(self):
"""The positional argument list and keyword argument mapping are
initialized to empty.
"""
#PYVER: arguments to super() are implicit under Python 3
super(_InitializationSupport, self).__init__()
self._args = []
self._keywords = {}
@property
def args(self):
"""The positional initialization arguments."""
return self._args
@property
def keywords(self):
"""The keyword initialization arguments."""
return self._keywords
@traced
@logged
class Evaluator(_InitializationSupport):
"""Perform lazy creation of objects."""
__slots__ = ["_factory"]
def __init__(self, factory, *args, **keywords):
"""
:param factory:
any callable that returns an object
:param tuple args:
the positional arguments to *func*
:param dict keywords:
the keyword arguments to *func*
An ``Evaluator`` is similar to a :func:`functools.partial` in
that they both collect a function and related arguments into a
:obj:`callable` object with a simplified signature that can be
called repeatedly to produce a new object.
*Unlike* a partial function, an ``Evaluator`` may have arguments
that are not truly "frozen," in the sense that any argument may
be defined as a :class:`Reference`, a :func:`functools.partial`,
or even another ``Evaluator``, which needs to be resolved (i.e.
assembled/called) before calling *factory*.
When an ``Evaluator`` is called, its arguments (positional and
keyword) are each resolved in one of the following ways:
* If the argument value is a :class:`Reference`, it is assembled
(by an :class:`aglyph.assembler.Assembler` reference passed to
:meth:`__call__`)
* If the argument value is an ``Evaluator`` or a
:func:`functools.partial`, it is called to produce its value.
* If the argument is a dictionary or a sequence other than a
string type, each item is resolved according to these rules.
* If none of the above cases apply, the argument value is used
as-is.
"""
#PYVER: arguments to super() are implicit under Python 3
super(Evaluator, self).__init__()
if not callable(factory):
raise TypeError("%r is not callable" % factory)
self._factory = factory
self._args = list(args) # mutable args for _InitializationSupport
self._keywords = keywords
@property
def factory(self):
"""The :obj:`callable` that creates new objects *(read-only)*."""
return self._factory
def __call__(self, assembler):
"""Call ``factory(*args, **keywords)`` and return the new object.
:param aglyph.assembly.Assembler assembler:
the assembler that will be used to assemble any
:class:`Reference` encountered in this evaluator's positional
and keyword arguments
"""
resolve = self._resolve
resolved_args = tuple(resolve(arg, assembler) for arg in self._args)
# keywords MUST be strings!
resolved_keywords = dict(
[(keyword, resolve(arg, assembler))
for (keyword, arg) in self._keywords.items()])
return self._factory(*resolved_args, **resolved_keywords)
def _resolve(self, arg, assembler):
"""Return the resolved *arg*.
:param arg:
represents an argument (positional or keyword) to
:attr:`factory`
:param aglyph.assembly.Assembler assembler:
the assembler that will be used to resolve *arg*
:return:
the resolved argument value that will actually be passed to
:attr:`factory`
"""
if isinstance(arg, Reference):
return assembler.assemble(arg)
elif isinstance(arg, Evaluator):
return arg(assembler)
elif isinstance(arg, partial):
return arg()
elif isinstance(arg, dict):
# either keys or values may themselves be References, partials, or
# Evaluators
resolve = self._resolve
return dict(
[(resolve(key, assembler), resolve(value, assembler))
for (key, value) in arg.items()])
elif hasattr(arg, "__iter__") and not is_string(arg):
resolve = self._resolve
# assumption: the iterable class supports initialization with
# __init__(iterable)
return arg.__class__([resolve(value, assembler) for value in arg])
else:
return arg
def __str__(self):
return "<%s %s @%08x>" % (
name_of(self.__class__), self._factory.__name__, id(self))
def __repr__(self):
return "%s.%s(%r, *%r **%r)" % (
self.__class__.__module__, name_of(self.__class__),
self._factory, self._args, self._keywords)
class _DependencySupport(_InitializationSupport):
"""The base for any class that configures both type 1 (setter) and
type 2 (constructor) injection.
"""
__slots__ = ["_attributes"]
def __init__(self):
"""The field/property/setter mapping is initialized to empty."""
#PYVER: arguments to super() are implicit under Python 3
super(_DependencySupport, self).__init__()
self._attributes = OrderedDict()
@property
def attributes(self):
"""The field/property/setter mapping."""
return self._attributes
@traced
@logged
class Template(_DependencySupport):
"""Support for configuring type 1 (setter) and type 2 (constructor)
injection, and lifecycle methods.
"""
__slots__ = [
"_after_inject",
"_before_clear",
"_parent_id",
"_unique_id",
]
def __init__(
self, unique_id, parent_id=None,
after_inject=None, before_clear=None):
"""
:arg str unique_id:
context-unique identifier for this template
:keyword str parent_id:
specifies the ID of a template or component that describes
the default dependencies and/or lifecyle methods for this
template
:keyword str after_inject:
specifies the name of the method that will be called on
objects of components that reference this template after all
component dependencies have been injected
:keyword str before_clear:
specifies the name of the method that will be called on
objects of components that reference this template
immediately before they are cleared from cache
:raise ValueError:
if *unique_id* is ``None`` or empty
.. note::
A ``Template`` cannot be assembled (it is equivalent to an
abstract class).
However, a :class:`Component` can also serve as a template,
so if you need the ability to assemble an object *and* use
its definition as the basis for other components, then define
the default dependencies and/or lifecycle methods in a
:class:`Component` and use that component's ID as the
:attr:`Component.parent_id` in other components.
*unique_id* must be a user-provided identifier that is unique
within the context to which this template is added. A component
may then be instructed to use a template by specifying the same
value for :attr:`Component.parent_id`.
*parent_id* is **another** :attr:`Component.unique_id` or
:attr:`Template.unique_id` in the same context that descibes
**this** template's default dependencies and/or lifecycle
methods.
*after_inject* is the name of a method *of objects of this
component* that will be called after **all** dependencies have
been injected, but before the object is returned to the caller.
This method will be called with **no** arguments (positional or
keyword). Exceptions raised by this method are not caught.
.. note::
``Template.after_inject`` takes precedence over any
*after_inject* method name specified for the template's
parent or context.
*before_clear* is the name of a method *of objects of this
component* that will be called immediately before the object is
cleared from cache via
:meth:`aglyph.assembler.Assembler.clear_singletons()`,
:meth:`aglyph.assembler.Assembler.clear_borgs()`, or
:meth:`aglyph.assembler.Assembler.clear_weakrefs()`.
.. note::
``Template.before_clear`` takes precedence over any
*before_clear* method name specified for the template's
parent or context.
.. warning::
The *before_clear* keyword argument has no meaning for and is
ignored by "prototype" components. If *before_clear* is
specified for a prototype, a :class:`RuntimeWarning` will be
issued.
For "weakref" components, there is a possibility that the
object no longer exists at the moment when the *before_clear*
method would be called. In such cases, the *before_clear*
method is **not** called. No warning is issued, but a
:attr:`logging.WARNING` message is emitted.
"""
#PYVER: arguments to super() are implicit under Python 3
super(Template, self).__init__()
if not unique_id:
raise ValueError(
"%s unique ID must not be None or empty" %
name_of(self.__class__))
self._unique_id = unique_id
self._parent_id = parent_id
self._after_inject = after_inject
self._before_clear = before_clear
@property
def unique_id(self):
"""Uniquely identifies this template in a context *(read-only)*."""
return self._unique_id
@property
def parent_id(self):
"""Identifies this template's parent template or component
*(read-only)*.
"""
return self._parent_id
@property
def after_inject(self):
"""The name of the component object method that will be called
after **all** dependencies have been injected *(read-only)*.
"""
return self._after_inject
@property
def before_clear(self):
"""The name of the component object method that will be called
immediately before the object is cleared from cache
*(read-only)*.
.. warning::
This property is not applicable to "prototype" component
objects, and is **not guaranteed** to be called for "weakref"
component objects.
"""
return self._before_clear
def __str__(self):
return "<%s %r @%08x>" % (
name_of(self.__class__), self._unique_id, id(self))
def __repr__(self):
return "%s.%s(%r, parent_id=%r, after_inject=%r, before_clear=%r)" % (
self.__class__.__module__, name_of(self.__class__),
self._unique_id, self._parent_id, self._after_inject,
self._before_clear)
@traced
@logged
class Component(Template):
"""Define a component and the dependencies needed to create a new
object of that component at runtime.
"""
__slots__ = [
"_dotted_name",
"_factory_name",
"_member_name",
"_strategy",
]
def __init__(
self, component_id, dotted_name=None,
factory_name=None, member_name=None, strategy=None,
parent_id=None,
after_inject=None, before_clear=None):
"""
:arg str component_id:
the context-unique identifier for this component
:keyword str dotted_name:
an **importable** dotted name
:keyword str factory_name:
names a :obj:`callable` member of objects of this component
:keyword str member_name:
names **any** member of objects of this component
:keyword str strategy:
specifies the component assembly strategy
:keyword str parent_id:
specifies the ID of a template or component that describes
the default dependencies and/or lifecyle methods for this
component
:keyword str after_inject:
specifies the name of the method that will be called on
objects of this component after all of its dependencies have
been injected
:keyword str before_clear:
specifies the name of the method that will be called on
objects of this component immediately before they are cleared
from cache
:raise aglyph.AglyphError:
if both *factory_name* and *member_name* are specified
:raise ValueError:
if *strategy* is not a recognized assembly strategy
*component_id* must be a user-provided identifier that is unique
within the context to which this component is added. An
**importable** dotted name may be used (see
:func:`aglyph.resolve_dotted_name`).
*dotted_name*, if provided, must be an **importable** dotted
name (see :func:`aglyph.resolve_dotted_name`).
.. note::
If *dotted_name* is not specified, then *component_id* is
used as the component's dotted name and **must** be an
importable dotted name.
*factory_name* is the name of a :obj:`callable` member of
*dotted-name* (i.e. a function, class, staticmethod, or
classmethod). When provided, the assembler will call this member
to create an object of this component.
*factory_name* enables Aglyph to inject dependencies into
objects that can only be initialized via nested classes,
:obj:`staticmethod`, or :obj:`classmethod`. See
:attr:`factory_name` for details.
*member_name* is the name of a member of *dotted-name*, which
**may or may not** be callable.
*member_name* differs from *factory_name* in two ways:
1. *member_name* is not restricted to callable members; it may
identify **any** member (attribute, property, nested class).
2. When an assembler assembles a component with a
*member_name*, initialization of the object is *bypassed*
(i.e. the assembler will not call the member, and any
initialization arguments defined for the component will be
**ignored**).
*member_name* enables Aglyph to reference class, function,
:obj:`staticmethod`, and :obj:`classmethod` obejcts, as well as
simple attributes or properties, as components and dependencies.
See :attr:`member_name` for details.
.. note::
Both *factory_name* and *member_name* can be dot-separated
names to reference nested members.
.. warning::
The *factory_name* and *member_name* arguments are mutually
exclusive. An exception is raised if both are provided.
*strategy* must be a recognized component assembly strategy, and
defaults to ``Strategy.PROTOTYPE`` (*"prototype"*) if not
specified.
.. versionadded:: 3.0.0
When :attr:`member_name` is specified, the strategy **must**
be *"_imported"*. Aglyph will use the "_imported" strategy
automatically for components that specify *member_name*;
setting strategy to anything other than "_imported" when
specifying *member_name* will issue :class:`UserWarning`.
Please see :data:`Strategy` for a description of the component
assembly strategies supported by Aglyph.
.. warning::
The ``Strategy.BORG`` (*"borg"*) component assembly strategy
is only supported for classes that **do not** define or
inherit ``__slots__``!
*parent_id* is the context-unique ID of a :class:`Template` (or
another ``Component``) that defines default dependencies and/or
lifecycle methods for this component.
*after_inject* is the name of a method *of objects of this
component* that will be called after **all** dependencies have
been injected, but before the object is returned to the caller.
This method will be called with **no** arguments (positional or
keyword). Exceptions raised by this method are not caught.
.. note::
``Component.after_inject`` takes precedence over any
*after_inject* method names specified for the component's
parent or context.
*before_clear* is the name of a method *of objects of this
component* that will be called immediately before the object is
cleared from cache via
:meth:`aglyph.assembler.Assembler.clear_singletons()`,
:meth:`aglyph.assembler.Assembler.clear_borgs()`, or
:meth:`aglyph.assembler.Assembler.clear_weakrefs()`.
.. note::
``Component.before_clear`` takes precedence over any
*before_clear* method names specified for the component's
parent or context.
.. warning::
The *before_clear* keyword argument has no meaning for, and
is ignored by, "prototype" components. If *before_clear* is
specified for a prototype component, a :class:`UserWarning`
is issued **when the component is defined**, and the
component's :attr:`before_clear` attribute is set to
``None``.
.. warning::
For "weakref" components, there is a possibility that the
object no longer exists at the moment when the *before_clear*
method would be called. In such cases, the
:meth:`aglyph.assembler.clear_weakrefs` method will issue a
:class:`RuntimeWarning` (see that method's documentation for
more details).
Once a ``Component`` instance is initialized, the ``args``
(:obj:`list`), ``keywords`` (:obj:`dict`), and ``attributes``
(:class:`collections.OrderedDict`) members can be modified
in-place to define the dependencies that must be injected into
objects of this component at assembly time. For example::
component = Component("http.client.HTTPConnection")
component.args.append("ninthtest.info")
component.args.append(80)
component.keywords["strict"] = True
component.attributes["set_debuglevel"] = 1
In Aglyph, a component may:
* be assembled directly by an
:class:`aglyph.assembler.Assembler`
* identify other components as dependencies (using a
:class:`Reference`)
* be used by other components as a dependency
* use common dependencies and behaviors (*after_inject*,
*before_clear*) defined in a
:class:`aglyph.component.Template`
* use any combination of the above behaviors
"""
#PYVER: arguments to super() are implicit under Python 3
super(Component, self).__init__(
component_id, parent_id=parent_id,
after_inject=after_inject, before_clear=before_clear)
# if a dotted name is not provided, the unique ID is assumed to be a
# dotted name
self._dotted_name = dotted_name if dotted_name else component_id
if factory_name and member_name:
raise AglyphError(
"only one of factory_name or member_name may be specified")
self._factory_name = factory_name
self._member_name = member_name
# issues/5: default strategy is "_imported" when member_name is
# specified, otherwise "prototype"
if strategy is None:
strategy = \
"_imported" if member_name else Strategy.PROTOTYPE
# issues/5: member_name requires "_imported" strategy and vice-versa
if member_name and strategy != "_imported":
warnings.warn(
("ignoring strategy %r for component %r -- strategy MUST be "
"'_imported' (implicit) if member_name is specified") %
(strategy, component_id),
UserWarning)
strategy = "_imported"
elif strategy == "_imported" and not member_name:
raise AglyphError(
"strategy '_imported' is only valid if member_name is specified")
if strategy not in Strategy and strategy != "_imported":
raise ValueError("unrecognized assembly strategy %r" % strategy)
self._strategy = strategy
# issues/5: also see Assembler._call_lifecycle_method, which issues a
# RuntimeWarning for _imported components that describe an after_inject
# method
if (strategy in [Strategy.PROTOTYPE, "_imported"]
and before_clear):
warnings.warn(
"ignoring before_clear=%r for %s component with ID %r" %
(before_clear, strategy, self._unique_id),
UserWarning)
self._before_clear = None
@property
def dotted_name(self):
"""The importable dotted name for objects of this component
*(read-only)*.
"""
return self._dotted_name
@property
def factory_name(self):
"""The name of a :obj:`callable` member of :attr:`dotted_name`
*(read-only)*.
``factory_name`` can be used to initialize objects of the
component when a class is not directly importable (e.g. the
component class is a nested class), or when component objects
need to be initialized via :obj:`staticmethod` or
:obj:`classmethod`.
Consider the following::
# module.py
class Example:
class Nested:
pass
The dotted name "module.Example.Nested" is not importable, and
so cannot be used as a component's ``unique_id`` or
``dotted_name``. To assemble objects of this type, use
``factory_name`` to identify the callable factory (the Nested
class, in this example) that is accessible through the
importable "module.Example"::
component = Component(
"nested-object", dotted_name="module.Example",
factory_name="Nested")
Or using XML configuration::
<component id="nested-object" dotted-name="module.Example"
factory-name="Nested" />
``factory_name`` may also be a dot-separated name to specify an
arbitrarily-nested callable. The following example is equivalent
to the above::
component = Component(
"nested-object", dotted_name="module",
factory_name="Example.Nested")
Or again using XML configuration::
<component id="nested-object" dotted-name="module"
factory-name="Example.Nested" />
.. note::
The important thing to remember is that :attr:`dotted_name`
must be **importable**, and ``factory_name`` must be
accessible from the imported class or module via attribute
access.
"""
return self._factory_name
@property
def member_name(self):
"""The name of any member of :attr:`dotted_name` *(read-only)*.
``member_name`` can be used to obtain an object *directly* from
an importable module or class. The named member is simply
accessed and returned (it is **not** called, even if it is
callable).
Consider the following::
# module.py
class Example:
class Nested:
pass
The following example shows how to define a component that will
produce the ``module.Example.Nested`` class *itself* when
assembled::
component = Component(
"nested-class", dotted_name="module.Example",
member_name="Nested")
Or using XML configuration::
<component id="nested-class" dotted-name="module.Example"
member-name="Nested" />
``member_name`` may also be a dot-separated name to specify an
arbitrarily-nested member. The following example is equivalent
to the above::
component = Component(
"nested-class", dotted_name="module",
member_name="Example.Nested")
Or again using XML configuration::
<component id="nested-class" dotted-name="module"
member-name="Example.Nested" />
.. note::
The important thing to remember is that :attr:`dotted_name`
must be **importable**, and ``member_name`` must be
accessible from the imported class or module via attribute
access.
.. warning::
When a component specifies ``member_name``, initialization is
assumed. In other words, Aglyph **will not** attempt to
initialize the member, and will **ignore** any :attr:`args`
and :attr:`keywords`.
On assembly, if any initialization arguments and/or keyword
arguments have been defined for such a component, they are
discarded and a WARNING-level log record is emitted to the
"aglyph.assembler.Assembler" channel.
(Any :attr:`attributes` that have been specified for the
component will still be processed as setter injection
dependencies, however.)
"""
return self._member_name
@property
def strategy(self):
"""The component assembly strategy *(read-only)*."""
return self._strategy
def __repr__(self):
return (
"%s.%s(%r, dotted_name=%r, factory_name=%r, member_name=%r, "
"strategy=%r, parent_id=%r, after_inject=%r, before_clear=%r)") % (
self.__class__.__module__, name_of(self.__class__),
self._unique_id, self._dotted_name, self._factory_name,
self._member_name, self._strategy, self._parent_id,
self._after_inject, self._before_clear) | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/aglyph/component.py | component.py |
# Copyright (c) 2006, 2011, 2013-2018 Matthew Zipay.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""The Aglyph assembler creates application objects from component
definitions, injecting dependencies into those objects through
initialization arguments and keywords, attributes, setter methods,
and/or properties.
Application components and their dependencies are defined in an
:class:`aglyph.context.Context`, which is used to initialize an
assembler.
An assembler provides thread-safe caching of **singleton** component
instances, **borg** component shared-states (i.e. instance ``__dict__``
references), and **weakref** component instance weak references.
"""
__author__ = "Matthew Zipay <[email protected]>"
from collections import OrderedDict
from functools import partial
from inspect import isclass
import logging
import warnings
import weakref
try:
import threading
threading_ = threading
except ImportError:
import dummy_threading
threading_ = dummy_threading
warnings.warn(
"threading module is not available; aglyph.assembler.Assembler "
"operations will NOT be thread-safe!",
RuntimeWarning)
from autologging import logged, traced
from aglyph import (
AglyphError,
format_dotted_name,
_identify,
resolve_dotted_name,
__version__,
)
from aglyph._compat import is_string, name_of, new_instance
from aglyph.component import Evaluator, Reference
__all__ = ["Assembler"]
_log = logging.getLogger(__name__)
_log.debug("using %r", threading_)
# thread-local storage for assembly
_assembly = threading_.local()
@traced
@logged
class Assembler(object):
"""Create application objects using type 2 (setter) and type 3
(constructor) dependency injection.
"""
def __init__(self, context):
"""
:arg aglyph.context.Context context:
a context object mapping unique IDs to component and template
definitions
"""
#PYVER: arguments to super() are implicit in Python 3
super(Assembler, self).__init__()
self._context = context
self._caches = {
"singleton": _ReentrantMutexCache(),
"borg": _ReentrantMutexCache(),
"weakref": _ReentrantMutexCache(),
}
self.__log.info("initialized %s", self)
def assemble(self, component_spec):
"""Create an object identified by *component_spec* and inject
its dependencies.
:arg component_spec:
a unique component ID, or an object whose dotted name is a
unique component ID
:return:
a complete object with all of its resolved dependencies
:raise KeyError:
if *component_spec* does not identify a component in this
assembler's context
:raise aglyph.AglyphError:
if *component_spec* causes a circular dependency
If *component_spec* is a string, it is assumed to be a unique
component ID and is used as-is. Otherwise,
:func:`aglyph.format_dotted_name` is called to convert
*component_spec* into a dotted name string, which is assumed to
be the component's unique ID.
How a component object is assembled (created, initialized,
wired, and returned) is determined by the component's
:attr:`aglyph.component.Component.strategy`:
**"prototype"**
A new object is always created, initialized, wired, and
returned.
This is the default assembly strategy for Aglyph components.
**"singleton"**
If the component has been assembled already during the
current application lifetime **and** there has been no
intervening call to :meth:`clear_singletons`, then a cached
reference to the object is returned.
Otherwise, a new object is created, initialized, wired,
cached, and returned.
Singleton component objects are cached by their
:attr:`aglyph.component.Component.unique_id`.
.. note::
Assembly of singleton components is a thread-safe
operation.
**"borg"**
If the component has been assembled already during the
current application lifetime **and** there has been no
intervening call to :meth:`clear_borgs`, then a new instance
is created and a cached reference to the shared-state is
directly assigned to the instance ``__dict__``.
Otherwise, a new instance is created, initialized, and wired;
its instance ``__dict__`` is cached; and the instance is
returned.
Borg component instance shared-states are cached by their
:attr:`aglyph.component.Component.unique_id`.
.. note::
Assembly of borg components is a thread-safe operation.
.. warning::
The borg assembly strategy is **only** supported for
components whose objects have an instance ``__dict__``.
This means that components using builtin classes, or
components using classes that define or inherit a
``__slots__`` member, **cannot** be declated as borg
components.
.. versionadded:: 2.1.0
support for the "weakref" assembly strategy
**"weakref"**
In the simplest terms, this is a "prototype" that can exhibit
"singleton" behavior: as long as there is at least one "live"
reference to the assembled object in the application runtime,
then requests to assemble this component will return the same
(cached) object.
When the only reference to the assembled object that remains
is the cached (weak) reference, the Python garbage collector
is free to destroy the object, at which point it is
automatically removed from the Aglyph cache.
Subsequent requests to assemble the same component will cause
a new object to be created, initialized, wired, cached (as a
weak reference), and returned.
.. note::
Please refer to the :mod:`weakref` module for a detailed
explanation of weak reference behavior.
.. versionadded:: 2.0.0
**Either** :attr:`aglyph.component.Component.factory_name`
**or** :attr:`aglyph.component.Component.member_name` may be
defined to exercise more control over how a component object
is created and initialized. Refer to the linked documentation
for details.
.. note::
This method is called recursively to assemble any dependency
of *component_spec* that is defined as a
:class:`aglyph.component.Reference`.
"""
component_id = _identify(component_spec)
component = self._context.get_component(component_id)
if component is None:
raise KeyError(
"component %r is not defined in %s" %
(component_id, self._context))
# issues/3: check for circular dependency
if not hasattr(_assembly, "component_stack"):
_assembly.component_stack = []
if (component_id in _assembly.component_stack):
raise AglyphError(
"circular dependency detected: %s" %
" > ".join(_assembly.component_stack + [component_id]))
_assembly.component_stack.append(component_id)
self.__log.debug(
"current assembly stack: %r", _assembly.component_stack)
try:
obj = self._create(component)
self.__log.info("assembled %r", component_id)
return obj
finally:
_assembly.component_stack.pop()
def _create(self, component):
"""Create an object of *component*.
:arg aglyph.component.Component component:
a component definition
:return:
an initialized object
:raise AglyphError:
if *component* uses an unrecognized assembly strategy
This method delegates to the appropriate
``_create_\<strategy\>`` method for *component*.
"""
# allow AttributeError; there is sufficient checking in Component for
# unrecognized strategy, and getting here with one takes quite a bit of
# effort (see test_Assembler.test_cant_create_unrecognized_strategy)
create = getattr(self, "_create_%s" % component.strategy)
return create(component)
def _create_prototype(self, component):
"""Create and initialize a prototype object for *component*.
:arg aglyph.component.Component component:
a component definition having strategy="prototype"
:return:
an initialized prototype object
A new object is always created and initialized when a
"prototype" component is assembled.
This is the default assembly strategy for Aglyph components.
"""
obj = self._initialize(component)
self._wire(obj, component)
self._call_lifecycle_method("after_inject", obj, component.unique_id)
self.__log.info("created %r", component)
return obj
# issues/5: support "_imported" strategy when using member_name
# (objects of these components are created like prototypes though they
# exhibit singleton behavior as long as the containing module is
# referenced in sys.modules)
_create__imported = _create_prototype
def _create_singleton(self, component):
"""Return the singleton object for *component*.
:arg aglyph.component.Component component:
a component definition having strategy="singleton"
:return:
the singleton object with all its dependencies resolved
If *component* has previously been assembled, the cached object
is returned. Otherwise, a new object is created, initialized,
wired, cached, and then returned.
.. note::
Assembly of singleton components is a thread-safe operation.
"""
with self._caches["singleton"] as cache:
obj = cache.get(component.unique_id)
if obj is None:
# singletons are initialized and wired once, then cached
obj = self._initialize(component)
self._wire(obj, component)
self._call_lifecycle_method(
"after_inject", obj, component.unique_id)
cache[component.unique_id] = obj
self.__log.info(
"created and cached %r @ %x", component, id(obj))
else:
self.__log.info(
"retrieved %r @ %x from cache", component, id(obj))
return obj
def _create_borg(self, component):
"""Create and initialize a borg object for *component*.
:arg aglyph.component.Component component:
a component definition having strategy="borg"
:return:
the borg instance with all its dependencies resolved
A new instance is always created. If *component* has been
previously assembled, the cached shared-state is assigned to the
new instance's ``__dict__`` and the instance is returned.
Otherwise, the new instance is initialized and wired, its
``__dict__`` is cached, and then the instance is returned.
.. note::
Assembly of borg components is a thread-safe operation.
.. warning::
The borg assembly strategy is **only** supported for
components whose objects have an instance ``__dict__``.
This means that components using builtin classes, or
components using classes that define or inherit a
``__slots__`` member, **cannot** be declated as borg
components.
"""
with self._caches["borg"] as cache:
cached_obj = cache.get(component.unique_id)
if cached_obj is None:
# borgs are initialized and wired, then the state is cached
# (an object of the borg is actually cached, but this is just
# an implementation detail... it's just as effective a
# container as anything else, and it makes the implementation
# of clear_borgs() far less expensive - if we only cached the
# new_obj.__dict__, we'd need to actually assemble each borg in
# clear_borgs() in order to call any before_clear lifecycle
# methods)
new_obj = self._initialize(component)
self._wire(new_obj, component)
self._call_lifecycle_method(
"after_inject", new_obj, component.unique_id)
cache[component.unique_id] = new_obj
self.__log.info(
"created and cached shared-state for %r", component)
else:
self.__log.info(
"retrieved shared-state for %r from cache", component)
cls = self._resolve_initializer(component)
new_obj = (
new_instance(cls) if (component.member_name is None)
else cls)
new_obj.__dict__ = cached_obj.__dict__
return new_obj
def _create_weakref(self, component):
"""Return a weakref object for *component*.
:arg aglyph.component.Component component:
a component definition having strategy="weakref"
:return:
the weakref object with all its dependencies resolved
.. note::
The object returned by this method and, therefore, by
:meth:`assemble` is the **referent** (i.e. the object which
is referred to *by* the weak reference).
If *component* has previously been assembled **and** the
internally-cached weak reference is still live, then the cached
referent object is returned. Otherwise, a new object is created,
initialized, wired, cached as a weak reference, and then
returned.
.. warning::
While assembly of weakref components is a thread-safe
operation with respect to *explicit* modification of the
weakref cache (i.e. any other thread attempting to assemble
a weakref component or to :meth:`clear_weakrefs` will be
blocked until this method returns), the nature of weak
references means that entries may still "disappear" from
the cache *even while the cache lock is held.*
With respect to assembly, this means that a referent
component object may "disappear" (i.e. the weak reference
goes dead) even *after* the cache lock has been acquired
and the weak reference retrieved from the cache. Practically
speaking, this should be of no concern to callers, since
a valid object of the component will be returned either way.
Please refer to the :mod:`weakref` module for a detailed
explanation of weak reference behavior.
"""
with self._caches["weakref"] as cache:
ref = cache.get(component.unique_id)
if ref is not None:
obj = ref()
if obj is None:
# referent is dead; discard the cache entry
self.__log.debug(
"cached weak reference to object of %r is dead; "
"new object will be created",
component)
cache.pop(component.unique_id)
else:
obj = None
if obj is None:
# an object is initialized and wired whenever a weak reference
# to the abject does not exist or is dead; then a weak
# reference to the object is cached and the object (i.e. the
# referent) is returned
obj = self._initialize(component)
self._wire(obj, component)
self._call_lifecycle_method(
"after_inject", obj, component.unique_id)
cache[component.unique_id] = weakref.ref(obj)
self.__log.info(
"created and cached weak reference to %r @ %x",
component, id(obj))
else:
self.__log.info(
"retrieved %r @ %x from cached weak reference",
component, id(obj))
return obj
def _initialize(self, component):
"""Create a new *component* object initialized with its
dependencies.
:arg aglyph.component.Component component:
a component definition
:return:
an initialized object of *component*
This method performs **type 3 (constructor)** dependency
injection.
.. versionchanged:: 2.1.0
If *component* specifies a :attr:`Component.member_name`
**and** either :attr:`Component.args`
or :attr:`Component.keywords`, then a :class:`RuntimeWarning`
is issued.
"""
initializer = self._resolve_initializer(component)
if component.member_name is None:
(args, keywords) = self._resolve_args_and_keywords(component)
try:
# issues/2: always use the __call__ protocol to initialize
obj = initializer(*args, **keywords)
except Exception as e:
raise AglyphError(
"failed to initialize object of component %r" %
component.unique_id,
e)
else:
obj = initializer
if component.args or component.keywords:
msg = (
"ignoring args and keywords for component %r "
"(uses member_name assembly)")
self.__log.warning(msg, component.unique_id)
warnings.warn(msg % component.unique_id, RuntimeWarning)
return obj
def _resolve_initializer(self, component):
"""Return the object that is responsible for creating new
*component* objects.
:arg aglyph.component.Component component:
a component definition
:return:
a callable if *component.member_name* is undefined, else the
member itself (which may or may not be a callable)
.. note::
If *component.member_name* is defined, the returned object
may still be callable (for example, *component.member_name*
may name a class). However, Aglyph will not **call** the
member.
This allows injection of dependencies that are references to
callable objects like classes and functions.
"""
initializer = resolve_dotted_name(component.dotted_name)
access_name = component.factory_name or component.member_name
if access_name:
for name in access_name.split('.'):
initializer = getattr(initializer, name) # allow AttributeError
return initializer
def _resolve_args_and_keywords(self, component):
"""Assemble or evaluate all positional and keyword arguments
for *component*.
:arg aglyph.component.Component component:
a component definition
:return:
the fully-resolved (i.e. recursively assembled or evaluated)
positional and keyword arguments for the *component*
initializer
:rtype:
a 2-tuple ``(args, keywords)`` where ``args`` is an N-tuple
and ``keywords`` is a :obj:`dict`
The values returned from this method are ready to be passed
directly to the *component* initializer (see :meth:`_initialize`
and :meth:`_resolve_initializer`).
.. versionchanged:: 2.1.0
The returned 2-tuple ``(args, keywords)`` accounts for the
*component* parent (and parent-of-parent, etc.) arguments and
keywords.
For any given component, this method will always return the
"official" arguments and keywords that should be passed to
the initializer.
"""
resolve = self._resolve_value
args = tuple([resolve(arg) for arg in self._collect_args(component)])
collected_keywords = self._collect_keywords(component)
keywords = dict(
[(name, resolve(value))
for (name, value) in collected_keywords.items()])
return (args, keywords)
def _collect_args(self, component):
"""Return the positional arguments used to initialize objects of
*component*.
:arg :class:`aglyph.component.Component` component:
the component being initialized
:return:
the positional arguments for the *component* initializer,
taking into account any positional arguments described by
parent components/templates
:rtype:
:obj:`list`
"""
collected_args = component.args
parent = self._context.get(component.parent_id)
while parent is not None:
if parent.args:
# children extend parents (like partial functions)
collected_args = parent.args + collected_args
parent = self._context.get(parent.parent_id)
return collected_args
def _collect_keywords(self, component):
"""Return the keyword arguments used to initialize objects of
*component*.
:arg aglyph.component.Component component:
the component being initialized
:return:
the keyword arguments for the *component* initializer, taking
into account any keyword arguments described by parent
components/templates
:rtype:
:obj:`dict`
"""
collected_keywords = component.keywords
parent = self._context.get(component.parent_id)
while parent is not None:
if parent.keywords:
parent_keywords = dict(parent.keywords)
# children extend/override parents (like partial functions)
parent_keywords.update(collected_keywords)
collected_keywords = parent_keywords
parent = self._context.get(parent.parent_id)
return collected_keywords
def _wire(self, obj, component):
"""Inject dependencies into *obj* using direct attribute
assignment, setter methods, and/or properties.
:param obj:
an initialized object for *component*
:param aglyph.component.Component component:
a component definition
This method performs **type 2 (setter)** dependency injection.
.. versionchanged:: 2.1.0
This method accounts for any attributes defined in the
*component* parent (and parent-of-parent, etc.).
"""
resolve = self._resolve_value
collected_attributes = self._collect_attributes(component)
for (attr_name, raw_attr_value) in collected_attributes.items():
# prevent AttributeError - if attr_name names a slot that has not
# been initialized, we want obj_attr to fail the callable test so
# that setattr initializes the slot value
obj_attr = getattr(obj, attr_name, None)
attr_value = resolve(raw_attr_value)
if callable(obj_attr):
# this is a setter method
obj_attr(attr_value)
else:
# this is a simple attribute or property
setattr(obj, attr_name, attr_value)
def _collect_attributes(self, component):
"""Return the attributes used to wire objects of *component*.
:arg aglyph.component.Component component:
the component definition for the object being wired
:return:
the (ordered) attributes for wiring an object of *component*,
taking into account any attributes described by parent
components/templates
:rtype:
:class:`collections.OrderedDict`
"""
collected_items = list(component.attributes.items())
parent = self._context.get(component.parent_id)
while parent is not None:
if parent.attributes:
parent_items = list(parent.attributes.items())
# children extend/override parents (like partial functions)
collected_items = parent_items + collected_items
parent = self._context.get(parent.parent_id)
return OrderedDict(collected_items)
def _resolve_value(self, value_spec):
"""Assemble or evaluate the runtime value of an initialization
or attribute value specification.
:arg value_spec:
the value specified for a component initialization argument
or component attribute
If *value_spec* is an :class:`aglyph.component.Reference`, the
:meth:`assemble` method is called recursively to assemble the
specified component, which is then returned.
If *value_spec* is an :class:`aglyph.component.Evaluator`, it is
evaluated (which may also result in nested references being
assembled, as described above). The resulting value is returned.
If *value_spec* is a :func:`functools.partial`, it is called,
and the resulting value is returned.
In any other case, *value_spec* is returned **unchanged**.
"""
#PYVER: Python 2.7 type(value_spec) would just give <type 'instance'>
if isinstance(value_spec, Reference):
return self.assemble(value_spec)
elif isinstance(value_spec, Evaluator):
# need to pass a reference to the assembler since the
# evaluation may require further component assembly
return value_spec(self)
elif isinstance(value_spec, partial):
return value_spec()
else:
return value_spec
def _call_lifecycle_method(self, lifecycle_state, obj, component_id):
"""Determine which *obj* lifecycle method to call, and call it.
:arg str lifecycle_state:
a lifecycle state identifier recognized by Aglyph
:arg obj:
the object on which to call the lifecycle method
:arg str component_id:
the component unique ID for *obj*
"""
component = self._context[component_id]
lifecycle_method_names = self._get_lifecycle_method_names(
lifecycle_state, component)
if lifecycle_method_names:
self.__log.debug(
"considering %s method names %r for %r %s",
lifecycle_state, lifecycle_method_names, component_id, obj)
# now call the first lifecycle method that is defined for obj
for method_name in lifecycle_method_names:
obj_lifecycle_method = getattr(obj, method_name, None)
if obj_lifecycle_method is not None:
# issues/5: if the component specifies member_name, it is
# possible that an after_inject method could be called
# multiple times on the same object
if component.member_name:
msg = (
"component %r specifies member_name; it is "
"possible that the %s %s.%s() method may be "
"called MULTIPLE times on %r")
self.__log.warning(
msg, component_id, lifecycle_state,
component.member_name, method_name, obj)
warnings.warn(
msg % (
component_id, lifecycle_state,
component.member_name, method_name, obj),
RuntimeWarning)
try:
obj_lifecycle_method()
except Exception as e:
msg = "ignoring %s raised from %r"
self.__log.exception(
msg, e.__class__.__name__, obj_lifecycle_method)
warnings.warn(
msg % (e.__class__.__name__, obj_lifecycle_method),
RuntimeWarning)
else:
self.__log.info(
"called %s %r on %r %s",
lifecycle_state, obj_lifecycle_method,
component_id, obj)
finally:
# whether or not it raised an exception, the
# lifecycle state method has now been called
break
else:
# here, we've encountered a "preferred" lifecycle method
# name, but the object doesn't define it; while this may be
# expected/intended by the developer, it also may suggest
# that there is a better way to configure the context, so
# at least log a warning
self.__log.warning(
"%r %s does not define %s method %r",
component_id, obj, lifecycle_state, method_name)
else:
self.__log.info(
"no %s lifecycle methods specified for %s %r",
lifecycle_state, obj, component_id)
def _get_lifecycle_method_names(self, lifecycle_state, component):
"""Determine the preferred-order list of all lifecycle method
names that may be applicable for an object of *component*.
:arg str lifecycle_state:
a lifecycle state identifier recognized by Aglyph
:arg aglyph.component.Component component:
the component
"""
lifecycle_method_names = []
# 1. Component.<lifecycle_state>
method_name = getattr(component, lifecycle_state)
if method_name is not None:
lifecycle_method_names.append(method_name)
# (2) parent Template/Component.<lifecycle_state>
parent = self._context.get(component.parent_id)
while parent is not None:
method_name = getattr(parent, lifecycle_state)
if method_name is not None:
lifecycle_method_names.append(method_name)
# (3) parent-of-parent Template/Component.<lifecycle_state>
parent = self._context.get(parent.parent_id)
# (4) Context.<lifecycle_state>
method_name = getattr(self._context, lifecycle_state)
if method_name is not None:
lifecycle_method_names.append(method_name)
return lifecycle_method_names
def init_singletons(self):
"""Assemble and cache all singleton component objects.
.. versionadded: 2.1.0
:return:
the initialized singleton component IDs
:rtype:
:obj:`list`
This method may be called at any time to "prime" the internal
singleton cache. For example, to eagerly initialize all
singleton components for your application::
assembler = Assembler(my_context)
assembler.init_singletons()
.. note::
Only singleton components that do not *already* have cached
objects will be initialized by this method.
Initialization of singleton component objects is a
thread-safe operation.
"""
return self._init_cache("singleton")
def clear_singletons(self):
"""Evict all cached singleton component objects.
:return:
the evicted singleton component IDs
:rtype:
:obj:`list`
Aglyph makes the following guarantees:
#. All cached singleton objects' "before_clear" lifecycle
methods are called (if specified) when they are evicted from
cache.
#. The singleton cache will be empty when this method
terminates.
.. note::
Any exception raised by a "before_clear" lifecycle method is
caught, logged, and issued as a :class:`RuntimeWarning`.
Eviction of cached singleton component objects is a
thread-safe operation.
"""
return self._clear_cache("singleton")
def init_borgs(self):
"""Assemble and cache the shared-states for all borg component
objects.
.. versionadded: 2.1.0
:return:
the initialized borg component IDs
:rtype:
:obj:`list`
This method may be called at any time to "prime" the internal
borg cache. For example, to eagerly initialize all borg
component shared-states for your application::
assembler = Assembler(my_context)
assembler.init_borgs()
.. note::
Only borg components that do not *already* have cached
shared-states will be initialized by this method.
Initialization of borg component shared-states is a
thread-safe operation.
"""
return self._init_cache("borg")
def clear_borgs(self):
"""Evict all cached borg component shared-states.
:return:
the evicted borg component IDs
:rtype:
:obj:`list`
Aglyph makes the following guarantees:
#. All cached borg shared-states' "before_clear" lifecycle
methods are called (if specified) when they are evicted from
cache.
#. The borg cache will be empty when this method terminates.
.. note::
Any exception raised by a "before_clear" lifecycle method is
caught, logged, and issued as a :class:`RuntimeWarning`.
Eviction of cached borg component shared-states is a
thread-safe operation.
"""
return self._clear_cache("borg")
def clear_weakrefs(self):
"""Evict all cached weakref component objects.
:return:
the evicted weakref component IDs
:rtype:
:obj:`list`
Aglyph makes the following guarantees:
#. **IF** a cached weakref object is still available **AND**
the component definition specifies a "before_clear" lifecycle
method, Aglyph will call that method when the object is
evicted.
#. The weakref cache will be empty when this method terminates.
.. note::
Any exception raised by a "before_clear" lifecycle method is
caught, logged, and issued as a :class:`RuntimeWarning`.
Eviction of cached weakref component objects is a thread-safe
operation.
.. warning::
While eviction of weakref components is a thread-safe
operation with respect to *explicit* modification of the
weakref cache (i.e. any other thread attempting to
:meth:`assemble` a weakref component or to
``clear_weakrefs()`` will be blocked until this method
returns), the nature of weak references means that entries
may still "disappear" from the cache *even while the cache
lock is held.*
With respect to cache-clearing, this means that referent
component objects may no longer be available even *after* the
cache lock has been acquired and the weakref component IDs
(keys) are retrieved from the cache. Practically speaking,
this means that callers must be aware of two things:
#. Aglyph **cannot** guarantee that "before_clear" lifecycle
methods are called on weakref component objects, because
there is no guarantee that a cached weak references is
"live." (This is the nature of weak references.)
#. Aglyph will only return the component IDs of weakref
component objects that were "live" at the moment they were
cleared.
Please refer to the :mod:`weakref` module for a detailed
explanation of weak reference behavior.
"""
with self._caches["weakref"] as cache:
eligible_weakref_ids = list(cache.keys())
cleared_weakref_ids = []
try:
for weakref_id in eligible_weakref_ids:
ref = cache.pop(weakref_id)
obj = ref()
if obj is not None:
self._call_lifecycle_method(
"before_clear", obj, weakref_id)
cleared_weakref_ids.append(weakref_id)
obj = None
else:
self.__log.info(
"weak reference to object of component %r is "
"already dead; any before_clear method "
"for this component will NOT be called",
weakref_id)
ref = None
finally:
cache.clear()
return cleared_weakref_ids
def _init_cache(self, strategy):
"""Prime the cache for *strategy* objects.
:arg str strategy:
"singleton" or "borg"
.. note::
The "weakref" strategy is not explicitly supported here
because priming a weak reference cache is nonsensical.
"""
with self._caches[strategy] as cache:
component_ids = []
for component in self._context.iter_components(strategy):
if component.unique_id not in cache:
self.assemble(component.unique_id)
component_ids.append(component.unique_id)
return component_ids
def _clear_cache(self, strategy):
"""Evict all objects from the cache for *strategy* objects,
calling the "before_clear" lifecycle method for each object.
:arg str strategy:
"singleton", "borg", or "weakref"
"""
with self._caches[strategy] as cache:
component_ids = list(cache.keys())
try:
for component_id in component_ids:
obj = cache.pop(component_id)
self._call_lifecycle_method(
"before_clear", obj, component_id)
obj = None
finally:
cache.clear()
return component_ids
def __contains__(self, component_spec):
"""Tell whether or not the component identified by
*component_spec* is defined in this assembler's context.
:arg component_spec:
used to determine the dotted name or component unique ID
:return:
``True`` if *component_spec* identifies a component that is
defined in this assembler's context, else ``False``
.. note::
Any *component_spec* for which this method returns ``True``
can be assembled by this assembler.
Accordingly, this method will return ``False`` if
*component_spec* actually identifies a
:class:`aglyph.component.Template` defined in this
assembler's context.
"""
try:
component_id = _identify(component_spec)
except:
return False
else:
return self._context.get_component(component_id) is not None
def __str__(self):
return "<%s @%08x %s>" % (
name_of(self.__class__), id(self), self._context)
def __repr__(self):
return "%s.%s(%r)" % (
self.__class__.__module__, name_of(self.__class__), self._context)
@traced
@logged
class _ReentrantMutexCache(dict):
"""A mapping that uses a reentrant lock object for synchronization.
Atomic "check-then-act" operations can be performed by
acquiring the cache lock, performing the check-then-act sequence,
and finally releasing the cache lock.
If the lock is held, any attempt to acquire it by a thread OTHER
than the holding thread will block until the holding thread releases
the lock. (A reentrant mutex permits the same thread to acquire the
same lock more than once, allowing nested access to a shared
resource by a single thread.)
A ``_ReentrantMutexCache`` object acts as a `context manager
<https://docs.python.org/3/library/stdtypes.html#typecontextmanager>`_
using `the with statement
<https://docs.python.org/3/reference/compound_stmts.html#with>`_::
cache = _ReentrantMutexCache()
...
with cache:
# check-then-act
"""
def __init__(self):
#PYVER: arguments to super() are implicit under Python 3
super(_ReentrantMutexCache, self).__init__()
self.__lock = threading_.RLock()
def __enter__(self):
"""Acquire the cache lock."""
self.__lock.acquire()
return self
def __exit__(self, e_type, e_obj, tb):
"""Release the cache lock.
:arg e_type:
the exception class if an exception occurred while executing
the body of the ``with`` statement, else ``None``
:arg Exception e_value:
the exception object if an exception occurred while executing
the body of the ``with`` statement, else ``None``
:arg tb:
the traceback if an exception occurred while executing the
body of the ``with`` statement, else ``None``
.. note::
If an exception occurred, it will be logged but allowed to
propagate.
"""
self.__lock.release()
if e_obj is not None:
self.__log.error(
"exception occurred while cache lock was held: %s", e_obj)
def __str__(self):
return "<%s @%08x>" % (name_of(self.__class__), id(self))
def __repr__(self):
return "%s.%s()" % (
self.__class__.__module__, name_of(self.__class__)) | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/aglyph/assembler.py | assembler.py |
# Copyright (c) 2006, 2011, 2013-2018 Matthew Zipay.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""This module defines a custom error type and several utility functions
used by Aglyph.
.. note::
Aglyph uses the standard :mod:`logging` module, but by default
registers a :class:`logging.NullHandler` to suppress messages.
To enable Aglyph logging, configure a logger and handler for the
*"aglyph"* log channel (see :mod:`logging.config`).
.. note::
.. versionadded:: 3.0.0
Aglyph framework functions and methods are fully traced using
`Autologging <http://ninthtest.info/python-autologging/>`_. However,
all tracing is **deactivated** by default.
To activate tracing:
1. Configure a logger and handler for the *"aglyph"* log channel and
set the logging level to :attr:`autologging.TRACE`.
2. Run Aglyph with the *AGLYPH_TRACED* environment variable set to a
**non-empty** value.
"""
from collections import namedtuple
# see https://semver.org/
version_info = namedtuple(
"version_info", ["major", "minor", "patch", "pre_release", "metadata"])(
3, 0, 0, "", "")
__author__ = "Matthew Zipay <[email protected]>"
__version__ = "%d.%d.%d%s%s" % version_info
from inspect import ismodule
import logging
import os
import sys
import autologging
if not os.getenv("AGLYPH_TRACED"):
autologging.install_traced_noop()
from autologging import traced
__all__ = [
"version_info",
"AglyphError",
"format_dotted_name",
"resolve_dotted_name",
]
# configure a logging for the "aglyph" channel to see log output
_log = logging.getLogger(__name__)
# prevent messages to the console when there's no logging configuration
# (see https://docs.python.org/3/howto/logging.html#library-config)
if not _log.handlers:
_log.addHandler(logging.NullHandler())
# log the Aglyph and Python versions, the platform, and compatibility details
from aglyph._compat import is_string, name_of, platform_detail
_log.info("Aglyph %s on %s", __version__, platform_detail)
class AglyphDeprecationWarning(DeprecationWarning):
"""Issued when deprecated Aglyph functions, classes, or methods are
used.
"""
def __init__(self, name, replacement=None):
"""
:arg str name:
the name of the deprecated function, class, or method
:keyword str replacement:
the name of the replacement function, class, or method
"""
message = (
"%s is deprecated and will be removed in release %d.0.0." %
(name, MAJOR + 1))
if replacement is not None:
message = "%s Use %s instead." % (message, replacement)
#PYVER: arguments to super() are implicit under Python 3
super(AglyphDeprecationWarning, self).__init__(message)
class AglyphError(Exception):
"""Raised when Aglyph operations fail with a condition that is not
sufficiently described by a built-in exception.
"""
def __init__(self, message, cause=None):
#PYVER: arguments to super() are implicit under Python 3
super(AglyphError, self).__init__(message)
self.cause = cause
@traced
def format_dotted_name(obj):
"""Return the importable dotted-name string for *obj*.
:param obj:
an **importable** class, function, or module
:return:
a dotted name representing *obj*
:rtype:
:obj:`str`
:raise AglyphError:
if *obj* does not have a resolvable (importable) dotted name
The dotted name returned by this function is a *"dotted_name.NAME"*
or *"dotted_name"* string for *obj* that represents a valid absolute
import statement according to the following productions:
.. productionlist::
absolute_import_stmt: "from" dotted_name "import" NAME
: | "import" dotted_name
dotted_name: NAME ('.' NAME)*
.. note::
This function is the inverse of :func:`resolve_dotted_name`.
.. warning::
This function will attempt to use the ``__qualname__`` attribute,
which is only available in Python 3.3+. When ``__qualname__`` is
**not** available, ``__name__`` is used instead.
.. seealso:: :pep:`3155`, :func:`aglyph._compat.name_of`
"""
if not _importable(obj):
raise AglyphError("%r does not have an importable dotted name" % obj)
if not ismodule(obj):
return "%s.%s" % (obj.__module__, name_of(obj))
else:
return obj.__name__
@traced
def _importable(obj):
"""Tell whether or not *obj* is directly importable.
:arg obj:
any object
:rtype:
:obj:`bool`
If *obj* is importable, then:
>>> resolve_dotted_name(format_dotted_name(obj)) is obj
True
"""
if ismodule(obj):
return True
elif hasattr(obj, "__module__") and hasattr(obj, "__name__"):
return obj.__name__ in sys.modules[obj.__module__].__dict__
else:
return False
@traced
def resolve_dotted_name(dotted_name):
"""Return the class, function, or module identified by
*dotted_name*.
:param str dotted_name:
a string representing an **importable** class, function, or
module
:return:
a class, function, or module
*dotted_name* must be a "dotted_name.NAME" or "dotted_name"
string that represents a valid absolute import statement according
to the following productions:
.. productionlist::
absolute_import_stmt: "from" dotted_name "import" NAME
: | "import" dotted_name
dotted_name: NAME ('.' NAME)*
.. note::
This function is the inverse of :func:`format_dotted_name`.
"""
if '.' in dotted_name:
(module_name, name) = dotted_name.rsplit('.', 1)
module = __import__(module_name, fromlist=[name], level=0)
obj = getattr(module, name)
else:
obj = __import__(dotted_name, level=0)
return obj
@traced
def _identify(spec):
"""Determine the unique ID for *spec*.
:arg spec:
an **importable** class, function, or module; or a :obj:`str`
:return:
*spec* unchanged (if it is a :obj:`str`), else *spec*'s
importable dotted name
:rtype:
:obj:`str`
If *spec* is a string, it is assumed to already represent a unique
ID and is returned unchanged. Otherwise, *spec* is assumed to be an
**importable** class, function, or module, and its dotted name is
returned (see :func:`format_dotted_name`).
"""
return spec if is_string(spec) else format_dotted_name(spec) | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/aglyph/__init__.py | __init__.py |
# Copyright (c) 2006, 2011, 2013-2018 Matthew Zipay.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""This module defines constants, functions, and classes that are used
to enable Python version and variant cross-compatibility.
There are two primary goals:
#. Make the differences between Python 2 ``str``/``unicode`` and
Python 3 ``bytes``/``str`` as transparent as possible.
#. Hide Python API differences behind aliases that can be used in any
version or variant.
Keeping these constructs contained in a separate module makes them
easier to maintain (and easier to remove later).
"""
__author__ = "Matthew Zipay <[email protected]>"
from inspect import getmodule
import logging
import os
import platform
import sys
import types
import xml.etree.ElementTree as ET
from aglyph import __version__
from autologging import logged, traced
__all__ = [
"is_python_2",
"is_python_3",
"is_pypy",
"is_stackless",
"is_jython",
"is_ironpython",
"platform_detail",
"TextType",
"DataType",
"is_string",
"new_instance",
"name_of",
"DoctypeTreeBuilder",
"CLRXMLParser",
"AglyphDefaultXMLParser",
]
_log = logging.getLogger(__name__)
#: True if the Python MAJOR version is 2.
is_python_2 = (sys.version_info[0] == 2)
#: True if the Python MAJOR version is 3.
is_python_3 = (sys.version_info[0] == 3)
_sys_version = ' '.join(sys.version.split())
try:
_py_impl = platform.python_implementation()
except:
_py_impl = "Python"
#: True if the runtime Python implementation is PyPy.
is_pypy = \
_py_impl == "PyPy" and getattr(sys, "pypy_version_info", None) is not None
try:
import stackless
except:
_has_stackless = False
else:
_py_impl = "Stackless Python"
_has_stackless = True
#: True if the runtime Python implementation is Stackless Python.
is_stackless = \
(not is_pypy) and _has_stackless and ("Stackless" in sys.version)
#: True if the runtime Python implementation is Jython.
is_jython = \
_py_impl == "Jython" and getattr(sys, "JYTHON_JAR", None) is not None
#: True if the runtime Python implementation is IronPython.
is_ironpython = _py_impl == "IronPython"
try:
import clr
except ImportError:
is_ironpython = False
_platform = None
try:
# preferred (most detail, but not universally available/supported)
_platform = platform.platform()
except:
_platform = getattr(os, "name", "unknown")
if hasattr(sys, "getwindowsversion"):
try:
_platform = "%s %s" % (_platform, sys.getwindowsversion())
except:
pass
#: The python implementation, version, and platform information.
platform_detail = "%s %s %s" % (_py_impl, _sys_version, _platform)
if "APPENGINE_RUNTIME" in os.environ:
platform_detail = "%s [GAE]" % platform_detail
_builtins = getmodule(hex).__dict__
#: The type of Unicode text strings.
TextType = _builtins["str"] if is_python_3 else _builtins["unicode"]
#: The type of encoded byte data strings.
DataType = _builtins["bytes"] if is_python_3 else _builtins["str"]
_StringTypes = (TextType, DataType)
def is_string(obj):
"""Return ``True`` if *obj* is Unicode text or encoded bytes data.
:param obj: an object
:rtype: bool
"""
return isinstance(obj, _StringTypes)
_instance_type = getattr(types, "InstanceType", None)
def new_instance(cls):
"""Create an **uninitialized** instance of the class *cls*.
:param cls: a class object
.. note::
This function can create uninitialized instances of both
"new-style" (Python 3, Python 2 derived from :class:`object`) and
"old-style" (Python 2 **not** derived from :class:`object`)
classes.
"""
return object.__new__(cls) if type(cls) is type else _instance_type(cls)
def name_of(obj):
"""Return the name of *obj*.
:param obj: any object
.. note::
This function will return ``obj.__qualname__`` if :pep:`3155` is
supported in the runtime Python implementation; otherwise
``obj.__name__`` is returned.
"""
return getattr(obj, "__qualname__", obj.__name__)
class DoctypeTreeBuilder(ET.TreeBuilder):
"""An :mod:`xml.etree.ElementTree.TreeBuilder` that avoids
deprecation warnings for
:meth:`xml.etree.ElementTree.XMLParser.doctype`.
.. seealso::
`Issue14007 <http://bugs.python.org/issue14007>`_
xml.etree.ElementTree - XMLParser and TreeBuilder's doctype()
method missing
"""
def __init__(self, *args, **keywords):
"""
:arg tuple *args: the positional initialization arguments
:arg dict **keywords: the keyword initialization arguments
"""
#PYVER: arguments to super() are implicit under Python 3
super(DoctypeTreeBuilder, self).__init__(*args, **keywords)
self._doctype_name = None
self._doctype_pubid = None
self._doctype_system = None
@property
def doctype_name(self):
"""The document type name *(read-only)*."""
return self._doctype_name
@property
def doctype_pubid(self):
"""The document type public identifier *(read-only)*."""
return self._doctype_pubid
@property
def doctype_system(self):
"""The document type system identifier *(read-only)*."""
return self._doctype_system
def doctype(self, name, pubid, system):
"""Report the parsed DOCTYPE declaration.
:arg str name: the document type name
:arg str pubid: the document type public identifier
:arg str system: the document type system identifier
"""
self._doctype_name = name
self._doctype_pubid = pubid
self._doctype_system = system
if is_ironpython:
clr.AddReference("System.IO")
clr.AddReference("System.Xml")
_log.info("loaded System.IO and System.Xml CLR namespaces")
from System.IO import StringReader
from System.Xml import (
DtdProcessing,
ValidationType,
XmlNodeType,
XmlReader,
XmlReaderSettings
)
@traced
@logged
class CLRXMLParser(ET.XMLParser):
"""An :class:`xml.etree.ElementTree.XMLParser` that delegates
parsing to the .NET CLR `System.Xml.XmlReader
<http://msdn.microsoft.com/en-us/library/system.xml.xmlreader>`_
parser.
.. note::
`IronPython <http://ironpython.net/>`_ is not able to load
CPython's :mod:`xml.parsers.expat` module by default, and so
the default parser used by ElementTree does not exist.
"""
def __init__(self, target=DoctypeTreeBuilder(), validating=False):
"""
:keyword xml.etree.ElementTree.TreeBuilder target:
the target object (optional; defaults to
:class:`aglyph._compat.DoctypeTreeBuilder`)
:keyword bool validating:
specify ``True`` to use a validating parser
"""
settings = XmlReaderSettings()
settings.IgnoreComments = True
settings.IgnoreProcessingInstructions = True
settings.IgnoreWhitespace = True
if not validating:
settings.DtdProcessing = DtdProcessing.Ignore
settings.ValidationType = getattr(ValidationType, "None")
else:
settings.DtdProcessing = DtdProcessing.Parse
settings.ValidationType = ValidationType.DTD
self.settings = settings
self.version = platform.python_compiler()
self.__log.debug("ET parser version is %s", self.version)
self._target = target
self._buffer = []
def feed(self, data):
"""Add more XML data to be parsed.
:arg str data: raw XML read from a stream
.. note::
All *data* across calls to this method are buffered
internally; the parser itself is not actually created
until the :meth:`close` method is called.
"""
self._buffer.append(data)
def close(self):
"""Parse the XML from the internal buffer to build an
element tree.
:return:
the root element of the XML document
:rtype:
:class:`xml.etree.ElementTree.ElementTree`
"""
xml_string = "".join(self._buffer)
self._buffer = None
reader = XmlReader.Create(StringReader(xml_string), self.settings)
# figure out which encoding to use
next = reader.Read()
document_encoding = (
reader.GetAttribute("encoding")
if next and reader.NodeType == XmlNodeType.XmlDeclaration
else None)
if document_encoding:
self.__log.info(
"parsed document encoding %r from XML declaration",
document_encoding)
else:
document_encoding = "UTF-8"
self.__log.warn(
"document encoding is missing! assuming default %r",
document_encoding)
while next:
if reader.IsStartElement():
self._start_element(reader)
elif reader.NodeType in [XmlNodeType.Text, XmlNodeType.CDATA]:
# decode the value first to work around IronPython quirk
self._target.data(reader.Value.decode(document_encoding))
elif reader.NodeType == XmlNodeType.EndElement:
self._target.end(reader.LocalName)
next = reader.Read()
return self._target.close()
def _start_element(self, reader):
"""Notify the tree builder that a start element has been
encountered.
:arg reader:
a .NET `System.Xml.XmlReader
<http://msdn.microsoft.com/en-us/library/system.xml.xmlreader>`_
If the element is an empty element (e.g. ``<name />``), the
tree builder is also notified that the element has been
closed.
"""
name = reader.LocalName
attributes = {}
while reader.MoveToNextAttribute():
attributes[reader.Name] = reader.Value
reader.MoveToElement()
self._target.start(name, attributes)
if reader.IsEmptyElement:
self._target.end(name)
else:
class CLRXMLParser(ET.XMLParser):
"""A dummy class that will raise :class:`RuntimeError` if
instantiated.
"""
def __new__(self, *args, **keywords):
raise RuntimeError(".NET CLR is not available")
#: The default XML parser used by :class:`aglyph.context.XMLContext`.
AglyphDefaultXMLParser = ET.XMLParser if not is_ironpython else CLRXMLParser
# log compatibility details
_log.debug(
"compatibility details:\n"
" is_python_2? %r\n"
" is_python_3? %r\n"
" is_pypy? %r\n"
" is_stackless? %r\n"
" is_jython? %r\n"
" is_ironpython? %r\n"
" TextType is %r\n"
" DataType is %r\n"
" _instance_type is %r\n"
" __qualname__ supported? %r\n"
" AglyphDefaultXMLParser is %r",
is_python_2,
is_python_3,
is_pypy,
is_stackless,
is_jython,
is_ironpython,
TextType,
DataType,
_instance_type,
hasattr(DoctypeTreeBuilder, "__qualname__"),
AglyphDefaultXMLParser
)
del _sys_version, _py_impl, _has_stackless, _platform, _builtins | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/aglyph/_compat.py | _compat.py |
# Copyright (c) 2006, 2011, 2013-2018 Matthew Zipay.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""Classes and utilities for integrating Aglyph with
`CherryPy <http://www.cherrypy.org/>`_.
.. versionadded:: 2.1.0
An example using XML configuration::
from aglyph.assembler import Assembler
from aglyph.context import XMLContext
from aglyph.integration.cherrypy import AglyphDIPlugin
import cherrypy
context = XMLContext("my-aglyph-context.xml")
assembler = Assembler(context)
cherrypy.engine.aglyph = AglyphDIPlugin(cherrypy.engine, assembler)
cherrypy.engine.aglyph.subscribe()
An example using the fluent configuration API::
from aglyph.integration.cherrypy import AglyphDIPlugin
from aglyph.context import Context
import cherrypy
context = Context("my-aglyph-context")
context.template(...)
context.prototype(...)
context.singleton(...)
context.borg(...)
context.weakref(...)
# and so on
assembler = Assembler(context)
cherrypy.engine.aglyph = AglyphDIPlugin(cherrypy.engine, assembler)
cherrypy.engine.aglyph.subscribe()
In either scenario, you can now use Aglyph to assemble components in
your CherryPy application by publishing an "aglyph-assemble" event to
the `Web Site Process Bus
<https://cherrypy.readthedocs.org/en/latest/pkg/cherrypy.process.html#web-site-process-bus>`_.
This event requires an Aglyph component specification (either an ID or
an object whose dotted name is a component ID)::
...
my_obj = cherrypy.engine.publish("aglyph-assemble", "my-id").pop()
...
"""
from __future__ import absolute_import
__author__ = "Matthew Zipay <[email protected]>"
import logging
# for logging, use self.bus.log rather than self.__log
from autologging import traced
from aglyph import __version__
from aglyph._compat import name_of
from cherrypy.process.plugins import SimplePlugin
__all__ = [
"AglyphDIPlugin",
]
_log = logging.getLogger(__name__)
@traced
class AglyphDIPlugin(SimplePlugin):
"""A `CherryPy <http://www.cherrypy.org/>`_ `plugin
<https://cherrypy.readthedocs.org/en/latest/extend.html#plugins>`_
that provides Aglyph dependency injection support to CherryPy
applications.
The Aglyph DI plugin subscribes to the following channels:
aglyph-assemble
Publish a component ID to this channel to assemble the component.
aglyph-init-singletons
Publish to this channel to pre-assemble and cache all *singleton*
components.
aglyph-clear-singletons
Publish to this channel to clear all cached *singleton*
components.
aglyph-init-borgs
Publish to this channel to pre-assemble and cache the
shared-states of all *borg* components.
aglyph-clear-borgs
Publish to this channel to clear all cached *borg* components.
aglyph-clear-weakrefs
Publish to this channel to clear all cached *weakref* components.
"""
def __init__(self, bus, assembler, eager_init=True):
"""
:arg cherrypy.process.wspbus.Bus bus:
the CherryPy Web Site Process Bus
:arg aglyph.assembler.Assembler assembler:
the configured Aglyph assembler (or binder)
:keyword bool eager_init:
if ``True``, all *singleton* and *borg* components in the
assembler's context will be pre-assembed and cached when the
Aglyph DI plugin is started
"""
SimplePlugin.__init__(self, bus)
self._assembler = assembler
self._eager_init = eager_init
@property
def eager_init(self):
"""Return the current value of the eager initialization flag."""
return self._eager_init
@eager_init.setter
def eager_init(self, flag):
"""Set the eager initialization flag.
:arg bool flag:
whether (``True``) or not (``False``) the Aglyph DI plugin
should pre-assemble and cache all *singleton* and *borg*
components when the plugin is (re)started
"""
self._eager_init = flag
def start(self):
"""Subscribe to all Aglyph DI channels.
aglyph-assemble
Publish a component ID to this channel to assemble the
component.
aglyph-init-singletons
Publish to this channel to pre-assemble and cache all
*singleton* components.
aglyph-clear-singletons
Publish to this channel to clear all cached *singleton*
components.
aglyph-init-borgs
Publish to this channel to pre-assemble and cache the
shared-states of all *borg* components.
aglyph-clear-borgs
Publish to this channel to clear all cached *borg*
components.
aglyph-clear-weakrefs
Publish to this channel to clear all cached *weakref*
components.
.. note::
If :attr:`eager_init` is ``True``, all *singleton* and *borg*
components are pre-assembled and cached before the channels
are subscribed.
"""
if self._eager_init:
self.bus.log(
"initializing Aglyph singleton and borg component objects")
self.init_singletons()
self.init_borgs()
self.bus.log("starting Aglyph dependency injection support")
self.bus.subscribe("aglyph-assemble", self.assemble)
self.bus.subscribe("aglyph-init-singletons", self.init_singletons)
self.bus.subscribe("aglyph-clear-singletons", self.clear_singletons)
self.bus.subscribe("aglyph-init-borgs", self.init_borgs)
self.bus.subscribe("aglyph-clear-borgs", self.clear_borgs)
self.bus.subscribe("aglyph-clear-weakrefs", self.clear_weakrefs)
def stop(self):
"""Unsubscribe from all Aglyph DI channels.
.. note::
After all Aglyph DI channels have been unsubscribed, the
*singleton*, *borg*, and *weakref* caches are automatically
cleared.
"""
self.bus.log("stopping Aglyph dependency injection support")
self.bus.unsubscribe("aglyph-assemble", self.assemble)
self.bus.unsubscribe("aglyph-init-singletons", self.init_singletons)
self.bus.unsubscribe("aglyph-clear-singletons", self.clear_singletons)
self.bus.unsubscribe("aglyph-init-borgs", self.init_borgs)
self.bus.unsubscribe("aglyph-clear-borgs", self.clear_borgs)
self.bus.unsubscribe("aglyph-clear-weakrefs", self.clear_weakrefs)
self.bus.log(
"clearing Aglyph singleton, borg, and weakref component objects")
self.clear_singletons()
self.clear_borgs()
self.clear_weakrefs()
def assemble(self, component_spec):
"""Return the object assembled according to *component_spec*.
:arg component_spec:
a string representing a component dotted name or unique ID;
or an importable class, function, or module
:return:
a complete object with all of its resolved dependencies
This method handles messages published to the
**aglyph-assemble** channel.
"""
self.bus.log("assembling %r" % component_spec)
return self._assembler.assemble(component_spec)
def init_singletons(self):
"""Assemble and cache all singleton component objects.
:return:
the initialized singleton component IDs
:rtype:
:obj:`list`
This method handles messages published to the
**aglyph-init-singletons** channel.
"""
singleton_ids = self._assembler.init_singletons()
if singleton_ids:
self.bus.log("initialized singletons %s" % repr(singleton_ids))
return singleton_ids
def clear_singletons(self):
"""Evict all cached singleton component objects.
:return:
the evicted singleton component IDs
:rtype:
:obj:`list`
This method handles messages published to the
**aglyph-clear-singletons** channel.
"""
singleton_ids = self._assembler.clear_singletons()
if singleton_ids:
self.bus.log("cleared singletons %s" % repr(singleton_ids))
return singleton_ids
def init_borgs(self):
"""Assemble and cache the shared-states for all borg component
objects.
:return:
the initialized borg component IDs
:rtype:
:obj:`list`
This method handles messages published to the
**aglyph-init-borgs** channel.
"""
borg_ids = self._assembler.init_borgs()
if borg_ids:
self.bus.log("initialized borgs %s" % repr(borg_ids))
return borg_ids
def clear_borgs(self):
"""Evict all cached borg component shared-states.
:return:
the evicted borg component IDs
:rtype:
:obj:`list`
This method handles messages published to the
**aglyph-clear-borgs** channel.
"""
borg_ids = self._assembler.clear_borgs()
if borg_ids:
self.bus.log("cleared borgs %s" % repr(borg_ids))
return borg_ids
def clear_weakrefs(self):
"""Evict all cached weakref component objects.
:return:
the evicted weakref component IDs
:rtype:
:obj:`list`
This method handles messages published to the
**aglyph-clear-weakrefs** channel.
"""
weakref_ids = self._assembler.clear_weakrefs()
if weakref_ids:
self.bus.log("cleared weakrefs %s" % repr(weakref_ids))
return weakref_ids
def __str__(self):
return "<%s @%08x %s>" % (
name_of(self.__class__), id(self), self._assembler)
def __repr__(self):
return "%s.%s(%r, %r, eager_init=%r)" % (
self.__class__.__module__, name_of(self.__class__),
self.bus, self._assembler, self._eager_init) | Aglyph | /Aglyph-3.0.0.tar.gz/Aglyph-3.0.0/aglyph/integration/cherrypy.py | cherrypy.py |
import logging
from .job import Job
from .errors import EnqueueError
QUEUE_PREFIX = "AGNER:"
BLOCK_SECONDS = 1
class Queue(object):
def __init__(self, queue_name, redis_connection):
"""Queues are responsible for both producing and consuming work
You must pass in a connected Redis object as well as a string queue_name
"""
self.redis = redis_connection
self.__queue_name = "%s%s" % (QUEUE_PREFIX, queue_name)
self.__should_run = True # set this to false to break consumer loops
self.log = logging.getLogger("%s.%s" % (__name__, queue_name))
self.log.debug(self.redis.ping())
def __len__(self):
"""Returns the number of jobs currently sitting in the queue
"""
return self.redis.llen(self.queue_name)
@property
def queue_name(self):
return self.__queue_name
def enqueue(self, job):
"""Enqueue a job for later processing, returns the new length of the queue
"""
if job.queue_name():
raise EnqueueError("job %s already queued!" % job.job_id)
new_len = self.redis.rpush(self.queue_name, job.serialize())
job.notify_queued(self)
return new_len
def next_job(self, timeout_seconds=None):
"""Retuns the next job in the queue, or None if is nothing there
"""
if timeout_seconds is not None:
timeout = timeout_seconds
else:
timeout = BLOCK_SECONDS
response = self.redis.blpop(self.queue_name, timeout)
if not response:
return
queue_name, serialized_job = response
job = Job.from_serialized(serialized_job)
if not job:
self.log.warn("could not deserialize job from: %s", serialized_job)
return job
def __iter__(self):
"""Generator interface that will block on a queue and return items as they
become available
"""
while self.__should_run:
job = self.next_job()
if job is not None:
yield job
raise StopIteration
def empty(self):
"""Empties the queue, you rarely want this other than for testing
"""
self.redis.delete(self.queue_name) | Agner | /Agner-0.2.1.tar.gz/Agner-0.2.1/agner/queue.py | queue.py |
import StringIO
from urllib import urlencode
import requests
from agora.client.execution import PlanExecutor
from rdflib import Graph
from rdflib.plugins.parsers.notation3 import BadSyntax
__author__ = "Fernando Serena"
class FountainException(Exception):
pass
class FragmentCollector(object):
""" Class for interacting with the Agora planner and executing the plan for a certain graph pattern.
"""
def __init__(self, planner_uri, gp):
self.__planner = planner_uri
self.__graph_pattern = gp
# Request a search plan on initialization and extract patterns and spaces
plan_graph = self.__get_gp_plan(self.__graph_pattern)
self.__plan_executor = PlanExecutor(plan_graph)
def __get_gp_plan(self, gp):
"""
Request the planner a search plan for a given gp and returns the plan as a graph.
:param gp:
:return:
"""
query = urlencode({'gp': gp})
response = requests.get('{}/plan?'.format(self.__planner) + query, headers={'Accept': 'text/turtle'})
graph = Graph()
try:
graph.parse(source=StringIO.StringIO(response.text), format='turtle')
except BadSyntax:
pass
return graph
def get_fragment(self, **kwargs):
return self.__plan_executor.get_fragment(**kwargs)
def get_fragment_generator(self, **kwargs):
return self.__plan_executor.get_fragment_generator(**kwargs)
class Agora(object):
"""
Wrapper class for the FragmentCollector
"""
def __init__(self, host='localhost', port=9001):
self.__host = 'http://{}:{}'.format(host, port)
def get_fragment(self, gp, **kwargs):
"""
Return a complete fragment for a given gp.
:param gp: A graph pattern
:return:
"""
collector = FragmentCollector(self.__host, gp)
return collector.get_fragment(**kwargs)
def get_fragment_generator(self, gp, **kwargs):
"""
Return a fragment generator for a given gp.
:param gp:
:param kwargs:
:return:
"""
collector = FragmentCollector(self.__host, gp)
return collector.get_fragment_generator(**kwargs)
@property
def prefixes(self):
response = requests.get(self.__host + '/prefixes')
if response.status_code == 200:
return response.json()
raise FountainException(response.text) | Agora-Client | /Agora-Client-0.5.0.tar.gz/Agora-Client-0.5.0/agora/client/wrapper.py | wrapper.py |
import Queue
import StringIO
import logging
import multiprocessing
import traceback
from threading import RLock, Thread, Event
from xml.sax import SAXParseException
import gc
from _bsddb import DBNotFoundError
from datetime import datetime as dt
import requests
from agora.client.namespaces import AGORA
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import wait
from rdflib import ConjunctiveGraph, RDF, URIRef
pool = ThreadPoolExecutor(max_workers=20)
__author__ = 'Fernando Serena'
log = logging.getLogger('agora.client')
_accept_mimes = {'turtle': 'text/turtle', 'xml': 'application/rdf+xml'}
class StopException(Exception):
pass
def chunks(l, n):
"""
Yield successive n-sized chunks from l.
:param l:
:param n:
:return:
"""
if n:
for i in xrange(0, len(l), n):
yield l[i:i + n]
def __extend_uri(prefixes, short):
"""
Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return:
"""
for prefix in prefixes:
if short.startswith(prefix):
return short.replace(prefix + ':', prefixes[prefix])
return short
class PlanExecutor(object):
def __init__(self, plan):
self.__plan_graph = plan
self.__fragment = set([])
self.__uri_cache = {}
self.__node_spaces = {}
self.__node_patterns = {}
self.__spaces = None
self.__patterns = {}
self.__subjects_to_ignore = {}
self.__resource_queue = {}
self.__resource_lock = RLock()
self.__completed = False
self.__last_success_format = None
self.__last_iteration_ts = dt.now()
# Request a search plan on initialization and extract patterns and spaces
self.__extract_patterns_and_spaces()
def __extract_patterns_and_spaces(self):
"""
Analyses the search plan graph in order to build the required data structures from patterns
and spaces.
:return:
"""
def __decorate_nodes(nodes, space):
"""
Performs a backward search from a list of pattern nodes and assigns a set of search spaces
to all encountered nodes.
:param nodes: List of pattern nodes that belongs to a search space
:param space: List of search space id
:return:
"""
for n in nodes:
if n not in self.__node_spaces:
self.__node_spaces[n] = set([])
self.__node_spaces[n].add(space)
pred_nodes = self.__plan_graph.subjects(AGORA.next, n)
__decorate_nodes(pred_nodes, space)
# Extract all search spaces in the plan and build a dictionary of subjects-to-ignore per each of them.
# Ignored subjects are those that won't be dereferenced due to a explicit graph pattern (object) filter,
# e.g. ?s doap:name "jenkins" -> All ?s that don't match the filter will be ignored.
self.__spaces = set(self.__plan_graph.subjects(RDF.type, AGORA.SearchSpace))
self.__subjects_to_ignore = dict([(sp, set([])) for sp in self.__spaces])
patterns = list(self.__plan_graph.subjects(RDF.type, AGORA.TriplePattern))
for tp in patterns:
# A triple pattern belongs to a UNIQUE search space
space = list(self.__plan_graph.subjects(AGORA.definedBy, tp)).pop()
self.__patterns[tp] = {'space': space}
# Depending on the format of each triple pattern (either '?s a Concept' or '?s prop O'),
# it is required to extract different properties.
tp_pred = list(self.__plan_graph.objects(tp, predicate=AGORA.predicate)).pop()
if tp_pred == RDF.type: # ?s a Concept
self.__patterns[tp]['type'] = list(self.__plan_graph.objects(tp, predicate=AGORA.object)).pop()
try:
check_type = list(self.__plan_graph.objects(tp, predicate=AGORA.checkType)).pop().toPython()
except IndexError:
check_type = True
self.__patterns[tp]['check'] = check_type
else: # ?s prop O
self.__patterns[tp]['property'] = tp_pred
tp_obj = list(self.__plan_graph.objects(tp, predicate=AGORA.object)).pop()
if (tp_obj, RDF.type, AGORA.Literal) in self.__plan_graph: # In case O is a Literal
self.__patterns[tp]['filter_object'] = list(self.__plan_graph.objects(tp_obj, AGORA.value)).pop()
elif isinstance(tp_obj, URIRef):
self.__patterns[tp]['filter_object'] = tp_obj
tp_sub = list(self.__plan_graph.objects(tp, predicate=AGORA.subject)).pop()
if isinstance(tp_sub, URIRef):
self.__patterns[tp]['filter_subject'] = tp_sub
# Get all pattern nodes (those that have a byPattern properties) of the search plan and search backwards
# in order to set the scope of each search space.
nodes = list(self.__plan_graph.subjects(AGORA.byPattern, tp))
for n in nodes:
if n not in self.__node_patterns:
self.__node_patterns[n] = set([])
self.__node_patterns[n].add(tp)
__decorate_nodes(nodes, space)
def get_fragment(self, **kwargs):
"""
Return a complete fragment.
:param gp:
:return:
"""
gen, namespaces, plan = self.get_fragment_generator(**kwargs)
graph = ConjunctiveGraph()
[graph.bind(prefix, u) for (prefix, u) in namespaces]
[graph.add((s, p, o)) for (_, s, p, o) in gen]
return graph
def get_fragment_generator(self, on_load=None, on_seeds=None, on_plink=None, on_link=None, on_type=None,
on_type_validation=None, on_tree=None, workers=None, stop_event=None, queue_wait=None,
queue_size=100, provider=None, lazy=True):
"""
Create a fragment generator that executes the search plan.
:param on_load: Function to be called just after a new URI is dereferenced
:param on_seeds: Function to be called just after a seed of a tree is identified
:param on_plink: Function to be called when a pattern link is reached
:param on_link: Function to be called when following a property that is not of a pattern
:param on_type: Function to be called when search for a type triple
:param on_type_validation: Function to be called just after a type is validated
:param on_tree: Function to be called just before a tree is going to be explored
:param provider:
:param queue_size:
:param workers:
:param stop_event:
:param queue_wait:
:param lazy:
:return:
"""
if workers is None:
workers = multiprocessing.cpu_count()
fragment_queue = Queue.Queue(maxsize=queue_size)
workers_queue = Queue.Queue(maxsize=workers)
if stop_event is None:
stop_event = Event()
def __create_graph():
if provider is None:
return ConjunctiveGraph()
else:
return provider.create(conjunctive=True)
def __release_graph(g):
if provider is not None:
provider.release(g)
else:
g.remove((None, None, None))
g.close()
def __open_graph(gid, loader, format):
if provider is None:
content, headers = loader(gid, format)
if not isinstance(content, bool):
g = ConjunctiveGraph()
g.parse(source=content, format=format)
return g
return content
else:
return provider.create(gid=gid, loader=loader, format=format)
def __get_content(uri, format):
try:
# log.debug('[Dereference][START] {}'.format(uri))
response = requests.get(uri, headers={'Accept': _accept_mimes[format]}, timeout=30)
except requests.Timeout:
log.debug('[Dereference][TIMEOUT][GET] {}'.format(uri))
return True
except UnicodeEncodeError:
log.debug('[Dereference][ERROR][ENCODE] {}'.format(uri))
return True
except Exception:
log.debug('[Dereference][ERROR][GET] {}'.format(uri))
return True
if response.status_code == 200:
try:
return StringIO.StringIO(response.content), response.headers
except SyntaxError:
traceback.print_exc()
log.error('[Dereference][ERROR][PARSE] {}'.format(uri))
return False
except ValueError:
traceback.print_exc()
log.debug('[Dereference][ERROR][VAL] {}'.format(uri))
return False
except DBNotFoundError:
# Ignore this exception... it is raised due to a stupid problem with prefixes
return True
except SAXParseException:
traceback.print_exc()
log.error('[Dereference][ERROR][SAX] {}'.format(uri))
return False
except Exception:
traceback.print_exc()
log.error('[Dereference][ERROR] {}'.format(uri))
return True
def __dereference_uri(tg, uri):
if not isinstance(uri, URIRef):
return
uri = uri.encode('utf-8')
def treat_resource_content(parse_format):
g = __open_graph(uri, loader=__get_content, format=parse_format)
if isinstance(g, bool):
return g
try:
tg.get_context(uri).__iadd__(g)
return True
finally:
if g is not None:
__release_graph(g)
"""
Load in a tree graph the set of triples contained in uri, trying to not deference the same uri
more than once in the context of a search plan execution
:param tg: The graph to be loaded with all the triples obtained from uri
:param uri: A resource uri to be dereferenced
:return:
"""
loaded = False
for fmt in sorted(_accept_mimes.keys(), key=lambda x: x != self.__last_success_format):
loaded = treat_resource_content(fmt)
if loaded:
self.__last_success_format = fmt
break
if loaded and on_load is not None:
triples = list(tg.get_context(uri).triples((None, None, None)))
on_load(uri, triples)
def __process_link_seed(seed, tree_graph, link, next_seeds):
__check_stop()
try:
__dereference_uri(tree_graph, seed)
seed_pattern_objects = tree_graph.objects(subject=seed, predicate=link)
next_seeds.update(seed_pattern_objects)
except Exception as e:
traceback.print_exc()
log.warning(e.message)
def __process_pattern_link_seed(seed, tree_graph, pattern_link):
__check_stop()
try:
__dereference_uri(tree_graph, seed)
except:
pass
seed_pattern_objects = tree_graph.objects(subject=seed, predicate=pattern_link)
return seed_pattern_objects
def __check_stop():
if stop_event.isSet():
with self.__resource_lock:
self.__fragment.clear()
for tg in self.__resource_queue.keys():
try:
tg.remove((None, None, None))
tg.store.close()
except KeyError:
pass
tg.close()
__release_graph(tg)
self.__plan_graph = None
self.__uri_cache = None
self.__node_spaces = None
self.__node_patterns = None
self.__spaces = None
self.__patterns = None
self.__subjects_to_ignore.clear()
self.__resource_queue.clear()
gc.collect()
raise StopException()
def __put_triple_in_queue(quad):
if (dt.now() - self.__last_iteration_ts).total_seconds() > 100:
log.info('Aborted fragment collection!')
stop_event.set()
fragment_queue.put(quad, timeout=queue_wait)
def __follow_node(node, tree_graph, seed_space, seed):
"""
Recursively search for relevant triples following the current node and all its successors
:param node: Tree node to be followed
:param tree_graph:
:param seed_space:
:param seed: Collected seed for the current node
:return:
"""
def node_has_filter(x):
"""
Check if a node is a pattern node and has an object filter
"""
p_node = list(self.__plan_graph.objects(subject=x, predicate=AGORA.byPattern))
try:
p_node = p_node.pop()
return 'filter_object' in self.__patterns[p_node] or 'filter_subject' in self.__patterns[p_node]
except IndexError:
return False
try:
# Get the sorted list of current node's successors
nxt = sorted(list(self.__plan_graph.objects(node, AGORA.next)),
key=lambda x: node_has_filter(x), reverse=True)
# Per each successor...
for n in nxt:
if seed_space in self.__node_spaces[n]:
node_patterns = self.__node_patterns.get(n, [])
# In case the node is not a leaf, 'onProperty' tells which is the next link to follow
try:
link = list(self.__plan_graph.objects(subject=n, predicate=AGORA.onProperty)).pop()
except IndexError:
link = None
filter_next_seeds = set([])
next_seeds = set([])
# If the current node is a pattern node, it must search for triples to yield
for pattern in node_patterns:
pattern_space = self.__patterns[pattern].get('space', None)
if pattern_space != seed_space or seed in self.__subjects_to_ignore[pattern_space]:
continue
subject_filter = self.__patterns[pattern].get('filter_subject', None)
if subject_filter is not None and seed != subject_filter:
self.__subjects_to_ignore[pattern_space].add(seed)
continue
pattern_link = self.__patterns[pattern].get('property', None)
# If pattern is of type '?s prop O'...
if pattern_link is not None:
if (seed, pattern_link) not in self.__fragment:
obj_filter = self.__patterns[pattern].get('filter_object', None)
if on_plink is not None:
on_plink(pattern_link, [seed], pattern_space)
seed_was_filtered = True
try:
for seed_object in list(
__process_pattern_link_seed(seed, tree_graph, pattern_link)):
__check_stop()
quad = (pattern, seed, pattern_link, seed_object)
if obj_filter is None or u''.join(seed_object).encode(
'utf-8') == u''.join(obj_filter.toPython()).encode('utf-8'):
self.__fragment.add((seed, pattern_link))
__put_triple_in_queue(quad)
seed_was_filtered = False
if isinstance(obj_filter, URIRef):
filter_next_seeds.add(obj_filter)
if obj_filter is not None and seed_was_filtered:
self.__subjects_to_ignore[pattern_space].add(seed)
except AttributeError as e:
log.warning('Trying to find {} objects of {}: {}'.format(link, seed, e.message))
# If pattern is of type '?s a Concept'...
obj_type = self.__patterns[pattern].get('type', None)
if obj_type is not None:
check_type = self.__patterns[pattern].get('check', False)
if on_type is not None:
on_type(obj_type, [seed], pattern_space)
__dereference_uri(tree_graph, seed)
try:
seed_objects = list(tree_graph.objects(subject=seed, predicate=link))
for seed_object in seed_objects:
type_triple = (pattern, seed_object, RDF.type, obj_type)
# In some cases, it is necessary to verify the type of the seed
if (seed_object, obj_type) not in self.__fragment:
if check_type:
__dereference_uri(tree_graph, seed_object)
types = list(
tree_graph.objects(subject=seed_object, predicate=RDF.type))
if obj_type in types:
self.__fragment.add((seed_object, obj_type))
__put_triple_in_queue(type_triple)
else:
self.__subjects_to_ignore[pattern_space].add(seed_object)
else:
self.__fragment.add((seed_object, obj_type))
__put_triple_in_queue(type_triple)
except AttributeError as e:
log.warning('Trying to find {} objects of {}: {}'.format(link, seed, e.message))
# If the current node is not a leaf... go on finding seeds for the successors
if link is not None and seed not in self.__subjects_to_ignore[seed_space]:
if on_link is not None:
on_link(link, [seed], seed_space)
__process_link_seed(seed, tree_graph, link, next_seeds)
if filter_next_seeds:
next_seeds = set.intersection(next_seeds, filter_next_seeds)
chs = list(chunks(list(next_seeds), min(len(next_seeds), max(1, workers / 2))))
next_seeds.clear()
try:
while True:
__check_stop()
chunk = chs.pop()
threads = []
for s in chunk:
try:
workers_queue.put_nowait(s)
future = pool.submit(__follow_node, n, tree_graph, seed_space, s)
threads.append(future)
except Queue.Full:
# If all threads are busy...I'll do it myself
__follow_node(n, tree_graph, seed_space, s)
except Queue.Empty:
pass
wait(threads)
[(workers_queue.get_nowait(), workers_queue.task_done()) for _ in threads]
except (IndexError, KeyError):
pass
except Queue.Full:
stop_event.set()
except Exception as e:
traceback.print_exc()
log.error(e.message)
return
def get_fragment_triples():
"""
Iterate over all search trees and yield relevant triples
:return:
"""
def execute_plan():
for tree in trees:
if on_tree is not None:
on_tree(tree)
# Prepare an dedicated graph for the current tree and a set of type triples (?s a Concept)
# to be evaluated retrospectively
tree_graph = __create_graph()
try:
self.__resource_queue[tree_graph] = []
# Get all seeds of the current tree
seeds = list(self.__plan_graph.objects(tree, AGORA.hasSeed))
if on_seeds is not None:
on_seeds(seeds)
# Check if the tree root is a pattern node and in that case, adds a type triple to the
# respective set
root_pattern = list(self.__plan_graph.objects(tree, AGORA.byPattern))
if len(root_pattern):
pattern_node = list(
self.__plan_graph.objects(subject=tree, predicate=AGORA.byPattern)).pop()
seed_type = self.__patterns[pattern_node].get('type', None)
[type_triples.add((pattern_node, sd, seed_type)) for sd in seeds]
# Get the children of the root node and follow them recursively
nxt = list(self.__plan_graph.objects(tree, AGORA.next))
if len(nxt):
# Prepare the list of seeds to start the exploration with, taking into account all
# search spaces that were defined
s_seeds = set(seeds)
for sp in self.__spaces:
for seed in s_seeds:
__follow_node(tree, tree_graph, sp, seed)
finally:
__release_graph(tree_graph)
if lazy and found_data and len(self.__spaces) == 1:
break
self.__completed = True
def get_tree_length(x):
"""
Return the value of the Agora length property in the given tree node
:param x:
:return:
"""
length = list(self.__plan_graph.objects(subject=x, predicate=AGORA.length)).pop()
return length
# Get all search trees contained in the search plan and sort them by length. A shorter tree is going
# to be explored first.
trees = self.__plan_graph.subjects(RDF.type, AGORA.SearchTree)
trees = sorted(trees, key=lambda x: get_tree_length(x))
type_triples = set([])
thread = Thread(target=execute_plan)
thread.daemon = True
thread.start()
found_data = False
while not self.__completed or fragment_queue.not_empty:
try:
(t, s, p, o) = fragment_queue.get(timeout=1)
found_data = True
fragment_queue.task_done()
if p == RDF.type:
type_triples.add((t, s, o))
else:
yield (t, s, p, o)
except Queue.Empty:
if self.__completed:
break
self.__last_iteration_ts = dt.now()
thread.join()
# All type triples that are of subjects to ignore won't be returned (this has to be done this way
# because of generators nature)
all_ignores = {}
if self.__subjects_to_ignore.values():
all_ignores = set.intersection(*self.__subjects_to_ignore.values())
valid_type_triples = [(t, s, o) for (t, s, o) in type_triples if s not in all_ignores]
for (t, s, o) in valid_type_triples:
if on_type_validation is not None:
on_type_validation((t, s, RDF.type, o))
yield (t, s, RDF.type, o)
return get_fragment_triples(), self.__plan_graph.namespaces(), self.__plan_graph | Agora-Client | /Agora-Client-0.5.0.tar.gz/Agora-Client-0.5.0/agora/client/execution.py | execution.py |
import logging
import random
import time
import traceback
from datetime import datetime as dt
from threading import Thread
from redis.lock import Lock
from agora.stoa.actions.core import AGENT_ID
from agora.stoa.client import get_query_generator
from agora.stoa.daemons.delivery import build_response
from agora.stoa.server import app
from agora.stoa.store import r
from agora.stoa.store.tables import db
from agora.stoa.store.triples import fragments_cache
from concurrent.futures.thread import ThreadPoolExecutor
__author__ = 'Fernando Serena'
log = logging.getLogger('agora.curator.daemons.fragment')
AGORA = app.config['AGORA']
BROKER = app.config['BROKER']
ON_DEMAND_TH = float(app.config.get('PARAMS', {}).get('on_demand_threshold', 2.0))
MIN_SYNC = int(app.config.get('PARAMS', {}).get('min_sync_time', 10))
MAX_CONCURRENT_FRAGMENTS = int(app.config.get('PARAMS', {}).get('max_concurrent_fragments', 8))
fragments_key = '{}:fragments'.format(AGENT_ID)
log.info("""Fragment daemon setup:
- On-demand threshold: {}
- Minimum sync time: {}
- Maximum concurrent fragments: {}""".format(ON_DEMAND_TH, MIN_SYNC,
MAX_CONCURRENT_FRAGMENTS))
thp = ThreadPoolExecutor(max_workers=min(8, MAX_CONCURRENT_FRAGMENTS))
log.info('Cleaning fragment locks...')
fragment_locks = r.keys('{}:*lock*'.format(fragments_key))
for flk in fragment_locks:
r.delete(flk)
log.info('Cleaning fragment pulling flags...')
fragment_pullings = r.keys('{}:*:pulling'.format(fragments_key))
for fpk in fragment_pullings:
r.delete(fpk)
def fragment_lock(fid):
"""
:param fid: Fragment id
:return: A redis-based lock object for a given fragment
"""
lock_key = '{}:{}:lock'.format(fragments_key, fid)
return r.lock(lock_key, lock_class=Lock)
def __notify_completion(sinks):
"""
Notify the ending of a fragment collection to all related requests
:param sinks: Set of dependent sinks
:return:
"""
for sink in sinks.values():
if sink.delivery == 'accepted':
sink.delivery = 'ready'
def __load_fragment_requests(fid):
"""
Load all requests and their sinks that are related to a given fragment id
:param fid: Fragment id
:return: A dictionary of sinks of all fragment requests
"""
sinks_ = {}
fragment_requests_key = '{}:{}:requests'.format(fragments_key, fid)
for rid in r.smembers(fragment_requests_key):
try:
sinks_[rid] = build_response(rid).sink
except Exception, e:
traceback.print_exc()
log.warning(e.message)
with r.pipeline(transaction=True) as p:
p.multi()
p.srem(fragment_requests_key, rid)
p.execute()
return sinks_
def __pull_fragment(fid):
fragment_key = '{}:{}'.format(fragments_key, fid)
tps = r.smembers('{}:gp'.format(fragment_key))
r_sinks = __load_fragment_requests(fid)
log.info("""Starting collection of fragment {}:
- GP: {}
- Supporting: ({}) {}""".format(fid, list(tps), len(r_sinks), list(r_sinks.keys())))
try:
prefixes, gen = get_query_generator(*tps,
broker_host=BROKER['host'],
agora_host=AGORA['host'],
broker_port=BROKER['port'],
agora_port=AGORA['port'], wait=True)
except Exception, e:
traceback.print_exc()
log.error('Scholar is not available')
return
lock = fragment_lock(fid)
lock.acquire()
with r.pipeline(transaction=True) as p:
p.multi()
p.set('{}:pulling'.format(fragment_key), True)
p.execute()
db[fid].delete_many({})
db.drop_collection(fid)
lock.release()
try:
for headers, row in gen:
try:
lock.acquire()
db[fid].insert_one(row)
except Exception, e:
log.warning(e.message)
traceback.print_exc()
finally:
lock.release()
except Exception, e:
log.error(e.message)
lock.acquire()
try:
with r.pipeline(transaction=True) as p:
p.multi()
sync_key = '{}:sync'.format(fragment_key)
# Fragment is now synced
p.set(sync_key, True)
min_durability = int(MIN_SYNC)
durability = random.randint(min_durability, min_durability * 2)
p.expire(sync_key, durability)
log.info('Fragment {} is considered synced for {} s'.format(fid, durability))
p.set('{}:updated'.format(fragment_key), dt.now())
p.delete('{}:pulling'.format(fragment_key))
p.execute()
if r.scard('{}:requests'.format(fragment_key)) != len(r_sinks):
r_sinks = __load_fragment_requests(fid)
__notify_completion(r_sinks)
finally:
lock.release()
def __collect_fragments():
registered_fragments = r.scard(fragments_key)
synced_fragments = len(r.keys('{}:*:sync'.format(fragments_key)))
log.info("""Collector daemon started:
- Fragments: {}
- Synced: {}""".format(registered_fragments, synced_fragments))
futures = {}
while True:
for fid in filter(
lambda x: r.get('{}:{}:sync'.format(fragments_key, x)) is None and r.get(
'{}:{}:pulling'.format(fragments_key, x)) is None,
r.smembers(fragments_key)):
if fid in futures:
if futures[fid].done():
del futures[fid]
if fid not in futures:
futures[fid] = thp.submit(__pull_fragment, fid)
time.sleep(1)
def fragment_updated_on(fid):
return r.get('{}:{}:updated'.format(fragments_key, fid))
def fragment_on_demand(fid):
return r.get('{}:{}:on_demand'.format(fragments_key, fid))
def is_pulling(fid):
return r.get('{}:{}:pulling'.format(fragments_key, fid)) is not None
def is_fragment_synced(fid):
return fragment_updated_on(fid) is not None
def fragment_graph(fid):
return cache.get_context('/' + fid)
th = Thread(target=__collect_fragments)
th.daemon = True
th.start() | Agora-Curator | /Agora-Curator-0.1.2.tar.gz/Agora-Curator-0.1.2/agora/curator/daemons/fragment.py | fragment.py |
import base64
import calendar
import logging
import traceback
import uuid
from datetime import datetime
from agora.curator.daemons.fragment import is_fragment_synced, fragment_lock
from agora.stoa.actions.core import STOA, TYPES, RDF, XSD, FOAF, AGENT_ID
from agora.stoa.actions.core.delivery import LIT_AGENT_ID
from agora.stoa.actions.core.fragment import FragmentRequest, FragmentAction, FragmentResponse, FragmentSink
from agora.stoa.actions.core.utils import CGraph, GraphPattern
from agora.stoa.store import r
from agora.stoa.store.tables import db
from rdflib import BNode, Literal, URIRef
from shortuuid import uuid as suuid
__author__ = 'Fernando Serena'
log = logging.getLogger('agora.curator.actions.enrichment')
enrichments_key = '{}:enrichments'.format(AGENT_ID)
def get_fragment_enrichments(fid):
return [EnrichmentData(eid) for eid in r.smembers('{}:fragments:{}:enrichments'.format(AGENT_ID, fid))]
def generate_enrichment_hash(target, links):
links = '|'.join(sorted([str(pr) for (pr, _) in links]))
eid = base64.b64encode('~'.join([target, links]))
return eid
def register_enrichment(pipe, fid, target, links):
e_hash = generate_enrichment_hash(target, links)
if not r.sismember(enrichments_key, e_hash):
eid = suuid()
enrichment_data = EnrichmentData(eid, fid, target, links)
enrichment_data.save(pipe)
pipe.sadd(enrichments_key, e_hash)
pipe.set('{}:map:enrichments:{}'.format(AGENT_ID, e_hash), eid)
else:
eid = r.get('{}:map:enrichments:{}'.format(AGENT_ID, e_hash))
return eid
class EnrichmentData(object):
def __init__(self, eid, fid=None, target=None, links=None):
if eid is None:
raise ValueError('Cannot create an enrichment data object without an identifier')
self.links = links
if target is not None:
self.target = URIRef(target)
self.target = target
self.fragment_id = fid
self.enrichment_id = eid
self._enrichment_key = '{}:enrichments:{}'.format(AGENT_ID, self.enrichment_id)
if not any([fid, target, links]):
self.load()
def save(self, pipe):
pipe.hset('{}'.format(self._enrichment_key), 'target', self.target)
pipe.hset('{}'.format(self._enrichment_key), 'fragment_id', self.fragment_id)
pipe.sadd('{}:fragments:{}:enrichments'.format(AGENT_ID, self.fragment_id), self.enrichment_id)
pipe.sadd('{}:links'.format(self._enrichment_key), *map(lambda x: str(x), self.links))
pipe.hmset('{}:links:status'.format(self._enrichment_key),
dict((pr, False) for (pr, _) in self.links))
def load(self):
dict_fields = r.hgetall(self._enrichment_key)
self.target = URIRef(dict_fields.get('target', None))
self.fragment_id = dict_fields.get('fragment_id', None)
self.links = map(lambda (link, v): (URIRef(link), v), [eval(pair_str) for pair_str in
r.smembers('{}:links'.format(
self._enrichment_key))])
def set_link(self, link):
with r.pipeline(transaction=True) as p:
p.multi()
p.hset('{}:links:status'.format(self._enrichment_key), str(link), True)
p.execute()
@property
def completed(self):
return all([eval(value) for value in r.hgetall('{}:links:status'.format(self._enrichment_key)).values()])
class EnrichmentRequest(FragmentRequest):
def __init__(self):
super(EnrichmentRequest, self).__init__()
self._target_resource = None
self._target_links = set([])
def _extract_content(self, request_type=STOA.EnrichmentRequest):
super(EnrichmentRequest, self)._extract_content(request_type)
q_res = self._graph.query("""SELECT ?node ?t WHERE {
?node a stoa:EnrichmentRequest;
stoa:targetResource ?t
}""")
q_res = list(q_res)
if len(q_res) != 1:
raise SyntaxError('Invalid enrichment request')
request_fields = q_res.pop()
if not all(request_fields):
raise ValueError('Missing fields for enrichment request')
if request_fields[0] != self._request_node:
raise SyntaxError('Request node does not match')
(self._target_resource,) = request_fields[1:]
log.info("""Parsed attributes of an enrichment request:
-target resource: {}""".format(self._target_resource))
target_pattern = self._graph.predicate_objects(self._target_resource)
for (pr, req_object) in target_pattern:
if (req_object, RDF.type, STOA.Variable) in self._graph:
self._target_links.add((pr, req_object))
enrich_properties = set([pr for (pr, _) in self._target_links])
if not enrich_properties:
raise ValueError('There is nothing to enrich')
log.info(
"""<{}> is requested to be enriched with values for the following properties:
{}""".format(
self._target_resource,
'\n'.join(enrich_properties)))
self._graph_pattern = GraphPattern(filter(lambda x: self._target_resource not in x, self._graph_pattern))
@property
def target_resource(self):
return self._target_resource
@property
def target_links(self):
return self._target_links.copy()
class EnrichmentAction(FragmentAction):
def __init__(self, message):
self.__request = EnrichmentRequest()
self.__sink = EnrichmentSink()
super(EnrichmentAction, self).__init__(message)
@property
def sink(self):
return self.__sink
@classmethod
def response_class(cls):
return EnrichmentResponse
@property
def request(self):
return self.__request
def submit(self):
super(EnrichmentAction, self).submit()
if is_fragment_synced(self.sink.fragment_id):
self.sink.delivery = 'ready'
class EnrichmentSink(FragmentSink):
def _remove(self, pipe):
pipe.srem(enrichments_key, self._request_id)
super(EnrichmentSink, self)._remove(pipe)
def __init__(self):
super(EnrichmentSink, self).__init__()
self.__target_links = None
self.__target_resource = None
self._enrichment_id = None
self._enrichment_data = None
def _save(self, action, general=True):
super(EnrichmentSink, self)._save(action, general)
variable_links = [(str(pr), self.map(action.request.variable_label(v))) for (pr, v) in
action.request.target_links]
enrichment_id = register_enrichment(self._pipe, self.fragment_id, action.request.target_resource,
variable_links)
self._pipe.hset('{}'.format(self._request_key), 'enrichment_id', enrichment_id)
self._dict_fields['enrichment_id'] = enrichment_id
def _load(self):
super(EnrichmentSink, self)._load()
@property
def enrichment_data(self):
if self._enrichment_data is None:
self._enrichment_data = EnrichmentData(self.enrichment_id)
self._enrichment_data.load()
return self._enrichment_data
@property
def backed(self):
return self.fragment_updated_on is not None and EnrichmentData(
self.enrichment_id).completed
class EnrichmentResponse(FragmentResponse):
def __init__(self, rid):
self.__sink = EnrichmentSink()
self.__sink.load(rid)
self.__fragment_lock = fragment_lock(self.__sink.fragment_id)
super(EnrichmentResponse, self).__init__(rid)
@property
def sink(self):
return self.__sink
def build(self):
self.__fragment_lock.acquire()
generator = self._build()
try:
for response in generator:
yield response
except Exception, e:
traceback.print_exc()
log.error(e.message)
finally:
self.__fragment_lock.release()
def _build(self):
log.debug('Building a response for request number {}'.format(self._request_id))
result = self.result_set()
enrichment = self.sink.enrichment_data
object_links = {}
for res in result:
links = dict(map(lambda (l, v): (v.lstrip('?'), l), enrichment.links))
for link in links:
try:
object_link = URIRef(res[link])
if links[link] not in object_links:
object_links[links[link]] = set([])
object_links[links[link]].add(object_link)
except KeyError:
pass
graph = CGraph()
resp_node = BNode('#response')
graph.add((resp_node, RDF.type, STOA.EnrichmentResponse))
graph.add((resp_node, STOA.messageId, Literal(str(uuid.uuid4()), datatype=TYPES.UUID)))
graph.add((resp_node, STOA.responseTo, Literal(self.sink.message_id, datatype=TYPES.UUID)))
graph.add((resp_node, STOA.responseNumber, Literal("1", datatype=XSD.unsignedLong)))
graph.add((resp_node, STOA.targetResource, self.sink.enrichment_data.target))
graph.add((resp_node, STOA.submittedOn, Literal(datetime.now())))
curator_node = BNode('#curator')
graph.add((resp_node, STOA.submittedBy, curator_node))
graph.add((curator_node, RDF.type, FOAF.Agent))
graph.add((curator_node, STOA.agentId, LIT_AGENT_ID))
addition_node = BNode('#addition')
graph.add((resp_node, STOA.additionTarget, addition_node))
graph.add((addition_node, RDF.type, STOA.Variable))
if object_links:
for link, v in self.sink.enrichment_data.links:
[graph.add((addition_node, link, o)) for o in object_links[link]]
yield graph.serialize(format='turtle'), {'state': 'end', 'source': 'store',
'response_to': self.sink.message_id,
'submitted_on': calendar.timegm(datetime.now().timetuple()),
'submitted_by': self.sink.submitted_by,
'format': 'turtle'}
self.sink.delivery = 'sent'
def result_set(self):
pattern = {}
mapping = filter(lambda x: x.startswith('?'), self.sink.mapping)
for v in mapping:
value = self.sink.map(v, fmap=True)
if not value.startswith('?'):
pattern[v.lstrip('?')] = value.strip('"')
table = db[self.sink.fragment_id]
return table.find(pattern) | Agora-Curator | /Agora-Curator-0.1.2.tar.gz/Agora-Curator-0.1.2/agora/curator/actions/enrichment.py | enrichment.py |
import json
import os
from flask import make_response, request, jsonify, render_template, url_for
from flask_negotiate import consumes
import agora.fountain
import agora.fountain.index.core as index
import agora.fountain.index.seeds as seeds
import agora.fountain.vocab.onto as vocs
from agora.fountain.index.paths import calculate_paths, find_path
from agora.fountain.server import app
from agora.fountain.view.graph import view_graph
from agora.fountain.view.path import view_path
from agora.fountain.vocab.schema import prefixes
__author__ = 'Fernando Serena'
with open(os.path.join(agora.fountain.__path__[0], 'metadata.json'), 'r') as stream:
metadata = json.load(stream)
class APIError(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
class NotFound(APIError):
def __init__(self, message, payload=None):
super(NotFound, self).__init__(message, 404, payload)
class Conflict(APIError):
def __init__(self, message, payload=None):
super(Conflict, self).__init__(message, 409, payload)
@app.errorhandler(APIError)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/api')
def get_api():
return jsonify({'meta': metadata,
'vocabularies': url_for('get_vocabularies', _external=True),
'seeds': url_for('get_seeds', _external=True),
'properties': url_for('get_properties', _external=True),
'types': url_for('get_types', _external=True)})
@app.route('/vocabs')
def get_vocabularies():
"""
Return the currently used ontology
:return:
"""
vocabs = vocs.get_vocabularies()
vocabs = [(x, url_for('get_vocabulary', vid=x, _external=True)) for x in vocabs]
response = make_response(json.dumps(dict(vocabs)))
response.headers['Content-Type'] = 'application/json'
return response
@app.route('/vocabs/<vid>')
def get_vocabulary(vid):
"""
Return a concrete vocabulary
:param vid: The identifier of a vocabulary (prefix)
:return:
"""
response = make_response(vocs.get_vocabulary(vid))
response.headers['Content-Type'] = 'text/turtle'
return response
def __analyse_vocabularies(vids):
for vid in reversed(vids):
index.extract_vocabulary(vid)
calculate_paths()
def __check_seeds():
seed_dict = seeds.get_seeds()
types = index.get_types()
obsolete_types = set.difference(set(seed_dict.keys()), set(types))
for t in obsolete_types:
seeds.delete_type_seeds(t)
@app.route('/vocabs', methods=['POST'])
@consumes('text/turtle')
def add_vocabulary():
"""
Add a new vocabulary to the fountain
:return:
"""
try:
vids = vocs.add_vocabulary(request.data)
except vocs.VocabularyNotFound, e:
raise APIError('Ontology URI not found')
except vocs.DuplicateVocabulary, e:
raise Conflict(e.message)
except vocs.VocabularyException, e:
raise APIError(e)
__analyse_vocabularies(vids)
response = make_response()
response.status_code = 201
response.headers['Location'] = url_for('get_vocabulary', vid=vids.pop(0), _external=True)
return response
@app.route('/vocabs/<vid>', methods=['PUT'])
@consumes('text/turtle')
def update_vocabulary(vid):
"""
Updates an already contained vocabulary
:return:
"""
try:
vocs.update_vocabulary(vid, request.data)
except IndexError:
raise APIError('Ontology URI not found')
except vocs.UnknownVocabulary, e:
raise NotFound(e.message)
except Exception, e:
raise APIError(e.message)
__analyse_vocabularies([vid])
__check_seeds()
response = make_response()
response.status_code = 200
return response
@app.route('/vocabs/<vid>', methods=['DELETE'])
def delete_vocabulary(vid):
"""
Delete an existing vocabulary
:return:
"""
try:
vocs.delete_vocabulary(vid)
except IndexError:
raise APIError('Ontology URI not found')
except vocs.UnknownVocabulary, e:
raise NotFound(e.message)
__analyse_vocabularies([vid])
__check_seeds()
response = make_response()
response.status_code = 200
return response
@app.route('/prefixes')
def get_prefixes():
"""
Return the prefixes dictionary of the ontology
:return:
"""
return jsonify(prefixes())
@app.route('/types')
def get_types():
"""
Return the list of supported types (prefixed)
:return:
"""
return jsonify({"types": index.get_types()})
@app.route('/types/<string:t>')
def get_type(t):
"""
Return a concrete type description
:param t: prefixed type e.g. foaf:Person
:return: description of 't'
"""
return jsonify(index.get_type(t))
@app.route('/properties')
def get_properties():
"""
Return the list of supported properties (prefixed)
:return:
"""
return jsonify({"properties": index.get_properties()})
@app.route('/properties/<string:prop>')
def get_property(prop):
"""
Return a concrete property description
:param prop: prefixed property e.g. foaf:name
:return: description of 'prop'
"""
p = index.get_property(prop)
return jsonify(p)
@app.route('/seeds')
def get_seeds():
"""
Return the complete list of seeds available
:return:
"""
return jsonify({"seeds": seeds.get_seeds()})
@app.route('/seeds/<string:ty>')
def get_type_seeds(ty):
"""
Return the list of seeds of a certain type
:param ty: prefixed required type e.g. foaf:Person
:return:
"""
try:
return jsonify({"seeds": seeds.get_type_seeds(ty)})
except seeds.TypeNotAvailableError as e:
raise NotFound(e.message)
@app.route('/seeds', methods=['POST'])
@consumes('application/json')
def add_seed():
"""
Add a new seed of a specific supported type
:return:
"""
data = request.json
try:
sid = seeds.add_seed(data.get('uri', None), data.get('type', None))
response = make_response(sid)
response.headers['Location'] = url_for('get_seed', sid=sid, _external=True)
response.status_code = 201
except (seeds.TypeNotAvailableError, ValueError) as e:
raise APIError(e.message)
except seeds.DuplicateSeedError as e:
raise Conflict(e.message)
return response
@app.route('/seeds/id/<sid>')
def get_seed(sid):
"""
Get the known information about a specific seed by id
:return:
"""
try:
seed = seeds.get_seed(sid)
return jsonify(seed)
except seeds.InvalidSeedError, e:
raise NotFound(e.message)
@app.route('/seeds/id/<sid>', methods=['DELETE'])
def delete_seed(sid):
"""
Delete a specific seed by id
:return:
"""
try:
seeds.delete_seed(sid)
return make_response()
except seeds.InvalidSeedError, e:
raise NotFound(e.message)
@app.route('/paths/<elm>')
@app.route('/paths/<elm>/view')
def get_path(elm):
"""
Return a path to a specific elem (either a property or a type, always prefixed)
:param elm: The required prefixed type/property
:return:
"""
try:
seed_paths, all_cycles = find_path(elm)
if 'view' in request.url_rule.rule:
nodes, edges, roots = view_path(elm, seed_paths)
return render_template('graph-path.html',
nodes=json.dumps(nodes),
edges=json.dumps(edges), roots=json.dumps(roots))
else:
return jsonify({'paths': seed_paths, 'all-cycles': all_cycles})
except seeds.TypeNotAvailableError, e:
raise APIError(e.message)
@app.route('/graph/')
def show_graph():
nodes, edges, roots = view_graph()
return render_template('graph-vocabs.html',
nodes=json.dumps(nodes),
edges=json.dumps(edges), roots=json.dumps(roots)) | Agora-Fountain | /Agora-Fountain-0.5.6.tar.gz/Agora-Fountain-0.5.6/agora/fountain/api.py | api.py |
$(function () { // on dom ready
var cy = cytoscape({
container: document.getElementById('cy'),
style: cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(label)',
'shape': 'data(shape)',
'width': 'mapData(width, 10, 500, 10, 500)',
'height': '40',
'text-valign': 'center',
'background-color': 'white',
'background-opacity': 0.2,
'font-family': 'Monoxil',
'font-size': '16px',
'color': '#484849',
'border-width': 2,
'border-opacity': 0.7,
'font-weight': 'regular',
'shadow-color': '#484849',
'shadow-opacity': 0.5,
'shadow-offset-x': 0,
'shadow-offset-y': 0,
'shadow-blur': 2
})
.selector('edge')
.css({
'target-arrow-shape': 'triangle',
'line-color': '#484849',
'target-arrow-color': '#484849',
'content': 'data(label)',
'color': '#484849',
'edge-text-rotation': 'autorotate',
'text-valign': 'top',
'text-wrap': 'wrap',
'curve-style': 'bezier',
'font-family': 'Monoxil',
'font-size': '14px'
}).selector('edge.subclass')
.css({
'line-style': 'dashed',
'source-arrow-shape': 'triangle',
'source-arrow-fill': 'hollow',
'target-arrow-shape': 'none',
'source-arrow-color': '#484849'
}).selector('node.seed')
.css({
'border-color': '#08f',
'border-width': 5,
'border-opacity': 0.7,
'background-color': '#06a'
}),
elements: {
nodes: vGraph.nodes,
edges: vGraph.edges
}
});
var params = {
name: 'cola',
animate: true, // whether to transition the node positions
// animationDuration: 6000, // duration of animation in ms if enabled
maxSimulationTime: 8000, // max length in ms to run the layout
nodeSpacing: 100, // min spacing between outside of nodes (used for radius adjustment)
edgeLengthVal: 80,
boundingBox: {x1: 0, y1: 0, w: vGraph.nodes.length * 150, h: vGraph.nodes.length * 150},
// boundingBox: undefined, // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
avoidOverlap: false, // prevents node overlap, may overflow boundingBox if not enough space
infinite: false,
fit: false,
randomize: false
};
var layout = makeLayout();
layout.run();
function makeLayout(opts) {
params.randomize = false;
params.edgeLength = function (e) {
return 200;
// return params.edgeLengthVal / e.data('weight');
};
for (var i in opts) {
params[i] = opts[i];
}
return cy.makeLayout(params);
}
cy.bfs = [];
vGraph.roots.forEach(function (r, index) {
cy.bfs.push(
{
index: index,
bfs: cy.elements().bfs('#' + vGraph.roots[index], function () {
}, true)
}
);
});
}); // on dom ready | Agora-Fountain | /Agora-Fountain-0.5.6.tar.gz/Agora-Fountain-0.5.6/agora/fountain/server/static/graph-vocabs.js | graph-vocabs.js |
$(function () { // on dom ready
var cy = cytoscape({
container: document.getElementById('cy'),
style: cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(label)',
'color': '#484849',
'shape': 'data(shape)',
'width': 'mapData(width, 1, 200, 1, 200)',
'height': '40',
'text-valign': 'center',
'background-color': 'white',
'background-opacity': 0.2,
'font-weight': 'regular',
'font-family': 'EagerNaturalist',
'font-size': '22px',
'border-width': 1,
'border-opacity': 0.3,
'shadow-color': '#484849',
'shadow-opacity': 0.3,
'shadow-offset-x': 0,
'shadow-offset-y': 0,
'shadow-blur': 2
})
.selector('edge')
.css({
'target-arrow-shape': 'triangle',
//'width': 3,
'line-color': '#484849',
'target-arrow-color': '#484849',
'content': 'data(label)',
'color': '#484849',
'edge-text-rotation': 'autorotate',
'text-wrap': 'wrap',
'curve-style': 'bezier',
'font-family': 'EagerNaturalist',
'font-size': '18px'
}).selector('edge.highlighted')
.css({
'transition-property': 'line-color, target-arrow-color, color, border-width, shadow-color, visibility',
'transition-duration': '0.8s'
}).selector('node.highlighted')
.css({
'transition-property': 'background-color, line-color, target-arrow-color, color, border-width, shadow-color, visibility',
'transition-duration': '0.8s',
'color': '#484849',
'border-width': 2,
'border-opacity': 0.7,
'font-weight': 'regular',
'shadow-color': '#484849',
'shadow-opacity': 0.5,
'shadow-offset-x': 0,
'shadow-offset-y': 0,
'shadow-blur': 2,
'visibility': 'visible'
}).selector('edge.subclass')
.css({
'line-style': 'dashed',
'source-arrow-shape': 'triangle',
'source-arrow-fill': 'hollow',
'target-arrow-shape': 'none'
}).selector('node.seed')
.css({
'border-color': '#0078B6',
'shadow-color': '#0078B6',
'visibility': 'visible',
'color': '#0078B6'
}).selector('edge.end')
.css({
'line-color': '#1F8A1F',
'color': '#1F8A1F',
'target-arrow-color': '#1F8A1F',
'text-shadow-color': '#1F8A1F',
'text-shadow-opacity': 0.1,
'text-shadow-offset-x': 0,
'text-shadow-offset-y': 0,
'text-shadow-blur': 2
}).selector('node.end')
.css({
'border-color': '#1F8A1F',
'shadow-color': '#1F8A1F',
'color': '#1F8A1F'
}),
elements: {
nodes: vGraph.nodes,
edges: vGraph.edges
}
});
var params = {
name: 'cola',
animate: true, // whether to transition the node positions
maxSimulationTime: 3000, // max length in ms to run the layout
nodeSpacing: 100, // min spacing between outside of nodes (used for radius adjustment)
edgeLengthVal: 80,
boundingBox: undefined, // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
avoidOverlap: true, // prevents node overlap, may overflow boundingBox if not enough space
infinite: false,
fit: true,
randomize: false
};
console.log(vGraph.edges)
var layout = makeLayout();
layout.run();
function makeLayout(opts) {
params.randomize = false;
params.edgeLength = function (e) {
return 200;
};
for (var i in opts) {
params[i] = opts[i];
}
return cy.makeLayout(params);
}
cy.bfs = [];
vGraph.roots.forEach(function (r, index) {
cy.bfs.push(
{
index: index,
bfs: cy.elements().bfs('#' + vGraph.roots[index], function () {
}, true)
}
);
});
var highlightNextEle = function (b) {
b.bfs.path[b.index].addClass('highlighted');
if (b.index < b.bfs.path.length) {
b.index++;
setTimeout(function () {
highlightNextEle(b);
}, 200);
}
};
// kick off first highlights
cy.bfs.forEach(function (b) {
highlightNextEle(b);
});
}); // on dom ready | Agora-Fountain | /Agora-Fountain-0.5.6.tar.gz/Agora-Fountain-0.5.6/agora/fountain/server/static/graph-path.js | graph-path.js |
import logging
from rdflib import ConjunctiveGraph, URIRef, BNode
from rdflib.namespace import RDFS
from agora.fountain.server import app
__author__ = 'Fernando Serena'
log = logging.getLogger('agora.fountain.schema')
store_mode = app.config['STORE']
if 'persist' in store_mode:
graph = ConjunctiveGraph('Sleepycat')
graph.open('graph_store', create=True)
else:
graph = ConjunctiveGraph()
log.info('Loading ontology...'),
graph.store.graph_aware = False
log.debug('\n{}'.format(graph.serialize(format='turtle')))
log.info('Ready')
_namespaces = {}
_prefixes = {}
def __flat_slice(lst):
"""
:param lst:
:return:
"""
lst = list(lst)
for i, _ in enumerate(lst):
while hasattr(lst[i], "__iter__") and not isinstance(lst[i], basestring):
lst[i:i + 1] = lst[i]
return set(filter(lambda x: x is not None, lst))
def __q_name(uri):
"""
:param uri:
:return:
"""
q = uri.n3(graph.namespace_manager)
return q
def __extend_prefixed(pu):
"""
:param pu:
:return:
"""
parts = pu.split(':')
if len(parts) == 1:
parts = ('', parts[0])
try:
return URIRef(_prefixes[parts[0]] + parts[1])
except KeyError:
return BNode(pu)
def prefixes(vid=None):
"""
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
return dict(context.namespaces())
def contexts():
"""
:return:
"""
return [str(x.identifier) for x in graph.contexts()]
def update_context(vid, g):
"""
:param vid:
:param g:
:return:
"""
context = graph.get_context(vid)
graph.remove_context(context)
add_context(vid, g)
def remove_context(vid):
"""
:param vid:
:return:
"""
context = graph.get_context(vid)
graph.remove_context(context)
def get_context(vid):
"""
:param vid:
:return:
"""
return graph.get_context(vid)
def add_context(vid, g):
"""
:param vid:
:param g:
:return:
"""
vid_context = graph.get_context(vid)
for t in g.triples((None, None, None)):
vid_context.add(t)
for (p, u) in g.namespaces():
if p != '':
vid_context.bind(p, u)
_namespaces.update([(uri, prefix) for (prefix, uri) in graph.namespaces()])
_prefixes.update([(prefix, uri) for (prefix, uri) in graph.namespaces()])
def get_types(vid=None):
"""
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
types = set([])
q_class_result = context.query(
"""SELECT DISTINCT ?c ?x WHERE {
{
{?c a owl:Class}
UNION
{?c a rdfs:Class}
FILTER(isURI(?c))
}
UNION
{?c rdfs:subClassOf ?x FILTER(isURI(?x))}
}""")
classes_set = __flat_slice(q_class_result)
types.update([__q_name(c) for c in classes_set])
q_class_result = context.query(
"""SELECT DISTINCT ?r ?d WHERE {
?p a owl:ObjectProperty.
{?p rdfs:range ?r FILTER(isURI(?r)) }
UNION
{?p rdfs:domain ?d}
}""")
classes_set = __flat_slice(q_class_result)
types.update([__q_name(c) for c in classes_set])
types.update([__q_name(x[0]) for x in context.query(
"""SELECT DISTINCT ?c WHERE {
{?r owl:allValuesFrom ?c .
?r owl:onProperty ?p .
{?p a owl:ObjectProperty } UNION { ?c a owl:Class } }
UNION
{?a owl:someValuesFrom ?c .
?a owl:onProperty ?p .
{?p a owl:ObjectProperty} UNION {?c a owl:Class } }
UNION
{?b owl:onClass ?c}
FILTER (isURI(?c))
}""")])
return types
def get_properties(vid=None):
"""
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
properties = set([])
properties.update([__q_name(o or d) for (o, d) in
context.query(
"""SELECT DISTINCT ?o ?d WHERE {
{?d a rdf:Property}
UNION
{?o a owl:ObjectProperty}
UNION
{?d a owl:DatatypeProperty}
UNION
{?r a owl:Restriction . ?r owl:onProperty ?o}
}""")])
return properties
def get_property_domain(prop, vid=None):
"""
:param prop:
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
dom = set([])
domain_set = set([__q_name(c[0]) for c in context.query(
"""SELECT DISTINCT ?c WHERE {
{ %s rdfs:domain ?c }
UNION
{ ?c rdfs:subClassOf [ owl:onProperty %s ] }
FILTER (isURI(?c))
}""" % (prop, prop))])
dom.update(domain_set)
for t in domain_set:
dom.update(get_subtypes(t, vid))
return dom
def is_object_property(prop, vid=None):
"""
:param prop:
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
type_res = context.query("""ASK {%s a owl:ObjectProperty}""" % prop)
object_evidence = [_ for _ in type_res].pop()
if not object_evidence:
object_evidence = [_ for _ in
context.query("""ASK {?r owl:onProperty %s.
{?r owl:onClass ?c} }""" % prop)].pop()
if not object_evidence:
object_evidence = [_ for _ in
context.query("""ASK {?r owl:onProperty %s.
?r owl:someValuesFrom ?c .
{?c a owl:Class} UNION {?c rdfs:subClassOf ?x} }""" % prop)].pop()
if not object_evidence:
object_evidence = [_ for _ in
context.query("""ASK {?r owl:onProperty %s.
?r owl:allValuesFrom ?c .
{?c a owl:Class} UNION {?c rdfs:subClassOf ?x} }""" % prop)].pop()
return object_evidence
def get_property_range(prop, vid=None):
"""
:param prop:
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
rang = set([])
range_set = set([__q_name(r[0]) for r in context.query(
"""SELECT DISTINCT ?r WHERE {
{%s rdfs:range ?r}
UNION
{?d owl:onProperty %s. ?d owl:allValuesFrom ?r. FILTER(isURI(?r))}
UNION
{?d owl:onProperty %s. ?d owl:someValuesFrom ?r. FILTER(isURI(?r))}
UNION
{?d owl:onProperty %s. ?d owl:onClass ?r. FILTER(isURI(?r))}
UNION
{?d owl:onProperty %s. ?d owl:onDataRange ?r. FILTER(isURI(?r))}
}""" % (prop, prop, prop, prop, prop))])
rang.update(range_set)
for y in range_set:
rang.update(get_subtypes(y, vid))
return rang
def get_property_inverses(prop, vid=None):
"""
:param prop:
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
inverses = set([])
inverses.update([__q_name(i[0]) for i in context.query(
"""SELECT ?i WHERE {
{%s owl:inverseOf ?i}
UNION
{?i owl:inverseOf %s}
}""" % (prop, prop))])
return inverses
def get_supertypes(ty, vid=None):
"""
:param ty:
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
res = map(lambda x: __q_name(x), filter(lambda y: isinstance(y, URIRef),
context.transitive_objects(__extend_prefixed(ty), RDFS.subClassOf)))
return set(filter(lambda x: str(x) != ty, res))
def get_subtypes(ty, vid=None):
"""
:param ty:
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
res = map(lambda x: __q_name(x), filter(lambda y: isinstance(y, URIRef),
context.transitive_subjects(RDFS.subClassOf, __extend_prefixed(ty))))
return filter(lambda x: str(x) != ty, res)
def get_type_properties(ty, vid=None):
"""
:param ty:
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
props = set([])
all_types = get_supertypes(ty, vid)
all_types.add(ty)
for sc in all_types:
props.update(
[__q_name(p[0]) for p in context.query(
"""SELECT ?p WHERE {
{%s rdfs:subClassOf [ owl:onProperty ?p ]}
UNION
{?p rdfs:domain %s}
FILTER (isURI(?p))
}""" % (sc, sc))])
return props
def get_type_references(ty, vid=None):
"""
:param ty:
:param vid:
:return:
"""
context = graph
if vid is not None:
context = context.get_context(vid)
refs = set([])
all_types = get_supertypes(ty, vid)
all_types.add(ty)
for sc in all_types:
refs.update(
[__q_name(p[0]) for p in context.query(
"""SELECT ?p WHERE {
{ ?r owl:onProperty ?p.
{?r owl:someValuesFrom %s}
UNION
{?r owl:allValuesFrom %s}
UNION
{?r owl:onClass %s}
}
UNION
{?p rdfs:range %s}
FILTER (isURI(?p))
}""" % (sc, sc, sc, sc))])
return refs | Agora-Fountain | /Agora-Fountain-0.5.6.tar.gz/Agora-Fountain-0.5.6/agora/fountain/vocab/schema.py | schema.py |
import StringIO
import urlparse
from rdflib import Graph, RDF
from rdflib.namespace import OWL
from rdflib.plugins.parsers.notation3 import BadSyntax
import agora.fountain.vocab.schema as sch
__author__ = 'Fernando Serena'
class VocabularyException(Exception):
pass
class DuplicateVocabulary(VocabularyException):
pass
class VocabularyNotFound(VocabularyException):
pass
class UnknownVocabulary(VocabularyException):
pass
def __load_owl(owl):
"""
:param owl:
:return:
"""
owl_g = Graph()
for f in ['turtle', 'xml']:
try:
owl_g.parse(source=StringIO.StringIO(owl), format=f)
break
except SyntaxError:
pass
if not len(owl_g):
raise VocabularyException()
try:
uri = list(owl_g.subjects(RDF.type, OWL.Ontology)).pop()
vid = [p for (p, u) in owl_g.namespaces() if uri in u and p != '']
imports = owl_g.objects(uri, OWL.imports)
if not len(vid):
vid = urlparse.urlparse(uri).path.split('/')[-1]
else:
vid = vid.pop()
return vid, uri, owl_g, imports
except IndexError:
raise VocabularyNotFound()
def add_vocabulary(owl):
"""
:param owl:
:return:
"""
vid, uri, owl_g, imports = __load_owl(owl)
if vid in sch.contexts():
raise DuplicateVocabulary('Vocabulary already contained')
sch.add_context(vid, owl_g)
vids = [vid]
# TODO: Import referenced ontologies
for im_uri in imports:
print im_uri
im_g = Graph()
try:
im_g.load(im_uri, format='turtle')
except BadSyntax:
try:
im_g.load(im_uri)
except BadSyntax:
print 'bad syntax in {}'.format(im_uri)
try:
child_vids = add_vocabulary(im_g.serialize(format='turtle'))
vids.extend(child_vids)
except DuplicateVocabulary, e:
print 'already added'
except VocabularyNotFound, e:
print 'uri not found for {}'.format(im_uri)
except Exception, e:
print e.message
return vids
def update_vocabulary(vid, owl):
"""
:param vid:
:param owl:
:return:
"""
owl_vid, uri, owl_g, imports = __load_owl(owl)
if vid != owl_vid:
raise Exception("Identifiers don't match")
if vid not in sch.contexts():
raise UnknownVocabulary('Vocabulary id is not known')
sch.update_context(vid, owl_g)
def delete_vocabulary(vid):
"""
:param vid:
:return:
"""
if vid not in sch.contexts():
raise UnknownVocabulary('Vocabulary id is not known')
sch.remove_context(vid)
def get_vocabularies():
"""
:return:
"""
return sch.contexts()
def get_vocabulary(vid):
"""
:param vid:
:return:
"""
return sch.get_context(vid).serialize(format='turtle') | Agora-Fountain | /Agora-Fountain-0.5.6.tar.gz/Agora-Fountain-0.5.6/agora/fountain/vocab/onto.py | onto.py |
import base64
import itertools
from agora.fountain.index import core as index
from agora.fountain.index import seeds
from agora.fountain.index.paths import pgraph
__author__ = 'Fernando Serena'
def view_graph():
"""
:return:
"""
types, nodes, edges, roots = [], [], [], []
ibase = 0
nodes_dict = dict([(nid, base64.b16encode(nid)) for nid in pgraph.nodes()])
for (nid, data) in pgraph.nodes(data=True):
if data.get('ty') == 'type':
types.append(nid)
has_seeds = len(seeds.get_type_seeds(nid))
node_d = {'data': {'id': nodes_dict[nid], 'label': nid, 'shape': 'roundrectangle',
'width': len(nid) * 10}}
if has_seeds:
roots.append(nodes_dict[nid])
node_d['classes'] = 'seed'
nodes.append(node_d)
ibase += 1
elif data.get('ty') == 'prop' and data.get('object'):
dom = [t for (t, _) in pgraph.in_edges(nid)]
ran = [t for (_, t) in pgraph.out_edges(nid)]
dom = [d for d in dom if not set.intersection(set(index.get_type(d).get('super')), set(dom))]
ran = [r for r in ran if not set.intersection(set(index.get_type(r).get('super')), set(ran))]
op_edges = list(itertools.product(*[dom, ran]))
edges.extend([{'data': {'id': 'e{}'.format(ibase + i), 'source': nodes_dict[s], 'label': nid + '\n\a',
'target': nodes_dict[tg]}} for i, (s, tg) in enumerate(op_edges)])
ibase += len(op_edges) + 1
else:
ran = data.get('range')
if ran is None:
print nid
if len(ran):
dom = [t for (t, _) in pgraph.in_edges(nid)]
dom = [d for d in dom if not set.intersection(set(index.get_type(d).get('super')), set(dom))]
dp_edges = list(itertools.product(*[dom, ran]))
for i, (s, t) in enumerate(dp_edges):
rid = 'n{}'.format(len(nodes_dict) + len(nodes))
nodes.append({'data': {'id': rid, 'label': t, 'width': len(t) * 10, 'shape': 'ellipse'}})
edges.append(
{'data': {'id': 'e{}'.format(ibase + i), 'source': nodes_dict[s], 'label': nid + '\n\a',
'target': rid}})
ibase += len(dp_edges) + 1
for t in types:
super_types = index.get_type(t).get('super')
super_types = [s for s in super_types if not set.intersection(set(index.get_type(s).get('sub')),
set(super_types))]
st_edges = [{'data': {'id': 'e{}'.format(ibase + i), 'source': nodes_dict[st], 'label': '',
'target': nodes_dict[t]}, 'classes': 'subclass'}
for i, st in enumerate(super_types) if st in nodes_dict]
if len(st_edges):
edges.extend(st_edges)
ibase += len(st_edges) + 1
return nodes, edges, roots | Agora-Fountain | /Agora-Fountain-0.5.6.tar.gz/Agora-Fountain-0.5.6/agora/fountain/view/graph.py | graph.py |
import base64
from agora.fountain.index import core as index
__author__ = 'Fernando Serena'
def view_path(elm, paths):
"""
:param elm:
:param paths:
:return:
"""
nodes, edges, roots, mem_edges = [], [], set([]), set([])
for path in paths:
steps = path['steps']
last_node = None
last_prop = None
for i, step in enumerate(steps):
ty = step['type']
prop = step['property']
node_d = {'data': {'id': base64.b16encode(ty), 'label': ty, 'shape': 'roundrectangle',
'width': max(100, len(ty) * 12)}}
if not i:
roots.add(base64.b16encode(ty))
node_d['classes'] = 'seed'
nodes.append(node_d)
if last_node is not None and (last_node, last_prop, ty) not in mem_edges:
edges.append(
{'data': {'id': 'e{}'.format(len(edges)), 'source': base64.b16encode(last_node),
'label': last_prop + '\n\a',
'target': base64.b16encode(ty)}})
mem_edges.add((last_node, last_prop, ty))
last_node = ty
last_prop = prop
if index.is_type(elm):
nodes.append({'data': {'id': base64.b16encode(elm), 'label': elm, 'shape': 'roundrectangle',
'width': len(elm) * 10}, 'classes': 'end'})
if (last_node, last_prop, elm) not in mem_edges:
edges.append(
{'data': {'id': 'e{}'.format(len(edges)), 'source': base64.b16encode(last_node),
'label': last_prop + '\n\a',
'target': base64.b16encode(elm)}})
mem_edges.add((last_node, last_prop, elm))
else:
prop = index.get_property(elm)
prop_range = prop['range']
prop_range = [d for d in prop_range if not set.intersection(set(index.get_type(d).get('super')),
set(prop_range))]
prop_type = prop['type']
for r in prop_range:
shape = 'roundrectangle'
if prop_type == 'data':
shape = 'ellipse'
nodes.append({'data': {'id': base64.b16encode(r), 'label': r, 'shape': shape,
'width': len(elm) * 10}})
if (last_node, elm, r) not in mem_edges:
edges.append(
{'data': {'id': 'e{}'.format(len(edges)), 'source': base64.b16encode(last_node),
'label': elm + '\n\a',
'target': base64.b16encode(r)}, 'classes': 'end'})
mem_edges.add((last_node, elm, r))
return nodes, edges, list(roots) | Agora-Fountain | /Agora-Fountain-0.5.6.tar.gz/Agora-Fountain-0.5.6/agora/fountain/view/path.py | path.py |
import logging
import multiprocessing
import sys
from datetime import datetime as dt
import redis
from concurrent.futures.thread import ThreadPoolExecutor
from redis.exceptions import RedisError, BusyLoadingError
import agora.fountain.vocab.onto as vocs
import agora.fountain.vocab.schema as sch
from agora.fountain.exceptions import FountainError
from agora.fountain.server import app
__author__ = 'Fernando Serena'
log = logging.getLogger('agora.fountain.index')
redis_conf = app.config['REDIS']
pool = redis.ConnectionPool(host=redis_conf.get('host'), port=redis_conf.get('port'), db=redis_conf.get('db'))
r = redis.StrictRedis(connection_pool=pool)
tpool = ThreadPoolExecutor(multiprocessing.cpu_count())
log.info('Trying to connect to Redis at {}'.format(redis_conf))
# Ping redis to check if it's ready
requests = 0
while True:
log.info('Checking Redis... ({})'.format(requests))
requests += 1
try:
r.keys('*')
break
except BusyLoadingError as re:
log.warning(re.message)
except RedisError:
print 'Redis is not available'
sys.exit(-1)
store_mode = app.config['STORE']
if 'memory' in store_mode:
r.flushdb()
def __get_by_pattern(pattern, func):
"""
:param pattern:
:param func:
:return:
"""
def get_all():
for k in pkeys:
yield func(k)
try:
pkeys = r.keys(pattern)
return list(get_all())
except RedisError as e:
raise FountainError(e.message)
def __remove_from_sets(values, *args):
"""
:param values:
:param args:
:return:
"""
try:
for pattern in args:
keys = r.keys(pattern)
for dk in keys:
key_parts = dk.split(':')
ef_values = values
if len(key_parts) > 1:
ef_values = filter(lambda x: x.split(':')[0] != key_parts[1], values)
if len(ef_values):
r.srem(dk, *ef_values)
except RedisError as e:
raise FountainError(e.message)
def __get_vocab_set(pattern, vid=None):
"""
:param pattern:
:param vid:
:return:
"""
try:
if vid is not None:
pattern = pattern.replace(':*:', ':%s:' % vid)
all_sets = map(lambda x: r.smembers(x), r.keys(pattern))
return list(reduce(set.union, all_sets, set([])))
except RedisError as e:
raise FountainError(e.message)
def __extract_type(t, vid):
"""
:param t:
:param vid:
:return:
"""
log.debug('Extracting type {} from the {} vocabulary...'.format(t, vid))
try:
with r.pipeline() as pipe:
pipe.multi()
pipe.sadd('vocabs:{}:types'.format(vid), t)
for s in sch.get_supertypes(t):
pipe.sadd('vocabs:{}:types:{}:super'.format(vid, t), s)
for s in sch.get_subtypes(t):
pipe.sadd('vocabs:{}:types:{}:sub'.format(vid, t), s)
for s in sch.get_type_properties(t):
pipe.sadd('vocabs:{}:types:{}:props'.format(vid, t), s)
for s in sch.get_type_references(t):
pipe.sadd('vocabs:{}:types:{}:refs'.format(vid, t), s)
pipe.execute()
except RedisError as e:
raise FountainError(e.message)
def __extract_property(p, vid):
"""
:param p:
:param vid:
:return:
"""
def p_type():
if sch.is_object_property(p):
return 'object'
else:
return 'data'
try:
log.debug('Extracting property {} from the {} vocabulary...'.format(p, vid))
with r.pipeline() as pipe:
pipe.multi()
pipe.sadd('vocabs:{}:properties'.format(vid), p)
pipe.hset('vocabs:{}:properties:{}'.format(vid, p), 'uri', p)
for dc in list(sch.get_property_domain(p)):
pipe.sadd('vocabs:{}:properties:{}:_domain'.format(vid, p), dc)
for dc in list(sch.get_property_range(p)):
pipe.sadd('vocabs:{}:properties:{}:_range'.format(vid, p), dc)
for dc in list(sch.get_property_inverses(p)):
pipe.sadd('vocabs:{}:properties:{}:_inverse'.format(vid, p), dc)
pipe.set('vocabs:{}:properties:{}:_type'.format(vid, p), p_type())
pipe.execute()
except RedisError as e:
raise FountainError(e.message)
def __extract_types(vid):
"""
:param vid:
:return:
"""
types = sch.get_types(vid)
other_vocabs = filter(lambda x: x != vid, vocs.get_vocabularies())
dependent_types = set([])
dependent_props = set([])
for ovid in other_vocabs:
o_types = [t for t in get_types(ovid) if t not in types]
for oty in o_types:
otype = get_type(oty)
if set.intersection(types, otype.get('super')) or set.intersection(types, otype.get('sub')):
dependent_types.add((ovid, oty))
o_props = [t for t in get_properties(ovid)]
for op in o_props:
oprop = get_property(op)
if set.intersection(types, oprop.get('domain')) or set.intersection(types, oprop.get('range')):
dependent_props.add((ovid, op))
types = set.union(set([(vid, t) for t in types]), dependent_types)
futures = []
# TODO: Catch exceptions from threadpool
for v, t in types:
futures.append(tpool.submit(__extract_type, t, v))
for v, p in dependent_props:
futures.append(tpool.submit(__extract_property, p, v))
return types, futures
def __extract_properties(vid):
"""
:param vid:
:return:
"""
properties = sch.get_properties(vid)
other_vocabs = filter(lambda x: x != vid, vocs.get_vocabularies())
dependent_types = set([])
for ovid in other_vocabs:
o_types = [t for t in get_types(ovid)]
for oty in o_types:
o_type = get_type(oty)
if set.intersection(properties, o_type.get('refs')) or set.intersection(properties,
o_type.get('properties')):
dependent_types.add((ovid, oty))
futures = []
for p in properties:
futures.append(tpool.submit(__extract_property, p, vid))
for v, ty in dependent_types:
futures.append(tpool.submit(__extract_type, ty, v))
return properties, futures
def delete_vocabulary(vid):
"""
:param vid:
:return:
"""
v_types = get_types(vid)
if len(v_types):
__remove_from_sets(v_types, '*:_domain', '*:_range', '*:sub', '*:super')
v_props = get_properties(vid)
if len(v_props):
__remove_from_sets(v_props, '*:refs', '*:props')
try:
v_keys = r.keys('vocabs:{}:*'.format(vid))
if len(v_keys):
r.delete(*v_keys)
except RedisError as e:
raise FountainError(e.message)
def extract_vocabulary(vid):
"""
:param vid:
:return:
"""
log.info('Extracting vocabulary {}...'.format(vid))
delete_vocabulary(vid)
start_time = dt.now()
types, t_futures = __extract_types(vid)
properties, p_futures = __extract_properties(vid)
for f in t_futures + p_futures:
f.result()
log.info('Done (in {}ms)'.format((dt.now() - start_time).total_seconds() * 1000))
return types, properties
def get_types(vid=None):
"""
:param vid:
:return:
"""
def shared_type(t):
return any(filter(lambda k: r.sismember(k, t), all_type_keys))
vid_types = __get_vocab_set('vocabs:*:types', vid)
if vid is not None:
all_type_keys = filter(lambda k: k != 'vocabs:{}:types'.format(vid), r.keys("vocabs:*:types"))
vid_types = filter(lambda t: not shared_type(t), vid_types)
return vid_types
def get_properties(vid=None):
"""
:param vid:
:return:
"""
def shared_property(t):
return any(filter(lambda k: r.sismember(k, t), all_prop_keys))
vid_props = __get_vocab_set('vocabs:*:properties', vid)
if vid is not None:
all_prop_keys = filter(lambda k: k != 'vocabs:{}:properties'.format(vid), r.keys("vocabs:*:properties"))
vid_props = filter(lambda t: not shared_property(t), vid_props)
return vid_props
def get_property(prop):
"""
:param prop:
:return:
"""
def get_inverse_domain(ip):
return reduce(set.union, __get_by_pattern('*:properties:{}:_domain'.format(ip), r.smembers), set([]))
def get_inverse_range(ip):
return reduce(set.union, __get_by_pattern('*:properties:{}:_range'.format(ip), r.smembers), set([]))
all_prop_keys = r.keys('*:properties')
if not filter(lambda k: r.sismember(k, prop), all_prop_keys):
raise TypeError('Unknown property')
domain = reduce(set.union, __get_by_pattern('*:properties:{}:_domain'.format(prop), r.smembers), set([]))
rang = reduce(set.union, __get_by_pattern('*:properties:{}:_range'.format(prop), r.smembers), set([]))
inv = reduce(set.union, __get_by_pattern('*:properties:{}:_inverse'.format(prop), r.smembers), set([]))
if len(inv):
inverse_dr = [(get_inverse_domain(i), get_inverse_range(i)) for i in inv]
for dom, ra in inverse_dr:
domain.update(ra)
rang.update(dom)
ty = __get_by_pattern('*:properties:{}:_type'.format(prop), r.get)
try:
ty = ty.pop()
except IndexError:
ty = 'object'
return {'domain': list(domain), 'range': list(rang), 'inverse': list(inv), 'type': ty}
def is_property(prop):
"""
:param prop:
:return:
"""
try:
return len(r.keys('*:properties:{}:*'.format(prop)))
except RedisError as e:
raise FountainError(e.message)
def is_type(ty):
"""
:param ty:
:return:
"""
try:
return len(r.keys('*:types:{}:*'.format(ty)))
except RedisError as e:
raise FountainError(e.message)
def get_type(ty):
"""
:param ty:
:return:
"""
try:
all_type_keys = r.keys('*:types')
if not filter(lambda k: r.sismember(k, ty), all_type_keys):
raise TypeError('Unknown type: {}'.format(ty))
super_types = reduce(set.union, __get_by_pattern('*:types:{}:super'.format(ty), r.smembers), set([]))
sub_types = reduce(set.union, __get_by_pattern('*:types:{}:sub'.format(ty), r.smembers), set([]))
type_props = reduce(set.union, __get_by_pattern('*:types:{}:props'.format(ty), r.smembers), set([]))
type_refs = reduce(set.union, __get_by_pattern('*:types:{}:refs'.format(ty), r.smembers), set([]))
return {'super': list(super_types),
'sub': list(sub_types),
'properties': list(type_props),
'refs': list(type_refs)}
except RedisError as e:
raise FountainError(e.message) | Agora-Fountain | /Agora-Fountain-0.5.6.tar.gz/Agora-Fountain-0.5.6/agora/fountain/index/core.py | core.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.