code
stringlengths
9
256k
<s> import urllib <EOL> import urlparse <EOL> import base64 <EOL> import datetime <EOL> import re <EOL> import tornado <EOL> from oauth2u . server import plugins <EOL> from oauth2u . server . handlers . register import register <EOL> import oauth2u . tokens <EOL> from . base import BaseRequestHandler <EOL> __all__ = '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> @ register ( r'<STR_LIT>' ) <EOL> class AuthorizationHandler ( BaseRequestHandler ) : <EOL> '''<STR_LIT>''' <EOL> supported_response_types = [ '<STR_LIT:code>' ] <EOL> def initialize ( self , ** kwargs ) : <EOL> self . code = None <EOL> self . state = None <EOL> self . client_id = None <EOL> self . redirect_uri = None <EOL> def get ( self ) : <EOL> self . load_parameters ( ) <EOL> self . verify_response_type ( ) <EOL> self . create_authorization_token ( ) <EOL> self . save_client_tokens ( ) <EOL> if not plugins . call ( '<STR_LIT>' , self ) : <EOL> self . redirect_access_granted ( self . client_id , self . code ) <EOL> def post ( self ) : <EOL> if not plugins . call ( '<STR_LIT>' , self ) : <EOL> self . raise_http_error ( <NUM_LIT> ) <EOL> def verify_response_type ( self ) : <EOL> value = self . require_argument ( '<STR_LIT>' ) <EOL> if value not in self . supported_response_types : <EOL> error = { <EOL> '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> self . raise_http_invalid_argument_error ( '<STR_LIT>' , error ) <EOL> def load_parameters ( self ) : <EOL> self . state = self . get_argument ( '<STR_LIT:state>' , None ) <EOL> self . redirect_uri = self . require_argument ( '<STR_LIT>' ) <EOL> self . client_id = self . require_argument ( '<STR_LIT>' ) <EOL> if not self . application . database . find_client ( self . client_id ) : <EOL> self . raise_http_401 ( { '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> def raise_http_invalid_argument_error ( self , parameter , error ) : <EOL> if parameter in [ '<STR_LIT>' , '<STR_LIT>' ] : <EOL> self . raise_http_400 ( error ) <EOL> else : <EOL> self . raise_http_302 ( error ) <EOL> def create_authorization_token ( self ) : <EOL> self . code = oauth2u . tokens . generate_authorization_code ( ) <EOL> def redirect_access_granted ( self , client_id , code ) : <EOL> '''<STR_LIT>''' <EOL> params = { '<STR_LIT:code>' : code } <EOL> state = self . application . database . get_state ( client_id , code ) <EOL> if state != None : <EOL> params [ '<STR_LIT:state>' ] = state <EOL> self . redirect_to_redirect_uri_with_params ( params , client_id , code ) <EOL> def redirect_access_denied ( self , client_id , code ) : <EOL> '''<STR_LIT>''' <EOL> params = { <EOL> '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> self . redirect_to_redirect_uri_with_params ( params , client_id , code ) <EOL> def redirect_unauthorized_client ( self , client_id , code ) : <EOL> params = { <EOL> '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> self . redirect_to_redirect_uri_with_params ( params , client_id , code ) <EOL> def redirect_temporarily_unavailable ( self , client_id , code ) : <EOL> params = { <EOL> '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> self . redirect_to_redirect_uri_with_params ( params , client_id , code ) <EOL> def redirect_server_error ( self , client_id , code ) : <EOL> params = { <EOL> '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } <EOL> self . redirect_to_redirect_uri_with_params ( params , client_id , code ) <EOL> def redirect_invalid_scope ( self , client_id , code ) : <EOL> params = { <EOL> '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> self . redirect_to_redirect_uri_with_params ( params , client_id , code ) <EOL> def redirect_to_redirect_uri_with_params ( self , params , client_id , code ) : <EOL> redirect_uri = self . application . database . get_redirect_uri ( client_id , code ) <EOL> url = self . build_redirect_uri ( params , redirect_uri ) <EOL> self . redirect ( url ) <EOL> def build_redirect_uri ( self , params , base_url = None ) : <EOL> return add_query_to_url ( base_url or self . redirect_uri , params ) <EOL> def save_client_tokens ( self ) : <EOL> self . application . database . save_new_authorization_code ( <EOL> self . code , <EOL> self . client_id , <EOL> self . state , <EOL> redirect_uri = self . redirect_uri ) <EOL> @ register ( r'<STR_LIT>' ) <EOL> class AccessTokenHandler ( BaseRequestHandler ) : <EOL> '''<STR_LIT>''' <EOL> required_content_type = "<STR_LIT>" <EOL> def post ( self ) : <EOL> self . validate_headers ( ) <EOL> self . load_arguments ( ) <EOL> self . parse_authorization_header ( ) <EOL> self . validate_client_authorization ( ) <EOL> self . build_response ( ) <EOL> self . mark_client_authorization_code_as_used ( ) <EOL> def validate_headers ( self ) : <EOL> self . require_header ( '<STR_LIT>' , self . required_content_type ) <EOL> self . require_header ( '<STR_LIT>' , startswith = '<STR_LIT>' ) <EOL> def load_arguments ( self ) : <EOL> self . require_argument ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . code = self . require_argument ( '<STR_LIT:code>' ) <EOL> self . redirect_uri = self . require_argument ( '<STR_LIT>' ) <EOL> def parse_authorization_header ( self ) : <EOL> digest = self . request . headers . get ( '<STR_LIT>' ) <EOL> digest = re . sub ( r'<STR_LIT>' , '<STR_LIT>' , digest ) <EOL> try : <EOL> digest = base64 . b64decode ( digest ) <EOL> except TypeError : <EOL> self . raise_http_400 ( { '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> self . client_id , self . code_from_header = digest . split ( '<STR_LIT::>' ) <EOL> def validate_client_authorization ( self ) : <EOL> database = self . application . database <EOL> client = database . find_client ( self . client_id ) <EOL> if not client : <EOL> self . raise_http_401 ( { '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> if not database . client_has_authorization_code ( self . client_id , self . code_from_header ) : <EOL> self . raise_http_401 ( { '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> if not database . client_has_authorization_code ( self . client_id , self . code ) : <EOL> self . raise_http_400 ( { '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> if not database . client_has_redirect_uri_for_code ( self . client_id , self . code , self . redirect_uri ) : <EOL> self . raise_http_400 ( { '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> if database . is_client_authorization_code_used ( self . client_id , self . code ) : <EOL> self . raise_http_400 ( { '<STR_LIT:error>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> plugins . call ( '<STR_LIT>' , self ) <EOL> def mark_client_authorization_code_as_used ( self ) : <EOL> self . application . database . mark_client_authorization_code_as_used ( self . client_id , self . code ) <EOL> def build_response ( self ) : <EOL> response = { <EOL> '<STR_LIT>' : self . build_access_token ( ) , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> plugins . call ( '<STR_LIT>' , self , response ) <EOL> self . write ( response ) <EOL> def build_access_token ( self ) : <EOL> return oauth2u . tokens . generate_access_token ( ) <EOL> def set_default_headers ( self ) : <EOL> self . set_header ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . set_header ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> def add_query_to_url ( url , params ) : <EOL> parts = urlparse . urlparse ( url ) <EOL> query = dict ( urlparse . parse_qsl ( parts . query ) ) <EOL> query . update ( params ) <EOL> return urlparse . urlunparse ( ( parts . scheme , parts . netloc , <EOL> parts . path , parts . params , <EOL> urllib . urlencode ( query ) , <EOL> parts . fragment ) ) </s>
<s> import json <EOL> from unittest import TestCase <EOL> from mock import patch , Mock <EOL> from copy import deepcopy <EOL> from pluct . resource import Resource <EOL> from pluct . schema import Schema <EOL> from pluct . session import Session <EOL> class ResourceRelTestCase ( TestCase ) : <EOL> def setUp ( self ) : <EOL> raw_schema = { <EOL> '<STR_LIT>' : [ <EOL> { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } , <EOL> { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } , <EOL> { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT:POST>' , <EOL> } , <EOL> { <EOL> '<STR_LIT>' : '<STR_LIT:list>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } <EOL> ] <EOL> } <EOL> self . data = { '<STR_LIT:id>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : [ { "<STR_LIT>" : <NUM_LIT:1> } , <EOL> { "<STR_LIT>" : <NUM_LIT:2> } ] } <EOL> self . session = Session ( ) <EOL> self . schema = Schema ( '<STR_LIT>' , raw_schema , session = self . session ) <EOL> self . response = Mock ( ) <EOL> self . response . url = '<STR_LIT>' <EOL> self . profile_url = '<STR_LIT>' <EOL> content_type = '<STR_LIT>' % ( self . profile_url ) <EOL> self . response . headers = { <EOL> '<STR_LIT>' : content_type <EOL> } <EOL> self . resource = Resource . from_data ( <EOL> '<STR_LIT>' , <EOL> data = deepcopy ( self . data ) , schema = self . schema , session = self . session <EOL> ) <EOL> self . resource2 = Resource . from_data ( <EOL> '<STR_LIT>' , <EOL> data = deepcopy ( self . data ) , schema = self . schema , <EOL> session = self . session , response = self . response <EOL> ) <EOL> self . request_patcher = patch . object ( self . session , '<STR_LIT>' ) <EOL> self . request = self . request_patcher . start ( ) <EOL> def tearDown ( self ) : <EOL> self . request_patcher . stop ( ) <EOL> def test_rel_follows_content_type_profile ( self ) : <EOL> self . resource2 . rel ( '<STR_LIT>' , data = self . resource2 ) <EOL> self . request . assert_called_with ( <EOL> '<STR_LIT>' , <EOL> method = '<STR_LIT>' , <EOL> data = json . dumps ( self . data ) , <EOL> headers = self . response . headers <EOL> ) <EOL> def test_get_content_type_for_resource_default ( self ) : <EOL> content_type = self . resource . _get_content_type_for_resource ( <EOL> self . resource ) <EOL> self . assertEqual ( content_type , '<STR_LIT>' ) <EOL> def test_get_content_type_for_resource_with_response ( self ) : <EOL> content_type = self . resource2 . _get_content_type_for_resource ( <EOL> self . resource2 ) <EOL> self . assertEqual ( content_type , self . response . headers [ '<STR_LIT>' ] ) <EOL> def test_expand_uri_returns_simple_link ( self ) : <EOL> uri = self . resource . expand_uri ( '<STR_LIT>' ) <EOL> self . assertEqual ( uri , '<STR_LIT>' ) <EOL> def test_expand_uri_returns_interpolated_link ( self ) : <EOL> uri = self . resource . expand_uri ( '<STR_LIT>' , related = '<STR_LIT:foo>' ) <EOL> self . assertEqual ( uri , '<STR_LIT>' ) <EOL> def test_has_rel_finds_existent_link ( self ) : <EOL> self . assertTrue ( self . resource . has_rel ( '<STR_LIT>' ) ) <EOL> def test_has_rel_detects_unexistent_link ( self ) : <EOL> self . assertFalse ( self . resource . has_rel ( '<STR_LIT>' ) ) <EOL> def test_delegates_request_to_session ( self ) : <EOL> self . resource . rel ( '<STR_LIT>' , data = self . resource ) <EOL> self . request . assert_called_with ( <EOL> '<STR_LIT>' , <EOL> method = '<STR_LIT>' , <EOL> data = json . dumps ( self . data ) , <EOL> headers = { '<STR_LIT>' : '<STR_LIT>' } <EOL> ) <EOL> def test_accepts_extra_parameters ( self ) : <EOL> self . resource . rel ( '<STR_LIT>' , data = self . resource , timeout = <NUM_LIT> ) <EOL> self . request . assert_called_with ( <EOL> '<STR_LIT>' , <EOL> method = '<STR_LIT>' , <EOL> data = json . dumps ( self . data ) , <EOL> headers = { '<STR_LIT>' : '<STR_LIT>' } , <EOL> timeout = <NUM_LIT> <EOL> ) <EOL> def test_accepts_dict ( self ) : <EOL> resource = { '<STR_LIT:name>' : '<STR_LIT>' } <EOL> self . resource . rel ( '<STR_LIT>' , data = resource ) <EOL> self . request . assert_called_with ( <EOL> '<STR_LIT>' , <EOL> method = '<STR_LIT>' , <EOL> data = json . dumps ( resource ) , <EOL> headers = { '<STR_LIT>' : '<STR_LIT:application/json>' } <EOL> ) <EOL> def test_uses_get_as_default_verb ( self ) : <EOL> self . resource . rel ( '<STR_LIT:list>' ) <EOL> self . request . assert_called_with ( <EOL> '<STR_LIT>' , method = '<STR_LIT>' <EOL> ) <EOL> def test_expands_uri_using_resource_data ( self ) : <EOL> self . resource . rel ( '<STR_LIT>' ) <EOL> self . request . assert_called_with ( <EOL> '<STR_LIT>' , method = '<STR_LIT>' <EOL> ) <EOL> def test_expands_uri_using_params ( self ) : <EOL> self . resource . rel ( '<STR_LIT>' , params = { '<STR_LIT:id>' : <NUM_LIT> } ) <EOL> self . request . assert_called_with ( <EOL> '<STR_LIT>' , method = '<STR_LIT>' , params = { } <EOL> ) <EOL> def test_expands_uri_using_resource_data_and_params ( self ) : <EOL> self . resource . rel ( '<STR_LIT>' , params = { '<STR_LIT>' : '<STR_LIT>' } ) <EOL> self . request . assert_called_with ( <EOL> '<STR_LIT>' , method = '<STR_LIT>' , params = { } <EOL> ) <EOL> def test_extracts_expanded_params_from_the_uri ( self ) : <EOL> self . resource . rel ( '<STR_LIT>' , params = { '<STR_LIT:id>' : <NUM_LIT> , '<STR_LIT>' : '<STR_LIT>' } ) <EOL> self . request . assert_called_with ( <EOL> '<STR_LIT>' , <EOL> method = '<STR_LIT>' , params = { '<STR_LIT>' : '<STR_LIT>' } <EOL> ) </s>
<s> import inspect <EOL> from tornado . web import RequestHandler <EOL> from tornado_cors import custom_decorator <EOL> def _get_class_that_defined_method ( meth ) : <EOL> for cls in inspect . getmro ( meth . __self__ . __class__ ) : <EOL> if meth . __name__ in cls . __dict__ : return cls <EOL> return None <EOL> class CorsMixin ( object ) : <EOL> CORS_ORIGIN = None <EOL> CORS_HEADERS = None <EOL> CORS_METHODS = None <EOL> CORS_CREDENTIALS = None <EOL> CORS_MAX_AGE = <NUM_LIT> <EOL> CORS_EXPOSE_HEADERS = None <EOL> def set_default_headers ( self ) : <EOL> if self . CORS_ORIGIN : <EOL> self . set_header ( "<STR_LIT>" , self . CORS_ORIGIN ) <EOL> if self . CORS_EXPOSE_HEADERS : <EOL> self . set_header ( '<STR_LIT>' , self . CORS_EXPOSE_HEADERS ) <EOL> @ custom_decorator . wrapper <EOL> def options ( self , * args , ** kwargs ) : <EOL> if self . CORS_HEADERS : <EOL> self . set_header ( '<STR_LIT>' , self . CORS_HEADERS ) <EOL> if self . CORS_METHODS : <EOL> self . set_header ( '<STR_LIT>' , self . CORS_METHODS ) <EOL> else : <EOL> self . set_header ( '<STR_LIT>' , self . _get_methods ( ) ) <EOL> if self . CORS_CREDENTIALS != None : <EOL> self . set_header ( '<STR_LIT>' , <EOL> "<STR_LIT:true>" if self . CORS_CREDENTIALS else "<STR_LIT:false>" ) <EOL> if self . CORS_MAX_AGE : <EOL> self . set_header ( '<STR_LIT>' , self . CORS_MAX_AGE ) <EOL> if self . CORS_EXPOSE_HEADERS : <EOL> self . set_header ( '<STR_LIT>' , self . CORS_EXPOSE_HEADERS ) <EOL> self . set_status ( <NUM_LIT> ) <EOL> self . finish ( ) <EOL> def _get_methods ( self ) : <EOL> supported_methods = [ method . lower ( ) for method in self . SUPPORTED_METHODS ] <EOL> methods = [ ] <EOL> for meth in supported_methods : <EOL> instance_meth = getattr ( self , meth ) <EOL> if not meth : <EOL> continue <EOL> handler_class = _get_class_that_defined_method ( instance_meth ) <EOL> if not handler_class is RequestHandler : <EOL> methods . append ( meth . upper ( ) ) <EOL> return "<STR_LIT:U+002CU+0020>" . join ( methods ) </s>
<s> from __future__ import absolute_import , division , print_function <EOL> import os <EOL> import sys <EOL> import warnings <EOL> import webbrowser <EOL> from glue . external . qt . QtCore import Qt <EOL> from glue . external . qt import QtGui , QtCore <EOL> from glue . core . application_base import Application <EOL> from glue . core import command , Data <EOL> from glue import env <EOL> from glue . main import load_plugins <EOL> from glue . icons . qt import get_icon <EOL> from glue . external . qt import get_qapp <EOL> from glue . app . qt . actions import action <EOL> from glue . dialogs . data_wizard . qt import data_wizard <EOL> from glue . app . qt . edit_subset_mode_toolbar import EditSubsetModeToolBar <EOL> from glue . app . qt . mdi_area import GlueMdiArea , GlueMdiSubWindow <EOL> from glue . app . qt . layer_tree_widget import PlotAction , LayerTreeWidget <EOL> from glue . app . qt . settings_editor import SettingsEditor <EOL> from glue . viewers . common . qt . mpl_widget import defer_draw <EOL> from glue . viewers . common . qt . data_viewer import DataViewer <EOL> from glue . viewers . image . qt import ImageWidget <EOL> from glue . viewers . scatter . qt import ScatterWidget <EOL> from glue . utils import nonpartial <EOL> from glue . utils . qt import ( pick_class , GlueTabBar , QMessageBoxPatched as <EOL> QMessageBox , set_cursor , messagebox_on_error , load_ui ) <EOL> from glue . app . qt . feedback import submit_bug_report , submit_feedback <EOL> from glue . app . qt . plugin_manager import QtPluginManager <EOL> from glue . app . qt . versions import show_glue_info <EOL> __all__ = [ '<STR_LIT>' ] <EOL> DOCS_URL = '<STR_LIT>' <EOL> def _fix_ipython_pylab ( ) : <EOL> try : <EOL> from IPython import get_ipython <EOL> except ImportError : <EOL> return <EOL> shell = get_ipython ( ) <EOL> if shell is None : <EOL> return <EOL> from IPython . core . error import UsageError <EOL> try : <EOL> shell . enable_pylab ( '<STR_LIT>' , import_all = True ) <EOL> except ValueError : <EOL> pass <EOL> except UsageError : <EOL> pass <EOL> def status_pixmap ( attention = False ) : <EOL> """<STR_LIT>""" <EOL> color = Qt . red if attention else Qt . lightGray <EOL> pm = QtGui . QPixmap ( <NUM_LIT:15> , <NUM_LIT:15> ) <EOL> p = QtGui . QPainter ( pm ) <EOL> b = QtGui . QBrush ( color ) <EOL> p . fillRect ( - <NUM_LIT:1> , - <NUM_LIT:1> , <NUM_LIT:20> , <NUM_LIT:20> , b ) <EOL> return pm <EOL> class ClickableLabel ( QtGui . QLabel ) : <EOL> """<STR_LIT>""" <EOL> clicked = QtCore . Signal ( ) <EOL> def mousePressEvent ( self , event ) : <EOL> self . clicked . emit ( ) <EOL> class GlueLogger ( QtGui . QWidget ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , parent = None ) : <EOL> super ( GlueLogger , self ) . __init__ ( parent ) <EOL> self . _text = QtGui . QTextEdit ( ) <EOL> self . _text . setTextInteractionFlags ( Qt . TextSelectableByMouse ) <EOL> clear = QtGui . QPushButton ( "<STR_LIT>" ) <EOL> clear . clicked . connect ( nonpartial ( self . _clear ) ) <EOL> report = QtGui . QPushButton ( "<STR_LIT>" ) <EOL> report . clicked . connect ( nonpartial ( self . _send_report ) ) <EOL> self . stderr = sys . stderr <EOL> sys . stderr = self <EOL> self . _status = ClickableLabel ( ) <EOL> self . _status . setToolTip ( "<STR_LIT>" ) <EOL> self . _status . clicked . connect ( self . _show ) <EOL> self . _status . setPixmap ( status_pixmap ( ) ) <EOL> self . _status . setContentsMargins ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) <EOL> l = QtGui . QVBoxLayout ( ) <EOL> h = QtGui . QHBoxLayout ( ) <EOL> l . setContentsMargins ( <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:2> ) <EOL> l . setSpacing ( <NUM_LIT:2> ) <EOL> h . setContentsMargins ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) <EOL> l . addWidget ( self . _text ) <EOL> h . insertStretch ( <NUM_LIT:0> ) <EOL> h . addWidget ( report ) <EOL> h . addWidget ( clear ) <EOL> l . addLayout ( h ) <EOL> self . setLayout ( l ) <EOL> @ property <EOL> def status_light ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _status <EOL> def write ( self , message ) : <EOL> """<STR_LIT>""" <EOL> self . stderr . write ( message ) <EOL> self . _text . moveCursor ( QtGui . QTextCursor . End ) <EOL> self . _text . insertPlainText ( message ) <EOL> self . _status . setPixmap ( status_pixmap ( attention = True ) ) <EOL> def flush ( self ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def _send_report ( self ) : <EOL> """<STR_LIT>""" <EOL> text = self . _text . document ( ) . toPlainText ( ) <EOL> submit_bug_report ( text ) <EOL> def _clear ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _text . setText ( '<STR_LIT>' ) <EOL> self . _status . setPixmap ( status_pixmap ( attention = False ) ) <EOL> self . close ( ) <EOL> def _show ( self ) : <EOL> """<STR_LIT>""" <EOL> self . show ( ) <EOL> self . raise_ ( ) <EOL> def keyPressEvent ( self , event ) : <EOL> """<STR_LIT>""" <EOL> if event . key ( ) == Qt . Key_Escape : <EOL> self . hide ( ) <EOL> class GlueApplication ( Application , QtGui . QMainWindow ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , data_collection = None , session = None ) : <EOL> self . app = get_qapp ( ) <EOL> QtGui . QMainWindow . __init__ ( self ) <EOL> Application . __init__ ( self , data_collection = data_collection , <EOL> session = session ) <EOL> self . app . setQuitOnLastWindowClosed ( True ) <EOL> icon = get_icon ( '<STR_LIT>' ) <EOL> self . app . setWindowIcon ( icon ) <EOL> load_plugins ( ) <EOL> self . setWindowTitle ( "<STR_LIT>" ) <EOL> self . setWindowIcon ( icon ) <EOL> self . setAttribute ( Qt . WA_DeleteOnClose ) <EOL> self . _actions = { } <EOL> self . _terminal = None <EOL> self . _setup_ui ( ) <EOL> self . tab_widget . setMovable ( True ) <EOL> self . tab_widget . setTabsClosable ( True ) <EOL> self . _total_tab_count = <NUM_LIT:0> <EOL> lwidget = self . _layer_widget <EOL> a = PlotAction ( lwidget , self ) <EOL> lwidget . ui . layerTree . addAction ( a ) <EOL> lwidget . bind_selection_to_edit_subset ( ) <EOL> self . _tweak_geometry ( ) <EOL> self . _create_actions ( ) <EOL> self . _create_menu ( ) <EOL> self . _connect ( ) <EOL> self . new_tab ( ) <EOL> self . _update_plot_dashboard ( None ) <EOL> self . _load_settings ( ) <EOL> def _setup_ui ( self ) : <EOL> self . _ui = load_ui ( '<STR_LIT>' , None , <EOL> directory = os . path . dirname ( __file__ ) ) <EOL> self . setCentralWidget ( self . _ui ) <EOL> self . _ui . tabWidget . setTabBar ( GlueTabBar ( ) ) <EOL> lw = LayerTreeWidget ( ) <EOL> lw . set_checkable ( False ) <EOL> self . _vb = QtGui . QVBoxLayout ( ) <EOL> self . _vb . setContentsMargins ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) <EOL> self . _vb . addWidget ( lw ) <EOL> self . _ui . data_layers . setLayout ( self . _vb ) <EOL> self . _layer_widget = lw <EOL> self . _log = GlueLogger ( ) <EOL> self . _log . window ( ) . setWindowTitle ( "<STR_LIT>" ) <EOL> self . _log . resize ( <NUM_LIT> , <NUM_LIT> ) <EOL> self . statusBar ( ) . addPermanentWidget ( self . _log . status_light ) <EOL> self . statusBar ( ) . setContentsMargins ( <NUM_LIT:2> , <NUM_LIT:0> , <NUM_LIT:20> , <NUM_LIT:2> ) <EOL> self . statusBar ( ) . setSizeGripEnabled ( False ) <EOL> def _tweak_geometry ( self ) : <EOL> """<STR_LIT>""" <EOL> self . setWindowState ( Qt . WindowMaximized ) <EOL> self . _ui . main_splitter . setSizes ( [ <NUM_LIT:100> , <NUM_LIT> ] ) <EOL> self . _ui . data_plot_splitter . setSizes ( [ <NUM_LIT:100> , <NUM_LIT> , <NUM_LIT> ] ) <EOL> @ property <EOL> def tab_widget ( self ) : <EOL> return self . _ui . tabWidget <EOL> @ property <EOL> def tab_bar ( self ) : <EOL> return self . _ui . tabWidget . tabBar ( ) <EOL> @ property <EOL> def tab_count ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _ui . tabWidget . count ( ) <EOL> @ property <EOL> def current_tab ( self ) : <EOL> return self . _ui . tabWidget . currentWidget ( ) <EOL> def tab ( self , index = None ) : <EOL> if index is None : <EOL> return self . current_tab <EOL> return self . _ui . tabWidget . widget ( index ) <EOL> def new_tab ( self ) : <EOL> """<STR_LIT>""" <EOL> layout = QtGui . QGridLayout ( ) <EOL> layout . setSpacing ( <NUM_LIT:1> ) <EOL> layout . setContentsMargins ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) <EOL> widget = GlueMdiArea ( self ) <EOL> widget . setLayout ( layout ) <EOL> tab = self . tab_widget <EOL> self . _total_tab_count += <NUM_LIT:1> <EOL> tab . addTab ( widget , str ( "<STR_LIT>" % self . _total_tab_count ) ) <EOL> tab . setCurrentWidget ( widget ) <EOL> widget . subWindowActivated . connect ( self . _update_plot_dashboard ) <EOL> def close_tab ( self , index ) : <EOL> """<STR_LIT>""" <EOL> if self . tab_widget . count ( ) == <NUM_LIT:1> : <EOL> return <EOL> if not os . environ . get ( '<STR_LIT>' ) : <EOL> buttons = QMessageBox . Ok | QMessageBox . Cancel <EOL> dialog = QMessageBox . warning ( self , "<STR_LIT>" , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" , <EOL> buttons = buttons , <EOL> defaultButton = QMessageBox . Cancel ) <EOL> if not dialog == QMessageBox . Ok : <EOL> return <EOL> w = self . tab_widget . widget ( index ) <EOL> for window in w . subWindowList ( ) : <EOL> widget = window . widget ( ) <EOL> if isinstance ( widget , DataViewer ) : <EOL> widget . close ( warn = False ) <EOL> w . close ( ) <EOL> self . tab_widget . removeTab ( index ) <EOL> def add_widget ( self , new_widget , label = None , tab = None , <EOL> hold_position = False ) : <EOL> """<STR_LIT>""" <EOL> page = self . tab ( tab ) <EOL> pos = getattr ( new_widget , '<STR_LIT>' , None ) <EOL> sub = new_widget . mdi_wrap ( ) <EOL> sub . closed . connect ( self . _clear_dashboard ) <EOL> if label : <EOL> sub . setWindowTitle ( label ) <EOL> page . addSubWindow ( sub ) <EOL> page . setActiveSubWindow ( sub ) <EOL> if hold_position and pos is not None : <EOL> new_widget . move ( pos [ <NUM_LIT:0> ] , pos [ <NUM_LIT:1> ] ) <EOL> return sub <EOL> def set_setting ( self , key , value ) : <EOL> """<STR_LIT>""" <EOL> super ( GlueApplication , self ) . set_setting ( key , value ) <EOL> settings = QtCore . QSettings ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> settings . setValue ( key , value ) <EOL> def _load_settings ( self , path = None ) : <EOL> settings = QtCore . QSettings ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> for k , v in self . settings : <EOL> if settings . contains ( k ) : <EOL> super ( GlueApplication , self ) . set_setting ( k , settings . value ( k ) ) <EOL> def _edit_settings ( self ) : <EOL> self . _editor = SettingsEditor ( self ) <EOL> self . _editor . widget . show ( ) <EOL> def gather_current_tab ( self ) : <EOL> """<STR_LIT>""" <EOL> self . current_tab . tileSubWindows ( ) <EOL> def _get_plot_dashboards ( self , sub_window ) : <EOL> if not isinstance ( sub_window , GlueMdiSubWindow ) : <EOL> return QtGui . QWidget ( ) , QtGui . QWidget ( ) , "<STR_LIT>" <EOL> widget = sub_window . widget ( ) <EOL> if not isinstance ( widget , DataViewer ) : <EOL> return QtGui . QWidget ( ) , QtGui . QWidget ( ) , "<STR_LIT>" <EOL> layer_view = widget . layer_view ( ) <EOL> options_widget = widget . options_widget ( ) <EOL> return layer_view , options_widget , str ( widget ) <EOL> def _clear_dashboard ( self ) : <EOL> for widget , title in [ ( self . _ui . plot_layers , "<STR_LIT>" ) , <EOL> ( self . _ui . plot_options , "<STR_LIT>" ) ] : <EOL> layout = widget . layout ( ) <EOL> if layout is None : <EOL> layout = QtGui . QVBoxLayout ( ) <EOL> layout . setContentsMargins ( <NUM_LIT:4> , <NUM_LIT:4> , <NUM_LIT:4> , <NUM_LIT:4> ) <EOL> widget . setLayout ( layout ) <EOL> while layout . count ( ) : <EOL> layout . takeAt ( <NUM_LIT:0> ) . widget ( ) . hide ( ) <EOL> widget . setTitle ( title ) <EOL> def _update_plot_dashboard ( self , sub_window ) : <EOL> self . _clear_dashboard ( ) <EOL> if sub_window is None : <EOL> return <EOL> layer_view , options_widget , title = self . _get_plot_dashboards ( sub_window ) <EOL> layout = self . _ui . plot_layers . layout ( ) <EOL> layout . addWidget ( layer_view ) <EOL> layout = self . _ui . plot_options . layout ( ) <EOL> layout . addWidget ( options_widget ) <EOL> layer_view . show ( ) <EOL> options_widget . show ( ) <EOL> if title : <EOL> self . _ui . plot_options . setTitle ( "<STR_LIT>" % title ) <EOL> self . _ui . plot_layers . setTitle ( "<STR_LIT>" % title ) <EOL> else : <EOL> self . _ui . plot_options . setTitle ( "<STR_LIT>" ) <EOL> self . _ui . plot_layers . setTitle ( "<STR_LIT>" ) <EOL> self . _update_focus_decoration ( ) <EOL> def _update_focus_decoration ( self ) : <EOL> mdi_area = self . current_tab <EOL> active = mdi_area . activeSubWindow ( ) <EOL> for win in mdi_area . subWindowList ( ) : <EOL> widget = win . widget ( ) <EOL> if isinstance ( widget , DataViewer ) : <EOL> widget . set_focus ( win is active ) <EOL> def _connect ( self ) : <EOL> self . setAcceptDrops ( True ) <EOL> self . _layer_widget . setup ( self . _data ) <EOL> self . tab_widget . tabCloseRequested . connect ( self . close_tab ) <EOL> def _create_menu ( self ) : <EOL> mbar = self . menuBar ( ) <EOL> menu = QtGui . QMenu ( mbar ) <EOL> menu . setTitle ( "<STR_LIT>" ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> if '<STR_LIT>' in self . _actions : <EOL> submenu = menu . addMenu ( "<STR_LIT>" ) <EOL> for a in self . _actions [ '<STR_LIT>' ] : <EOL> submenu . addAction ( a ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> if '<STR_LIT>' in self . _actions : <EOL> submenu = menu . addMenu ( "<STR_LIT>" ) <EOL> for a in self . _actions [ '<STR_LIT>' ] : <EOL> submenu . addAction ( a ) <EOL> menu . addSeparator ( ) <EOL> menu . addAction ( "<STR_LIT>" , self . _edit_settings ) <EOL> menu . addAction ( "<STR_LIT>" , QtGui . qApp . quit ) <EOL> mbar . addMenu ( menu ) <EOL> menu = QtGui . QMenu ( mbar ) <EOL> menu . setTitle ( "<STR_LIT>" ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> mbar . addMenu ( menu ) <EOL> menu = QtGui . QMenu ( mbar ) <EOL> menu . setTitle ( "<STR_LIT>" ) <EOL> a = QtGui . QAction ( "<STR_LIT>" , menu ) <EOL> a . triggered . connect ( self . _log . _show ) <EOL> menu . addAction ( a ) <EOL> mbar . addMenu ( menu ) <EOL> menu = QtGui . QMenu ( mbar ) <EOL> menu . setTitle ( "<STR_LIT>" ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> menu . addSeparator ( ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> mbar . addMenu ( menu ) <EOL> menu = QtGui . QMenu ( mbar ) <EOL> menu . setTitle ( "<STR_LIT>" ) <EOL> menu . addActions ( self . _layer_widget . actions ( ) ) <EOL> mbar . addMenu ( menu ) <EOL> menu = QtGui . QMenu ( mbar ) <EOL> menu . setTitle ( "<STR_LIT>" ) <EOL> tbar = EditSubsetModeToolBar ( ) <EOL> self . _mode_toolbar = tbar <EOL> self . addToolBar ( tbar ) <EOL> tbar . hide ( ) <EOL> a = QtGui . QAction ( "<STR_LIT>" , menu ) <EOL> a . setCheckable ( True ) <EOL> a . toggled . connect ( tbar . setVisible ) <EOL> try : <EOL> tbar . visibilityChanged . connect ( a . setChecked ) <EOL> except AttributeError : <EOL> pass <EOL> menu . addAction ( a ) <EOL> menu . addActions ( tbar . actions ( ) ) <EOL> mbar . addMenu ( menu ) <EOL> menu = QtGui . QMenu ( mbar ) <EOL> menu . setTitle ( "<STR_LIT>" ) <EOL> menu . addAction ( self . _actions [ '<STR_LIT>' ] ) <EOL> menu . addSeparator ( ) <EOL> if '<STR_LIT>' in self . _actions : <EOL> for plugin in self . _actions [ '<STR_LIT>' ] : <EOL> menu . addAction ( plugin ) <EOL> mbar . addMenu ( menu ) <EOL> menu = mbar . addMenu ( "<STR_LIT>" ) <EOL> a = QtGui . QAction ( "<STR_LIT>" , menu ) <EOL> a . triggered . connect ( nonpartial ( webbrowser . open , DOCS_URL ) ) <EOL> menu . addAction ( a ) <EOL> a = QtGui . QAction ( "<STR_LIT>" , menu ) <EOL> a . triggered . connect ( nonpartial ( submit_feedback ) ) <EOL> menu . addAction ( a ) <EOL> menu . addSeparator ( ) <EOL> menu . addAction ( "<STR_LIT>" , show_glue_info ) <EOL> def _choose_load_data ( self , data_importer = None ) : <EOL> if data_importer is None : <EOL> self . add_datasets ( self . data_collection , data_wizard ( ) ) <EOL> else : <EOL> data = data_importer ( ) <EOL> if not isinstance ( data , list ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> for item in data : <EOL> if not isinstance ( item , Data ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> self . add_datasets ( self . data_collection , data ) <EOL> def _create_actions ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _actions = { } <EOL> a = action ( "<STR_LIT>" , self , <EOL> tip = "<STR_LIT>" , <EOL> shortcut = QtGui . QKeySequence . New <EOL> ) <EOL> a . triggered . connect ( nonpartial ( self . choose_new_data_viewer ) ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> a = action ( '<STR_LIT>' , self , <EOL> shortcut = QtGui . QKeySequence . AddTab , <EOL> tip = '<STR_LIT>' ) <EOL> a . triggered . connect ( nonpartial ( self . new_tab ) ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> a = action ( '<STR_LIT>' , self , <EOL> shortcut = "<STR_LIT>" , <EOL> tip = '<STR_LIT>' ) <EOL> a . triggered . connect ( nonpartial ( self . tab_bar . rename_tab ) ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> a = action ( '<STR_LIT>' , self , <EOL> tip = '<STR_LIT>' , <EOL> shortcut = '<STR_LIT>' ) <EOL> a . triggered . connect ( nonpartial ( self . gather_current_tab ) ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> a = action ( '<STR_LIT>' , self , <EOL> tip = '<STR_LIT>' ) <EOL> a . triggered . connect ( nonpartial ( self . _choose_save_session ) ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> a = action ( "<STR_LIT>" , self , tip = "<STR_LIT>" , <EOL> shortcut = QtGui . QKeySequence . Open ) <EOL> a . triggered . connect ( nonpartial ( self . _choose_load_data , <EOL> data_wizard ) ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> from glue . config import importer <EOL> acts = [ ] <EOL> a = action ( "<STR_LIT>" , self , tip = "<STR_LIT>" ) <EOL> a . triggered . connect ( nonpartial ( self . _choose_load_data , <EOL> data_wizard ) ) <EOL> acts . append ( a ) <EOL> for i in importer : <EOL> label , data_importer = i <EOL> a = action ( label , self , tip = label ) <EOL> a . triggered . connect ( nonpartial ( self . _choose_load_data , <EOL> data_importer ) ) <EOL> acts . append ( a ) <EOL> self . _actions [ '<STR_LIT>' ] = acts <EOL> from glue . config import exporters <EOL> if len ( exporters ) > <NUM_LIT:0> : <EOL> acts = [ ] <EOL> for e in exporters : <EOL> label , saver , checker , mode = e <EOL> a = action ( label , self , <EOL> tip = '<STR_LIT>' % <EOL> label ) <EOL> a . triggered . connect ( nonpartial ( self . _choose_export_session , <EOL> saver , checker , mode ) ) <EOL> acts . append ( a ) <EOL> self . _actions [ '<STR_LIT>' ] = acts <EOL> a = action ( '<STR_LIT>' , self , <EOL> tip = '<STR_LIT>' ) <EOL> a . triggered . connect ( nonpartial ( self . _restore_session ) ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> a = action ( '<STR_LIT>' , self , <EOL> tip = '<STR_LIT>' ) <EOL> a . triggered . connect ( nonpartial ( self . _reset_session ) ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> a = action ( "<STR_LIT>" , self , <EOL> tip = '<STR_LIT>' , <EOL> shortcut = QtGui . QKeySequence . Undo ) <EOL> a . triggered . connect ( nonpartial ( self . undo ) ) <EOL> a . setEnabled ( False ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> a = action ( "<STR_LIT>" , self , <EOL> tip = '<STR_LIT>' , <EOL> shortcut = QtGui . QKeySequence . Redo ) <EOL> a . triggered . connect ( nonpartial ( self . redo ) ) <EOL> a . setEnabled ( False ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> from glue . config import menubar_plugin <EOL> acts = [ ] <EOL> for label , function in menubar_plugin : <EOL> a = action ( label , self , tip = label ) <EOL> a . triggered . connect ( nonpartial ( function , <EOL> self . session , <EOL> self . data_collection ) ) <EOL> acts . append ( a ) <EOL> self . _actions [ '<STR_LIT>' ] = acts <EOL> a = action ( '<STR_LIT>' , self , <EOL> tip = '<STR_LIT>' ) <EOL> a . triggered . connect ( nonpartial ( self . plugin_manager ) ) <EOL> self . _actions [ '<STR_LIT>' ] = a <EOL> def choose_new_data_viewer ( self , data = None ) : <EOL> """<STR_LIT>""" <EOL> from glue . config import qt_client <EOL> if data and data . ndim == <NUM_LIT:1> and ScatterWidget in qt_client . members : <EOL> default = qt_client . members . index ( ScatterWidget ) <EOL> elif data and data . ndim > <NUM_LIT:1> and ImageWidget in qt_client . members : <EOL> default = qt_client . members . index ( ImageWidget ) <EOL> else : <EOL> default = <NUM_LIT:0> <EOL> client = pick_class ( list ( qt_client . members ) , title = '<STR_LIT>' , <EOL> label = "<STR_LIT>" , <EOL> default = default , sort = True ) <EOL> cmd = command . NewDataViewer ( viewer = client , data = data ) <EOL> return self . do ( cmd ) <EOL> new_data_viewer = defer_draw ( Application . new_data_viewer ) <EOL> @ set_cursor ( Qt . WaitCursor ) <EOL> def _choose_save_session ( self ) : <EOL> """<STR_LIT>""" <EOL> outfile , file_filter = QtGui . QFileDialog . getSaveFileName ( self , <EOL> filter = "<STR_LIT>" ) <EOL> if not outfile : <EOL> return <EOL> if not '<STR_LIT:.>' in outfile : <EOL> outfile += '<STR_LIT>' <EOL> self . save_session ( outfile , include_data = "<STR_LIT>" in file_filter ) <EOL> @ messagebox_on_error ( "<STR_LIT>" ) <EOL> def _choose_export_session ( self , saver , checker , outmode ) : <EOL> checker ( self ) <EOL> if outmode in [ '<STR_LIT:file>' , '<STR_LIT>' ] : <EOL> outfile , file_filter = QtGui . QFileDialog . getSaveFileName ( self ) <EOL> if not outfile : <EOL> return <EOL> return saver ( self , outfile ) <EOL> else : <EOL> assert outmode == '<STR_LIT:label>' <EOL> label , ok = QtGui . QInputDialog . getText ( self , '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> if not ok : <EOL> return <EOL> return saver ( self , label ) <EOL> @ messagebox_on_error ( "<STR_LIT>" ) <EOL> @ set_cursor ( Qt . WaitCursor ) <EOL> def _restore_session ( self , show = True ) : <EOL> """<STR_LIT>""" <EOL> fltr = "<STR_LIT>" <EOL> file_name , file_filter = QtGui . QFileDialog . getOpenFileName ( self , <EOL> filter = fltr ) <EOL> if not file_name : <EOL> return <EOL> ga = self . restore_session ( file_name ) <EOL> self . close ( ) <EOL> return ga <EOL> def _reset_session ( self , show = True ) : <EOL> """<STR_LIT>""" <EOL> if not os . environ . get ( '<STR_LIT>' ) : <EOL> buttons = QMessageBox . Ok | QMessageBox . Cancel <EOL> dialog = QMessageBox . warning ( self , "<STR_LIT>" , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" , <EOL> buttons = buttons , <EOL> defaultButton = QMessageBox . Cancel ) <EOL> if not dialog == QMessageBox . Ok : <EOL> return <EOL> ga = GlueApplication ( ) <EOL> ga . show ( ) <EOL> self . close ( ) <EOL> return ga <EOL> @ staticmethod <EOL> def restore_session ( path , show = True ) : <EOL> """<STR_LIT>""" <EOL> ga = Application . restore_session ( path ) <EOL> if show : <EOL> ga . show ( ) <EOL> return ga <EOL> def has_terminal ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _create_terminal ( ) <EOL> return self . _terminal is not None <EOL> def _create_terminal ( self ) : <EOL> if self . _terminal is not None : <EOL> return <EOL> if hasattr ( self , '<STR_LIT>' ) : <EOL> return <EOL> self . _terminal_button = QtGui . QToolButton ( self . _ui ) <EOL> self . _terminal_button . setToolTip ( "<STR_LIT>" ) <EOL> i = get_icon ( '<STR_LIT>' ) <EOL> self . _terminal_button . setIcon ( i ) <EOL> self . _terminal_button . setIconSize ( QtCore . QSize ( <NUM_LIT> , <NUM_LIT> ) ) <EOL> self . _layer_widget . ui . button_row . addWidget ( self . _terminal_button ) <EOL> try : <EOL> from glue . app . qt . terminal import glue_terminal <EOL> widget = glue_terminal ( data_collection = self . _data , <EOL> dc = self . _data , <EOL> hub = self . _hub , <EOL> session = self . session , <EOL> application = self , <EOL> ** vars ( env ) ) <EOL> self . _terminal_button . clicked . connect ( self . _toggle_terminal ) <EOL> except Exception as e : <EOL> import traceback <EOL> self . _terminal_exception = traceback . format_exc ( ) <EOL> self . _setup_terminal_error_dialog ( e ) <EOL> return <EOL> self . _terminal = self . add_widget ( widget , label = '<STR_LIT>' ) <EOL> self . _hide_terminal ( ) <EOL> def _setup_terminal_error_dialog ( self , exception ) : <EOL> """<STR_LIT>""" <EOL> title = "<STR_LIT>" <EOL> msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" % exception ) <EOL> def show_msg ( ) : <EOL> mb = QMessageBox ( QMessageBox . Critical , <EOL> title , msg ) <EOL> mb . setDetailedText ( self . _terminal_exception ) <EOL> mb . exec_ ( ) <EOL> self . _terminal_button . clicked . connect ( show_msg ) <EOL> def _toggle_terminal ( self ) : <EOL> if self . _terminal . isVisible ( ) : <EOL> self . _hide_terminal ( ) <EOL> if self . _terminal . isVisible ( ) : <EOL> warnings . warn ( "<STR_LIT>" ) <EOL> else : <EOL> self . _show_terminal ( ) <EOL> if not self . _terminal . isVisible ( ) : <EOL> warnings . warn ( "<STR_LIT>" ) <EOL> def _hide_terminal ( self ) : <EOL> self . _terminal . hide ( ) <EOL> def _show_terminal ( self ) : <EOL> self . _terminal . show ( ) <EOL> self . _terminal . widget ( ) . show ( ) <EOL> def start ( self , size = None , position = None ) : <EOL> """<STR_LIT>""" <EOL> self . _create_terminal ( ) <EOL> self . show ( ) <EOL> if size is not None : <EOL> self . resize ( * size ) <EOL> if position is not None : <EOL> self . move ( * position ) <EOL> self . raise_ ( ) <EOL> _fix_ipython_pylab ( ) <EOL> return self . app . exec_ ( ) <EOL> exec_ = start <EOL> def keyPressEvent ( self , event ) : <EOL> """<STR_LIT>""" <EOL> mod = event . modifiers ( ) <EOL> if mod == Qt . ShiftModifier : <EOL> self . _mode_toolbar . set_mode ( '<STR_LIT>' ) <EOL> def keyReleaseEvent ( self , event ) : <EOL> """<STR_LIT>""" <EOL> self . _mode_toolbar . unset_mode ( ) <EOL> def dragEnterEvent ( self , event ) : <EOL> if event . mimeData ( ) . hasUrls ( ) : <EOL> event . accept ( ) <EOL> else : <EOL> event . ignore ( ) <EOL> def dropEvent ( self , event ) : <EOL> urls = event . mimeData ( ) . urls ( ) <EOL> for url in urls : <EOL> self . load_data ( url . path ( ) ) <EOL> event . accept ( ) <EOL> def report_error ( self , message , detail ) : <EOL> """<STR_LIT>""" <EOL> qmb = QMessageBox ( QMessageBox . Critical , "<STR_LIT>" , message ) <EOL> qmb . setDetailedText ( detail ) <EOL> qmb . resize ( <NUM_LIT> , qmb . size ( ) . height ( ) ) <EOL> qmb . exec_ ( ) <EOL> def plugin_manager ( self ) : <EOL> from glue . main import _installed_plugins <EOL> pm = QtPluginManager ( installed = _installed_plugins ) <EOL> pm . ui . exec_ ( ) <EOL> def _update_undo_redo_enabled ( self ) : <EOL> undo , redo = self . _cmds . can_undo_redo ( ) <EOL> self . _actions [ '<STR_LIT>' ] . setEnabled ( undo ) <EOL> self . _actions [ '<STR_LIT>' ] . setEnabled ( redo ) <EOL> self . _actions [ '<STR_LIT>' ] . setText ( '<STR_LIT>' + self . _cmds . undo_label ) <EOL> self . _actions [ '<STR_LIT>' ] . setText ( '<STR_LIT>' + self . _cmds . redo_label ) <EOL> @ property <EOL> def viewers ( self ) : <EOL> """<STR_LIT>""" <EOL> result = [ ] <EOL> for t in range ( self . tab_count ) : <EOL> tab = self . tab ( t ) <EOL> item = [ ] <EOL> for subwindow in tab . subWindowList ( ) : <EOL> widget = subwindow . widget ( ) <EOL> if isinstance ( widget , DataViewer ) : <EOL> item . append ( widget ) <EOL> result . append ( tuple ( item ) ) <EOL> return tuple ( result ) <EOL> @ property <EOL> def tab_names ( self ) : <EOL> """<STR_LIT>""" <EOL> return [ self . tab_bar . tabText ( i ) for i in range ( self . tab_count ) ] <EOL> @ staticmethod <EOL> def _choose_merge ( data , others ) : <EOL> w = load_ui ( '<STR_LIT>' , None , directory = os . path . dirname ( __file__ ) ) <EOL> w . show ( ) <EOL> w . raise_ ( ) <EOL> label = others [ <NUM_LIT:0> ] . label if len ( others ) > <NUM_LIT:0> else data . label <EOL> w . merged_label . setText ( label ) <EOL> entries = [ QtGui . QListWidgetItem ( other . label ) for other in others ] <EOL> for e in entries : <EOL> e . setCheckState ( Qt . Checked ) <EOL> for d , item in zip ( others , entries ) : <EOL> w . choices . addItem ( item ) <EOL> if not w . exec_ ( ) : <EOL> return None <EOL> result = [ layer for layer , entry in zip ( others , entries ) <EOL> if entry . checkState ( ) == Qt . Checked ] <EOL> if result : <EOL> result [ <NUM_LIT:0> ] . label = str ( w . merged_label . text ( ) ) <EOL> return result + [ data ] </s>
<s> """<STR_LIT>""" <EOL> from __future__ import absolute_import , division , print_function <EOL> from pandas import Series <EOL> from numpy import ndarray , s_ <EOL> from glue . external . six import string_types <EOL> from glue . config import enable_contracts <EOL> def _build_custom_contracts ( ) : <EOL> """<STR_LIT>""" <EOL> from contracts import new_contract <EOL> @ new_contract <EOL> def cid_like ( value ) : <EOL> """<STR_LIT>""" <EOL> from glue . core import ComponentID <EOL> return isinstance ( value , ( ComponentID , string_types ) ) <EOL> @ new_contract <EOL> def component_like ( value ) : <EOL> from glue . core import Component , ComponentLink <EOL> return isinstance ( value , ( Component , ComponentLink , <EOL> ndarray , list , Series ) ) <EOL> @ new_contract <EOL> def array_like ( value ) : <EOL> return isinstance ( value , ( ndarray , list ) ) <EOL> @ new_contract <EOL> def color ( value ) : <EOL> """<STR_LIT>""" <EOL> from matplotlib . colors import colorConverter <EOL> try : <EOL> colorConverter . to_rgba ( value ) <EOL> except ValueError : <EOL> return False <EOL> @ new_contract <EOL> def inst ( value , * types ) : <EOL> return isinstance ( value , types ) <EOL> @ new_contract <EOL> def data_view ( value ) : <EOL> from glue . core import ComponentID <EOL> if value is None : <EOL> return <EOL> if isinstance ( value , ComponentID ) : <EOL> return <EOL> try : <EOL> if not isinstance ( value [ <NUM_LIT:0> ] , ComponentID ) : <EOL> return False <EOL> s_ [ value [ <NUM_LIT:1> : ] ] <EOL> except : <EOL> return False <EOL> @ new_contract <EOL> def array_view ( value ) : <EOL> try : <EOL> s_ [ value ] <EOL> except : <EOL> return False <EOL> @ new_contract <EOL> def callable ( value ) : <EOL> return hasattr ( value , '<STR_LIT>' ) <EOL> try : <EOL> from contracts import contract , ContractsMeta <EOL> if not enable_contracts ( ) : <EOL> from contracts import disable_all <EOL> disable_all ( ) <EOL> _build_custom_contracts ( ) <EOL> except ImportError : <EOL> def contract ( * args , ** kwargs ) : <EOL> if args : <EOL> return args [ <NUM_LIT:0> ] <EOL> else : <EOL> return lambda func : func <EOL> ContractsMeta = type </s>
<s> """<STR_LIT>""" <EOL> from __future__ import absolute_import , division , print_function <EOL> from collections import Counter <EOL> from glue . external import six <EOL> class Rectangle ( object ) : <EOL> def __init__ ( self , x , y , w , h ) : <EOL> """<STR_LIT>""" <EOL> self . x = x <EOL> self . y = y <EOL> self . w = w <EOL> self . h = h <EOL> def __eq__ ( self , other ) : <EOL> return ( self . x == other . x and <EOL> self . y == other . y and <EOL> self . w == other . w and <EOL> self . h == other . h ) <EOL> if six . PY3 : <EOL> __hash__ = object . __hash__ <EOL> def __str__ ( self ) : <EOL> return repr ( self ) <EOL> def __repr__ ( self ) : <EOL> return "<STR_LIT>" % ( self . x , self . y , self . w , self . h ) <EOL> def snap ( self , xstep , ystep = None , padding = <NUM_LIT:0.0> ) : <EOL> """<STR_LIT>""" <EOL> if ystep is None : <EOL> ystep = xstep <EOL> return Rectangle ( round ( self . x * xstep ) / xstep + padding , <EOL> round ( self . y * ystep ) / ystep + padding , <EOL> round ( self . w * xstep ) / xstep - <NUM_LIT:2> * padding , <EOL> round ( self . h * ystep ) / ystep - <NUM_LIT:2> * padding ) <EOL> def _snap_size ( rectangles ) : <EOL> x = Counter ( [ round ( <NUM_LIT:1> / r . w ) for r in rectangles ] ) <EOL> y = Counter ( [ round ( <NUM_LIT:1> / r . h ) for r in rectangles ] ) <EOL> return x . most_common ( ) [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , y . most_common ( ) [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> def snap_to_grid ( rectangles , padding = <NUM_LIT:0.0> ) : <EOL> """<STR_LIT>""" <EOL> result = { } <EOL> xs , ys = _snap_size ( rectangles ) <EOL> for r in rectangles : <EOL> result [ r ] = r . snap ( xs , ys , padding = padding ) <EOL> return result </s>
<s> """<STR_LIT>""" <EOL> from __future__ import absolute_import , division , print_function <EOL> from warnings import warn <EOL> from glue . external import six <EOL> from glue . core . contracts import contract <EOL> from glue . core . message import ( DataCollectionAddMessage , <EOL> DataCollectionDeleteMessage ) <EOL> from glue . core . visual import VisualAttributes <EOL> from glue . core . hub import HubListener <EOL> from glue . utils import Pointer <EOL> from glue . core . subset import SubsetState <EOL> from glue . core import Subset <EOL> from glue . config import settings <EOL> __all__ = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> class GroupedSubset ( Subset ) : <EOL> """<STR_LIT>""" <EOL> subset_state = Pointer ( '<STR_LIT>' ) <EOL> label = Pointer ( '<STR_LIT>' ) <EOL> def __init__ ( self , data , group ) : <EOL> """<STR_LIT>""" <EOL> self . group = group <EOL> super ( GroupedSubset , self ) . __init__ ( data , label = group . label , <EOL> color = group . style . color , <EOL> alpha = group . style . alpha ) <EOL> def _setup ( self , color , alpha , label ) : <EOL> self . color = color <EOL> self . label = label <EOL> self . style = VisualAttributes ( parent = self ) <EOL> self . style . markersize *= <NUM_LIT> <EOL> self . style . color = color <EOL> self . style . alpha = alpha <EOL> @ property <EOL> def verbose_label ( self ) : <EOL> return "<STR_LIT>" % ( self . label , self . data . label ) <EOL> def sync_style ( self , other ) : <EOL> self . style . set ( other ) <EOL> def __eq__ ( self , other ) : <EOL> return other is self <EOL> if six . PY3 : <EOL> __hash__ = object . __hash__ <EOL> def __gluestate__ ( self , context ) : <EOL> return dict ( group = context . id ( self . group ) , <EOL> style = context . do ( self . style ) ) <EOL> @ classmethod <EOL> def __setgluestate__ ( cls , rec , context ) : <EOL> dummy_grp = SubsetGroup ( ) <EOL> self = cls ( None , dummy_grp ) <EOL> yield self <EOL> self . group = context . object ( rec [ '<STR_LIT>' ] ) <EOL> self . style = context . object ( rec [ '<STR_LIT>' ] ) <EOL> class SubsetGroup ( HubListener ) : <EOL> def __init__ ( self , color = settings . SUBSET_COLORS [ <NUM_LIT:0> ] , alpha = <NUM_LIT:0.5> , label = None , subset_state = None ) : <EOL> """<STR_LIT>""" <EOL> self . subsets = [ ] <EOL> if subset_state is None : <EOL> subset_state = SubsetState ( ) <EOL> self . subset_state = subset_state <EOL> self . label = label <EOL> self . _style = None <EOL> self . style = VisualAttributes ( parent = self ) <EOL> self . style . markersize *= <NUM_LIT> <EOL> self . style . color = color <EOL> self . style . alpha = alpha <EOL> @ contract ( data = '<STR_LIT>' ) <EOL> def register ( self , data ) : <EOL> """<STR_LIT>""" <EOL> self . register_to_hub ( data . hub ) <EOL> for d in data : <EOL> s = GroupedSubset ( d , self ) <EOL> self . subsets . append ( s ) <EOL> for d , s in zip ( data , self . subsets ) : <EOL> d . add_subset ( s ) <EOL> def paste ( self , other_subset ) : <EOL> """<STR_LIT>""" <EOL> state = other_subset . subset_state . copy ( ) <EOL> self . subset_state = state <EOL> def _add_data ( self , data ) : <EOL> s = GroupedSubset ( data , self ) <EOL> data . add_subset ( s ) <EOL> self . subsets . append ( s ) <EOL> def _remove_data ( self , data ) : <EOL> for s in list ( self . subsets ) : <EOL> if s . data is data : <EOL> self . subsets . remove ( s ) <EOL> def register_to_hub ( self , hub ) : <EOL> hub . subscribe ( self , DataCollectionAddMessage , <EOL> lambda x : self . _add_data ( x . data ) ) <EOL> hub . subscribe ( self , DataCollectionDeleteMessage , <EOL> lambda x : self . _remove_data ( x . data ) ) <EOL> @ property <EOL> def style ( self ) : <EOL> return self . _style <EOL> @ style . setter <EOL> def style ( self , value ) : <EOL> self . _style = value <EOL> self . _sync_style ( ) <EOL> def _sync_style ( self ) : <EOL> for s in self . subsets : <EOL> s . sync_style ( self . style ) <EOL> @ contract ( item = '<STR_LIT:string>' ) <EOL> def broadcast ( self , item ) : <EOL> if item == '<STR_LIT>' : <EOL> self . _sync_style ( ) <EOL> return <EOL> for s in self . subsets : <EOL> s . broadcast ( item ) <EOL> def __setattr__ ( self , attr , value ) : <EOL> object . __setattr__ ( self , attr , value ) <EOL> if attr in [ '<STR_LIT>' , '<STR_LIT:label>' , '<STR_LIT>' ] : <EOL> self . broadcast ( attr ) <EOL> def __gluestate__ ( self , context ) : <EOL> return dict ( label = self . label , <EOL> state = context . id ( self . subset_state ) , <EOL> style = context . do ( self . style ) , <EOL> subsets = list ( map ( context . id , self . subsets ) ) ) <EOL> @ classmethod <EOL> def __setgluestate__ ( cls , rec , context ) : <EOL> result = cls ( ) <EOL> yield result <EOL> result . subset_state = context . object ( rec [ '<STR_LIT:state>' ] ) <EOL> result . label = rec [ '<STR_LIT:label>' ] <EOL> result . style = context . object ( rec [ '<STR_LIT>' ] ) <EOL> result . style . parent = result <EOL> result . subsets = list ( map ( context . object , rec [ '<STR_LIT>' ] ) ) <EOL> def __and__ ( self , other ) : <EOL> return self . subset_state & other . subset_state <EOL> def __or__ ( self , other ) : <EOL> return self . subset_state | other . subset_state <EOL> def __xor__ ( self , other ) : <EOL> return self . subset_state ^ other . subset_state <EOL> def __invert__ ( self ) : <EOL> return ~ self . subset_state <EOL> def coerce_subset_groups ( collect ) : <EOL> """<STR_LIT>""" <EOL> for data in collect : <EOL> for subset in data . subsets : <EOL> if not isinstance ( subset , GroupedSubset ) : <EOL> warn ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> subset . delete ( ) <EOL> grp = collect . new_subset_group ( ) <EOL> grp . subset_state = subset . subset_state <EOL> grp . style = subset . style <EOL> grp . label = subset . label </s>
<s> from __future__ import absolute_import , division , print_function <EOL> import json <EOL> from io import BytesIO <EOL> import pytest <EOL> import numpy as np <EOL> from glue . external import six <EOL> from glue import core <EOL> from glue . tests . helpers import requires_astropy , make_file <EOL> from . . data_factories import load_data <EOL> from . . data_factories . tests . test_fits import TEST_FITS_DATA <EOL> from . . state import ( GlueSerializer , GlueUnSerializer , <EOL> saver , loader , VersionedDict ) <EOL> def clone ( object , include_data = False ) : <EOL> gs = GlueSerializer ( object , include_data = include_data ) <EOL> oid = gs . id ( object ) <EOL> dump = gs . dumps ( ) <EOL> gu = GlueUnSerializer . loads ( dump ) <EOL> result = gu . object ( oid ) <EOL> return result <EOL> def doubler ( x ) : <EOL> return <NUM_LIT:2> * x <EOL> def containers_equal ( c1 , c2 ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( c1 , six . string_types ) : <EOL> return c1 == c2 <EOL> try : <EOL> for a , b in zip ( c1 , c2 ) : <EOL> if not containers_equal ( a , b ) : <EOL> return False <EOL> if isinstance ( c1 , dict ) and isinstance ( c2 , dict ) : <EOL> if not containers_equal ( c1 [ a ] , c2 [ b ] ) : <EOL> return False <EOL> except TypeError : <EOL> pass <EOL> return True <EOL> class Cloner ( object ) : <EOL> def __init__ ( self , obj ) : <EOL> self . s = GlueSerializer ( obj ) <EOL> self . us = GlueUnSerializer . loads ( self . s . dumps ( ) ) <EOL> def get ( self , o ) : <EOL> return self . us . object ( self . s . id ( o ) ) <EOL> class Circular ( object ) : <EOL> def __gluestate__ ( self , context ) : <EOL> return dict ( other = context . id ( self . other ) ) <EOL> @ classmethod <EOL> def __setgluestate__ ( cls , rec , context ) : <EOL> result = cls ( ) <EOL> yield result <EOL> result . other = context . object ( rec [ '<STR_LIT>' ] ) <EOL> def test_generator_loaders ( ) : <EOL> f = Circular ( ) <EOL> b = Circular ( ) <EOL> f . other = b <EOL> b . other = f <EOL> f2 = clone ( f ) <EOL> assert f2 . other . other is f2 <EOL> def test_none ( ) : <EOL> assert clone ( None ) is None <EOL> def test_data ( ) : <EOL> d = core . Data ( x = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] , label = '<STR_LIT>' ) <EOL> d2 = clone ( d ) <EOL> assert d2 . label == '<STR_LIT>' <EOL> np . testing . assert_array_equal ( d2 [ '<STR_LIT:x>' ] , [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] ) <EOL> np . testing . assert_array_equal ( d2 [ '<STR_LIT>' ] , [ <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:2> ] ) <EOL> def test_data_style ( ) : <EOL> d = core . Data ( x = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] ) <EOL> d . style . color = '<STR_LIT>' <EOL> d2 = clone ( d ) <EOL> assert d2 . style . color == '<STR_LIT>' <EOL> @ requires_astropy <EOL> def test_data_factory ( ) : <EOL> with make_file ( TEST_FITS_DATA , '<STR_LIT>' , decompress = True ) as infile : <EOL> d = load_data ( infile ) <EOL> d2 = clone ( d ) <EOL> np . testing . assert_array_equal ( d [ '<STR_LIT>' ] , d2 [ '<STR_LIT>' ] ) <EOL> @ requires_astropy <EOL> def test_data_factory_include_data ( ) : <EOL> with make_file ( TEST_FITS_DATA , '<STR_LIT>' , decompress = True ) as infile : <EOL> d = load_data ( infile ) <EOL> d2 = clone ( d , include_data = True ) <EOL> np . testing . assert_array_equal ( d [ '<STR_LIT>' ] , d2 [ '<STR_LIT>' ] ) <EOL> def test_save_numpy_scalar ( ) : <EOL> assert clone ( np . float32 ( <NUM_LIT:5> ) ) == <NUM_LIT:5> <EOL> @ requires_astropy <EOL> def tests_data_factory_double ( ) : <EOL> from astropy . io import fits <EOL> d = np . random . normal ( <NUM_LIT:0> , <NUM_LIT:1> , ( <NUM_LIT:100> , <NUM_LIT:100> , <NUM_LIT:100> ) ) <EOL> s = BytesIO ( ) <EOL> fits . writeto ( s , d ) <EOL> with make_file ( s . getvalue ( ) , '<STR_LIT>' ) as infile : <EOL> d = load_data ( infile ) <EOL> d2 = clone ( d ) <EOL> assert len ( GlueSerializer ( d ) . dumps ( ) ) < <NUM_LIT> * len ( GlueSerializer ( d2 ) . dumps ( ) ) <EOL> def test_inequality_subset ( ) : <EOL> d = core . Data ( x = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] , label = '<STR_LIT>' ) <EOL> s = d . new_subset ( label = '<STR_LIT:abc>' ) <EOL> s . subset_state = d . id [ '<STR_LIT:x>' ] > <NUM_LIT:1> <EOL> d2 = clone ( d ) <EOL> s2 = d2 . subsets [ <NUM_LIT:0> ] <EOL> assert s . label == s2 . label <EOL> np . testing . assert_array_equal ( s2 . to_mask ( ) , [ False , True , True ] ) <EOL> assert s . style == s2 . style <EOL> def test_compound_state ( ) : <EOL> d = core . Data ( x = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] ) <EOL> s = d . new_subset ( label = '<STR_LIT:abc>' ) <EOL> s . subset_state = ( d . id [ '<STR_LIT:x>' ] > <NUM_LIT:2> ) | ( d . id [ '<STR_LIT:x>' ] < <NUM_LIT> ) <EOL> d2 = clone ( d ) <EOL> np . testing . assert_array_equal ( d2 . subsets [ <NUM_LIT:0> ] . to_mask ( ) , [ True , False , True ] ) <EOL> def test_empty_subset ( ) : <EOL> d = core . Data ( x = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] , label = '<STR_LIT>' ) <EOL> s = d . new_subset ( label = '<STR_LIT:abc>' ) <EOL> s . style . color = '<STR_LIT>' <EOL> s2 = clone ( s ) <EOL> assert s . style == s2 . style <EOL> assert s2 . style . color == '<STR_LIT>' <EOL> def test_box_roi_subset ( ) : <EOL> d = core . Data ( x = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] , y = [ <NUM_LIT:2> , <NUM_LIT:4> , <NUM_LIT:8> ] ) <EOL> s = d . new_subset ( label = '<STR_LIT>' ) <EOL> roi = core . roi . RectangularROI ( xmin = <NUM_LIT> , xmax = <NUM_LIT> , ymin = <NUM_LIT> , ymax = <NUM_LIT> ) <EOL> s . subset_state = core . subset . RoiSubsetState ( xatt = d . id [ '<STR_LIT:x>' ] , <EOL> yatt = d . id [ '<STR_LIT:y>' ] , roi = roi ) <EOL> d2 = clone ( d ) <EOL> np . testing . assert_array_equal ( <EOL> d2 . subsets [ <NUM_LIT:0> ] . to_mask ( ) , [ False , True , False ] ) <EOL> def test_range_subset ( ) : <EOL> d = core . Data ( x = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] ) <EOL> s = d . new_subset ( label = '<STR_LIT>' ) <EOL> s . subset_state = core . subset . RangeSubsetState ( <NUM_LIT:0.5> , <NUM_LIT> , att = d . id [ '<STR_LIT:x>' ] ) <EOL> d2 = clone ( d ) <EOL> np . testing . assert_array_equal ( <EOL> d2 . subsets [ <NUM_LIT:0> ] . to_mask ( ) , [ True , True , False ] ) <EOL> def test_complex_state ( ) : <EOL> d = core . Data ( x = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] , y = [ <NUM_LIT:2> , <NUM_LIT:4> , <NUM_LIT:8> ] ) <EOL> s = d . new_subset ( label = '<STR_LIT:test>' ) <EOL> s . subset_state = ( d . id [ '<STR_LIT:x>' ] > <NUM_LIT:2> ) | ( d . id [ '<STR_LIT:y>' ] < <NUM_LIT:4> ) <EOL> s . subset_state = s . subset_state & ( d . id [ '<STR_LIT:x>' ] < <NUM_LIT:4> ) <EOL> d2 = clone ( d ) <EOL> s2 = d2 . subsets [ <NUM_LIT:0> ] <EOL> np . testing . assert_array_equal ( s2 . to_mask ( ) , [ True , False , True ] ) <EOL> def test_range_roi ( ) : <EOL> roi = core . roi . RangeROI ( '<STR_LIT:x>' , min = <NUM_LIT:1> , max = <NUM_LIT:2> ) <EOL> r2 = clone ( roi ) <EOL> assert r2 . ori == '<STR_LIT:x>' <EOL> assert r2 . min == <NUM_LIT:1> <EOL> assert r2 . max == <NUM_LIT:2> <EOL> def test_circular_roi ( ) : <EOL> roi = core . roi . CircularROI ( xc = <NUM_LIT:0> , yc = <NUM_LIT:1> , radius = <NUM_LIT:2> ) <EOL> r2 = clone ( roi ) <EOL> assert r2 . xc == <NUM_LIT:0> <EOL> assert r2 . yc == <NUM_LIT:1> <EOL> assert r2 . radius == <NUM_LIT:2> <EOL> def test_polygonal_roi ( ) : <EOL> roi = core . roi . PolygonalROI ( ) <EOL> roi . add_point ( <NUM_LIT:0> , <NUM_LIT:0> ) <EOL> roi . add_point ( <NUM_LIT:0> , <NUM_LIT:1> ) <EOL> roi . add_point ( <NUM_LIT:1> , <NUM_LIT:0> ) <EOL> r2 = clone ( roi ) <EOL> assert r2 . vx == [ <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:1> ] <EOL> assert r2 . vy == [ <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:0> ] <EOL> class DummyClass ( object ) : <EOL> pass <EOL> class TestVersioning ( object ) : <EOL> def setup_method ( self , method ) : <EOL> @ saver ( DummyClass , version = <NUM_LIT:1> ) <EOL> def s ( d , context ) : <EOL> return dict ( v = <NUM_LIT:3> ) <EOL> @ loader ( DummyClass , version = <NUM_LIT:1> ) <EOL> def l ( d , context ) : <EOL> return <NUM_LIT:3> <EOL> @ saver ( DummyClass , version = <NUM_LIT:2> ) <EOL> def s ( d , context ) : <EOL> return dict ( v = <NUM_LIT:4> ) <EOL> @ loader ( DummyClass , version = <NUM_LIT:2> ) <EOL> def l ( rec , context ) : <EOL> return <NUM_LIT:4> <EOL> def teardown_method ( self , method ) : <EOL> GlueSerializer . dispatch . _data [ DummyClass ] . pop ( <NUM_LIT:1> ) <EOL> GlueSerializer . dispatch . _data [ DummyClass ] . pop ( <NUM_LIT:2> ) <EOL> GlueUnSerializer . dispatch . _data [ DummyClass ] . pop ( <NUM_LIT:1> ) <EOL> GlueUnSerializer . dispatch . _data [ DummyClass ] . pop ( <NUM_LIT:2> ) <EOL> def test_default_latest_save ( self ) : <EOL> assert list ( GlueSerializer ( DummyClass ( ) ) . dumpo ( ) . values ( ) ) [ <NUM_LIT:0> ] [ '<STR_LIT:v>' ] == <NUM_LIT:4> <EOL> assert list ( GlueSerializer ( DummyClass ( ) ) . dumpo ( ) . values ( ) ) [ <NUM_LIT:0> ] [ '<STR_LIT>' ] == <NUM_LIT:2> <EOL> def test_legacy_load ( self ) : <EOL> data = json . dumps ( { '<STR_LIT>' : { '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : <NUM_LIT:1> , '<STR_LIT:v>' : <NUM_LIT:2> } } ) <EOL> assert GlueUnSerializer ( data ) . object ( '<STR_LIT>' ) == <NUM_LIT:3> <EOL> def test_default_earliest_load ( self ) : <EOL> data = json . dumps ( { '<STR_LIT>' : { '<STR_LIT>' : '<STR_LIT>' } } ) <EOL> assert GlueUnSerializer ( data ) . object ( '<STR_LIT>' ) == <NUM_LIT:3> <EOL> class TestVersionedDict ( object ) : <EOL> def test_bad_add ( self ) : <EOL> d = VersionedDict ( ) <EOL> with pytest . raises ( KeyError ) : <EOL> d [ '<STR_LIT>' , <NUM_LIT:2> ] = <NUM_LIT:5> <EOL> def test_get ( self ) : <EOL> d = VersionedDict ( ) <EOL> d [ '<STR_LIT:key>' , <NUM_LIT:1> ] = <NUM_LIT:5> <EOL> d [ '<STR_LIT:key>' , <NUM_LIT:2> ] = <NUM_LIT:6> <EOL> d [ '<STR_LIT:key>' , <NUM_LIT:3> ] = <NUM_LIT:7> <EOL> assert d [ '<STR_LIT:key>' ] == ( <NUM_LIT:7> , <NUM_LIT:3> ) <EOL> assert d . get_version ( '<STR_LIT:key>' , <NUM_LIT:1> ) == <NUM_LIT:5> <EOL> assert d . get_version ( '<STR_LIT:key>' , <NUM_LIT:2> ) == <NUM_LIT:6> <EOL> assert d . get_version ( '<STR_LIT:key>' , <NUM_LIT:3> ) == <NUM_LIT:7> <EOL> with pytest . raises ( KeyError ) as exc : <EOL> d [ '<STR_LIT>' ] <EOL> def test_get_missing ( self ) : <EOL> d = VersionedDict ( ) <EOL> d [ '<STR_LIT:key>' , <NUM_LIT:1> ] = <NUM_LIT:5> <EOL> with pytest . raises ( KeyError ) as exc : <EOL> d . get_version ( '<STR_LIT:key>' , <NUM_LIT:2> ) <EOL> assert exc . value . args [ <NUM_LIT:0> ] == '<STR_LIT>' <EOL> def test_contains ( self ) : <EOL> d = VersionedDict ( ) <EOL> assert '<STR_LIT:key>' not in d <EOL> d [ '<STR_LIT:key>' , <NUM_LIT:1> ] = <NUM_LIT:3> <EOL> assert '<STR_LIT:key>' in d <EOL> def test_overwrite_forbidden ( self ) : <EOL> d = VersionedDict ( ) <EOL> d [ '<STR_LIT:key>' , <NUM_LIT:1> ] = <NUM_LIT:3> <EOL> with pytest . raises ( KeyError ) as exc : <EOL> d [ '<STR_LIT:key>' , <NUM_LIT:1> ] = <NUM_LIT:3> <EOL> def test_noninteger_version ( self ) : <EOL> d = VersionedDict ( ) <EOL> with pytest . raises ( ValueError ) as exc : <EOL> d [ '<STR_LIT:key>' , '<STR_LIT>' ] = <NUM_LIT:4> </s>
<s> from . slices import extract_slice <EOL> from . path import Path </s>
<s> import numpy as np <EOL> from astropy import units as u <EOL> from astropy . extern import six <EOL> def select_step_degree ( dv ) : <EOL> if dv > <NUM_LIT:1.> * u . arcsec : <EOL> degree_limits_ = [ <NUM_LIT> , <NUM_LIT:3> , <NUM_LIT:7> , <NUM_LIT> , <NUM_LIT:20> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> degree_steps_ = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:5> , <NUM_LIT:10> , <NUM_LIT:15> , <NUM_LIT:30> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> degree_units = [ u . degree ] * len ( degree_steps_ ) <EOL> minsec_limits_ = [ <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:8> , <NUM_LIT:11> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> minsec_steps_ = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:5> , <NUM_LIT:10> , <NUM_LIT:15> , <NUM_LIT:20> , <NUM_LIT:30> ] <EOL> minute_limits_ = np . array ( minsec_limits_ ) / <NUM_LIT> <EOL> minute_units = [ u . arcmin ] * len ( minute_limits_ ) <EOL> second_limits_ = np . array ( minsec_limits_ ) / <NUM_LIT> <EOL> second_units = [ u . arcsec ] * len ( second_limits_ ) <EOL> degree_limits = np . concatenate ( [ second_limits_ , <EOL> minute_limits_ , <EOL> degree_limits_ ] ) <EOL> degree_steps = minsec_steps_ + minsec_steps_ + degree_steps_ <EOL> degree_units = second_units + minute_units + degree_units <EOL> n = degree_limits . searchsorted ( dv . to ( u . degree ) ) <EOL> step = degree_steps [ n ] <EOL> unit = degree_units [ n ] <EOL> return step * unit <EOL> else : <EOL> return select_step_scalar ( dv . to ( u . arcsec ) . value ) * u . arcsec <EOL> def select_step_hour ( dv ) : <EOL> if dv > <NUM_LIT> * u . arcsec : <EOL> hour_limits_ = [ <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:5> , <NUM_LIT:7> , <NUM_LIT:10> , <NUM_LIT:15> , <NUM_LIT> , <NUM_LIT> ] <EOL> hour_steps_ = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> , <NUM_LIT:6> , <NUM_LIT:8> , <NUM_LIT:12> , <NUM_LIT> , <NUM_LIT> ] <EOL> hour_units = [ u . hourangle ] * len ( hour_steps_ ) <EOL> minsec_limits_ = [ <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:8> , <NUM_LIT:11> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> minsec_steps_ = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> , <NUM_LIT:5> , <NUM_LIT:6> , <NUM_LIT:10> , <NUM_LIT:12> , <NUM_LIT:15> , <NUM_LIT:20> , <NUM_LIT:30> ] <EOL> minute_limits_ = np . array ( minsec_limits_ ) / <NUM_LIT> <EOL> minute_units = [ <NUM_LIT> * u . arcmin ] * len ( minute_limits_ ) <EOL> second_limits_ = np . array ( minsec_limits_ ) / <NUM_LIT> <EOL> second_units = [ <NUM_LIT> * u . arcsec ] * len ( second_limits_ ) <EOL> hour_limits = np . concatenate ( [ second_limits_ , <EOL> minute_limits_ , <EOL> hour_limits_ ] ) <EOL> hour_steps = minsec_steps_ + minsec_steps_ + hour_steps_ <EOL> hour_units = second_units + minute_units + hour_units <EOL> n = hour_limits . searchsorted ( dv . to ( u . hourangle ) ) <EOL> step = hour_steps [ n ] <EOL> unit = hour_units [ n ] <EOL> return step * unit <EOL> else : <EOL> return select_step_scalar ( dv . to ( <NUM_LIT> * u . arcsec ) . value ) * ( <NUM_LIT> * u . arcsec ) <EOL> def select_step_scalar ( dv ) : <EOL> log10_dv = np . log10 ( dv ) <EOL> base = np . floor ( log10_dv ) <EOL> frac = log10_dv - base <EOL> steps = np . log10 ( [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:5> , <NUM_LIT:10> ] ) <EOL> imin = np . argmin ( np . abs ( frac - steps ) ) <EOL> return <NUM_LIT> ** ( base + steps [ imin ] ) <EOL> def get_coord_meta ( frame ) : <EOL> coord_meta = { } <EOL> coord_meta [ '<STR_LIT:type>' ] = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> coord_meta [ '<STR_LIT>' ] = ( None , None ) <EOL> coord_meta [ '<STR_LIT>' ] = ( u . deg , u . deg ) <EOL> try : <EOL> from astropy . coordinates import frame_transform_graph <EOL> if isinstance ( frame , six . string_types ) : <EOL> frame = frame_transform_graph . lookup_name ( frame ) <EOL> names = list ( frame ( ) . representation_component_names . keys ( ) ) <EOL> coord_meta [ '<STR_LIT:name>' ] = names [ : <NUM_LIT:2> ] <EOL> except ImportError : <EOL> if isinstance ( frame , six . string_types ) : <EOL> if frame in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> coord_meta [ '<STR_LIT:name>' ] = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> elif frame == '<STR_LIT>' : <EOL> coord_meta [ '<STR_LIT:name>' ] = ( '<STR_LIT:l>' , '<STR_LIT:b>' ) <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" . format ( frame ) ) <EOL> return coord_meta <EOL> def coord_type_from_ctype ( ctype ) : <EOL> """<STR_LIT>""" <EOL> if ctype [ : <NUM_LIT:4> ] in [ '<STR_LIT>' ] or ctype [ <NUM_LIT:1> : <NUM_LIT:4> ] == '<STR_LIT>' : <EOL> return '<STR_LIT>' , None <EOL> elif ctype [ : <NUM_LIT:4> ] in [ '<STR_LIT>' ] : <EOL> return '<STR_LIT>' , <NUM_LIT> <EOL> elif ctype [ : <NUM_LIT:4> ] in [ '<STR_LIT>' , '<STR_LIT>' ] or ctype [ <NUM_LIT:1> : <NUM_LIT:4> ] == '<STR_LIT>' : <EOL> return '<STR_LIT>' , None <EOL> else : <EOL> return '<STR_LIT>' , None </s>
<s> from __future__ import absolute_import , division , print_function <EOL> import os <EOL> from shutil import rmtree <EOL> from tempfile import mkdtemp <EOL> import numpy as np <EOL> from glue . core import Data <EOL> from glue . tests . helpers import requires_astropy <EOL> from . . export_d3po import make_data_file <EOL> @ requires_astropy <EOL> def test_make_data_file ( ) : <EOL> from astropy . table import Table <EOL> d = Data ( x = [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] , y = [ <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> ] , label = '<STR_LIT:data>' ) <EOL> s = d . new_subset ( label = '<STR_LIT:test>' ) <EOL> s . subset_state = d . id [ '<STR_LIT:x>' ] > <NUM_LIT:1> <EOL> dir = mkdtemp ( ) <EOL> try : <EOL> make_data_file ( d , ( s , ) , dir ) <EOL> t = Table . read ( os . path . join ( dir , '<STR_LIT>' ) , format = '<STR_LIT:ascii>' ) <EOL> np . testing . assert_array_equal ( t [ '<STR_LIT:x>' ] , [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] ) <EOL> np . testing . assert_array_equal ( t [ '<STR_LIT:y>' ] , [ <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> ] ) <EOL> np . testing . assert_array_equal ( t [ '<STR_LIT>' ] , [ <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:1> ] ) <EOL> finally : <EOL> rmtree ( dir , ignore_errors = True ) </s>
<s> from __future__ import absolute_import , division , print_function <EOL> import logging <EOL> from functools import wraps <EOL> import numpy as np <EOL> from glue . external . axescache import AxesCache <EOL> from glue . utils . misc import DeferredMethod <EOL> __all__ = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> def renderless_figure ( ) : <EOL> from mock import MagicMock <EOL> import matplotlib . pyplot as plt <EOL> fig = plt . figure ( ) <EOL> fig . canvas . draw = MagicMock ( ) <EOL> plt . close ( '<STR_LIT:all>' ) <EOL> return fig <EOL> def all_artists ( fig ) : <EOL> """<STR_LIT>""" <EOL> return set ( item <EOL> for axes in fig . axes <EOL> for container in [ axes . collections , axes . patches , axes . lines , <EOL> axes . texts , axes . artists , axes . images ] <EOL> for item in container ) <EOL> def new_artists ( fig , old_artists ) : <EOL> """<STR_LIT>""" <EOL> return all_artists ( fig ) - old_artists <EOL> def remove_artists ( artists ) : <EOL> """<STR_LIT>""" <EOL> for a in artists : <EOL> try : <EOL> a . remove ( ) <EOL> except ValueError : <EOL> pass <EOL> def get_extent ( view , transpose = False ) : <EOL> sy , sx = [ s for s in view if isinstance ( s , slice ) ] <EOL> if transpose : <EOL> return ( sy . start , sy . stop , sx . start , sx . stop ) <EOL> return ( sx . start , sx . stop , sy . start , sy . stop ) <EOL> def view_cascade ( data , view ) : <EOL> """<STR_LIT>""" <EOL> shp = data . shape <EOL> v2 = list ( view ) <EOL> logging . debug ( "<STR_LIT>" , shp , view ) <EOL> step = max ( shp [ i - <NUM_LIT:1> ] * v . step // max ( v . stop - v . start , <NUM_LIT:1> ) <EOL> for i , v in enumerate ( view ) if isinstance ( v , slice ) ) <EOL> step = max ( step , <NUM_LIT:1> ) <EOL> for i , v in enumerate ( v2 ) : <EOL> if not ( isinstance ( v , slice ) ) : <EOL> continue <EOL> v2 [ i ] = slice ( <NUM_LIT:0> , shp [ i - <NUM_LIT:1> ] , step ) <EOL> return tuple ( v2 ) , view <EOL> def _scoreatpercentile ( values , percentile , limit = None ) : <EOL> if limit is not None : <EOL> values = values [ ( values >= limit [ <NUM_LIT:0> ] ) & ( values <= limit [ <NUM_LIT:1> ] ) ] <EOL> return np . percentile ( values , percentile ) <EOL> def fast_limits ( data , plo , phi ) : <EOL> """<STR_LIT>""" <EOL> shp = data . shape <EOL> view = tuple ( [ slice ( None , None , np . intp ( max ( s / <NUM_LIT:50> , <NUM_LIT:1> ) ) ) for s in shp ] ) <EOL> values = np . asarray ( data ) [ view ] <EOL> if ~ np . isfinite ( values ) . any ( ) : <EOL> return ( <NUM_LIT:0.0> , <NUM_LIT:1.0> ) <EOL> limits = ( - np . inf , np . inf ) <EOL> lo = _scoreatpercentile ( values . flat , plo , limit = limits ) <EOL> hi = _scoreatpercentile ( values . flat , phi , limit = limits ) <EOL> return lo , hi <EOL> def defer_draw ( func ) : <EOL> """<STR_LIT>""" <EOL> @ wraps ( func ) <EOL> def wrapper ( * args , ** kwargs ) : <EOL> from matplotlib . backends . backend_agg import FigureCanvasAgg <EOL> if isinstance ( FigureCanvasAgg . draw , DeferredMethod ) : <EOL> return func ( * args , ** kwargs ) <EOL> try : <EOL> FigureCanvasAgg . draw = DeferredMethod ( FigureCanvasAgg . draw ) <EOL> result = func ( * args , ** kwargs ) <EOL> finally : <EOL> FigureCanvasAgg . draw . execute_deferred_calls ( ) <EOL> FigureCanvasAgg . draw = FigureCanvasAgg . draw . original_method <EOL> return result <EOL> wrapper . _is_deferred = True <EOL> return wrapper <EOL> def color2rgb ( color ) : <EOL> from matplotlib . colors import ColorConverter <EOL> result = ColorConverter ( ) . to_rgb ( color ) <EOL> return result <EOL> def point_contour ( x , y , data ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> from scipy import ndimage <EOL> except ImportError : <EOL> raise ImportError ( "<STR_LIT>" ) <EOL> inten = data [ y , x ] <EOL> labeled , nr_objects = ndimage . label ( data >= inten ) <EOL> z = data * ( labeled == labeled [ y , x ] ) <EOL> y , x = np . mgrid [ <NUM_LIT:0> : data . shape [ <NUM_LIT:0> ] , <NUM_LIT:0> : data . shape [ <NUM_LIT:1> ] ] <EOL> from matplotlib import _cntr <EOL> cnt = _cntr . Cntr ( x , y , z ) <EOL> xy = cnt . trace ( inten ) <EOL> if not xy : <EOL> return None <EOL> xy = xy [ <NUM_LIT:0> ] <EOL> return xy <EOL> class AxesResizer ( object ) : <EOL> def __init__ ( self , ax , margins ) : <EOL> self . ax = ax <EOL> self . margins = margins <EOL> @ property <EOL> def margins ( self ) : <EOL> return self . _margins <EOL> @ margins . setter <EOL> def margins ( self , margins ) : <EOL> self . _margins = margins <EOL> def on_resize ( self , event ) : <EOL> fig_width = self . ax . figure . get_figwidth ( ) <EOL> fig_height = self . ax . figure . get_figheight ( ) <EOL> x0 = self . margins [ <NUM_LIT:0> ] / fig_width <EOL> x1 = <NUM_LIT:1> - self . margins [ <NUM_LIT:1> ] / fig_width <EOL> y0 = self . margins [ <NUM_LIT:2> ] / fig_height <EOL> y1 = <NUM_LIT:1> - self . margins [ <NUM_LIT:3> ] / fig_height <EOL> dx = max ( <NUM_LIT> , x1 - x0 ) <EOL> dy = max ( <NUM_LIT> , y1 - y0 ) <EOL> self . ax . set_position ( [ x0 , y0 , dx , dy ] ) <EOL> self . ax . figure . canvas . draw ( ) <EOL> def freeze_margins ( axes , margins = [ <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ] ) : <EOL> """<STR_LIT>""" <EOL> axes . resizer = AxesResizer ( axes , margins ) <EOL> axes . figure . canvas . mpl_connect ( '<STR_LIT>' , axes . resizer . on_resize ) <EOL> def cache_axes ( axes , toolbar ) : <EOL> """<STR_LIT>""" <EOL> canvas = axes . figure . canvas <EOL> cache = AxesCache ( axes ) <EOL> canvas . resize_begin . connect ( cache . enable ) <EOL> canvas . resize_end . connect ( cache . disable ) <EOL> toolbar . pan_begin . connect ( cache . enable ) <EOL> toolbar . pan_end . connect ( cache . disable ) <EOL> return cache </s>
<s> from __future__ import absolute_import , division , print_function <EOL> import os <EOL> from glue . external . qt . QtCore import Qt <EOL> from glue . external . qt import QtGui <EOL> from glue . core . application_base import ViewerBase <EOL> from glue . core . qt . layer_artist_model import QtLayerArtistContainer , LayerArtistWidget <EOL> from glue . external . qt import get_qapp <EOL> from glue . core . qt . mime import LAYERS_MIME_TYPE , LAYER_MIME_TYPE <EOL> from glue . utils . qt import set_cursor <EOL> __all__ = [ '<STR_LIT>' ] <EOL> class DataViewer ( ViewerBase , QtGui . QMainWindow ) : <EOL> """<STR_LIT>""" <EOL> _layer_artist_container_cls = QtLayerArtistContainer <EOL> _layer_style_widget_cls = None <EOL> LABEL = '<STR_LIT>' <EOL> def __init__ ( self , session , parent = None ) : <EOL> """<STR_LIT>""" <EOL> QtGui . QMainWindow . __init__ ( self , parent ) <EOL> ViewerBase . __init__ ( self , session ) <EOL> self . setWindowIcon ( get_qapp ( ) . windowIcon ( ) ) <EOL> self . _view = LayerArtistWidget ( layer_style_widget_cls = self . _layer_style_widget_cls ) <EOL> self . _view . layer_list . setModel ( self . _layer_artist_container . model ) <EOL> self . _tb_vis = { } <EOL> self . setAttribute ( Qt . WA_DeleteOnClose ) <EOL> self . setAcceptDrops ( True ) <EOL> self . setAnimated ( False ) <EOL> self . _toolbars = [ ] <EOL> self . _warn_close = True <EOL> self . setContentsMargins ( <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:2> ) <EOL> self . _mdi_wrapper = None <EOL> self . statusBar ( ) . setStyleSheet ( "<STR_LIT>" ) <EOL> self . _layer_artist_container . on_empty ( lambda : self . close ( warn = False ) ) <EOL> self . _layer_artist_container . on_changed ( self . update_window_title ) <EOL> def remove_layer ( self , layer ) : <EOL> self . _layer_artist_container . pop ( layer ) <EOL> def dragEnterEvent ( self , event ) : <EOL> """<STR_LIT>""" <EOL> if event . mimeData ( ) . hasFormat ( LAYER_MIME_TYPE ) : <EOL> event . accept ( ) <EOL> elif event . mimeData ( ) . hasFormat ( LAYERS_MIME_TYPE ) : <EOL> event . accept ( ) <EOL> else : <EOL> event . ignore ( ) <EOL> def dropEvent ( self , event ) : <EOL> """<STR_LIT>""" <EOL> if event . mimeData ( ) . hasFormat ( LAYER_MIME_TYPE ) : <EOL> self . request_add_layer ( event . mimeData ( ) . data ( LAYER_MIME_TYPE ) ) <EOL> assert event . mimeData ( ) . hasFormat ( LAYERS_MIME_TYPE ) <EOL> for layer in event . mimeData ( ) . data ( LAYERS_MIME_TYPE ) : <EOL> self . request_add_layer ( layer ) <EOL> event . accept ( ) <EOL> def mousePressEvent ( self , event ) : <EOL> """<STR_LIT>""" <EOL> event . accept ( ) <EOL> apply_roi = set_cursor ( Qt . WaitCursor ) ( ViewerBase . apply_roi ) <EOL> def close ( self , warn = True ) : <EOL> self . _warn_close = warn <EOL> super ( DataViewer , self ) . close ( ) <EOL> self . _warn_close = True <EOL> def mdi_wrap ( self ) : <EOL> """<STR_LIT>""" <EOL> from glue . app . qt . mdi_area import GlueMdiSubWindow <EOL> sub = GlueMdiSubWindow ( ) <EOL> sub . setWidget ( self ) <EOL> self . destroyed . connect ( sub . close ) <EOL> sub . resize ( self . size ( ) ) <EOL> self . _mdi_wrapper = sub <EOL> return sub <EOL> @ property <EOL> def position ( self ) : <EOL> target = self . _mdi_wrapper or self <EOL> pos = target . pos ( ) <EOL> return pos . x ( ) , pos . y ( ) <EOL> @ position . setter <EOL> def position ( self , xy ) : <EOL> x , y = xy <EOL> self . move ( x , y ) <EOL> def move ( self , x = None , y = None ) : <EOL> """<STR_LIT>""" <EOL> x0 , y0 = self . position <EOL> if x is None : <EOL> x = x0 <EOL> if y is None : <EOL> y = y0 <EOL> if self . _mdi_wrapper is not None : <EOL> self . _mdi_wrapper . move ( x , y ) <EOL> else : <EOL> QtGui . QMainWindow . move ( self , x , y ) <EOL> @ property <EOL> def viewer_size ( self ) : <EOL> if self . _mdi_wrapper is not None : <EOL> sz = self . _mdi_wrapper . size ( ) <EOL> else : <EOL> sz = self . size ( ) <EOL> return sz . width ( ) , sz . height ( ) <EOL> @ viewer_size . setter <EOL> def viewer_size ( self , value ) : <EOL> width , height = value <EOL> self . resize ( width , height ) <EOL> if self . _mdi_wrapper is not None : <EOL> self . _mdi_wrapper . resize ( width , height ) <EOL> def closeEvent ( self , event ) : <EOL> """<STR_LIT>""" <EOL> if not self . _confirm_close ( ) : <EOL> event . ignore ( ) <EOL> return <EOL> if self . _hub is not None : <EOL> self . unregister ( self . _hub ) <EOL> self . _layer_artist_container . clear_callbacks ( ) <EOL> self . _layer_artist_container . clear ( ) <EOL> super ( DataViewer , self ) . closeEvent ( event ) <EOL> event . accept ( ) <EOL> def _confirm_close ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _warn_close and ( not os . environ . get ( '<STR_LIT>' ) ) and self . isVisible ( ) : <EOL> buttons = QtGui . QMessageBox . Ok | QtGui . QMessageBox . Cancel <EOL> dialog = QtGui . QMessageBox . warning ( self , "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> buttons = buttons , <EOL> defaultButton = QtGui . QMessageBox . Cancel ) <EOL> return dialog == QtGui . QMessageBox . Ok <EOL> return True <EOL> def _confirm_large_data ( self , data ) : <EOL> warn_msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" % data . size ) <EOL> title = "<STR_LIT>" <EOL> ok = QtGui . QMessageBox . Ok <EOL> cancel = QtGui . QMessageBox . Cancel <EOL> buttons = ok | cancel <EOL> result = QtGui . QMessageBox . question ( self , title , warn_msg , <EOL> buttons = buttons , <EOL> defaultButton = cancel ) <EOL> return result == ok <EOL> def layer_view ( self ) : <EOL> return self . _view <EOL> def options_widget ( self ) : <EOL> return QtGui . QWidget ( ) <EOL> def addToolBar ( self , tb ) : <EOL> super ( DataViewer , self ) . addToolBar ( tb ) <EOL> self . _toolbars . append ( tb ) <EOL> self . _tb_vis [ tb ] = True <EOL> def show_toolbars ( self ) : <EOL> """<STR_LIT>""" <EOL> for tb in self . _toolbars : <EOL> if self . _tb_vis . get ( tb , False ) : <EOL> tb . setEnabled ( True ) <EOL> def hide_toolbars ( self ) : <EOL> """<STR_LIT>""" <EOL> for tb in self . _toolbars : <EOL> self . _tb_vis [ tb ] = self . _tb_vis . get ( tb , False ) or tb . isVisible ( ) <EOL> tb . setEnabled ( False ) <EOL> def set_focus ( self , state ) : <EOL> if state : <EOL> css = """<STR_LIT>""" <EOL> self . setStyleSheet ( css ) <EOL> self . show_toolbars ( ) <EOL> else : <EOL> css = """<STR_LIT>""" <EOL> self . setStyleSheet ( css ) <EOL> self . hide_toolbars ( ) <EOL> def __str__ ( self ) : <EOL> return self . LABEL <EOL> def unregister ( self , hub ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> @ property <EOL> def window_title ( self ) : <EOL> return str ( self ) <EOL> def update_window_title ( self ) : <EOL> self . setWindowTitle ( self . window_title ) </s>
<s> from __future__ import absolute_import , division , print_function <EOL> import os <EOL> from glue . external . modest_image import imshow <EOL> from glue . external . qt . QtCore import Qt <EOL> from glue . external . qt import QtGui , QtCore <EOL> from glue . core . callback_property import add_callback , delay_callback <EOL> from glue import core <EOL> from glue . viewers . image . ds9norm import DS9Normalize <EOL> from glue . viewers . image . client import MplImageClient <EOL> from glue . viewers . common . qt . toolbar import GlueToolbar <EOL> from glue . viewers . common . qt . mouse_mode import ( RectangleMode , CircleMode , PolyMode , <EOL> ContrastMode ) <EOL> from glue . icons . qt import get_icon <EOL> from glue . utils . qt . widget_properties import CurrentComboProperty , ButtonProperty , connect_current_combo , _find_combo_data <EOL> from glue . viewers . common . qt . data_slice_widget import DataSlice <EOL> from glue . viewers . common . qt . data_viewer import DataViewer <EOL> from glue . viewers . common . qt . mpl_widget import MplWidget , defer_draw <EOL> from glue . utils import nonpartial , Pointer <EOL> from glue . utils . qt import cmap2pixmap , update_combobox , load_ui <EOL> from glue . viewers . image . qt . rgb_edit import RGBEdit <EOL> WARN_THRESH = <NUM_LIT> <EOL> __all__ = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> class ImageWidgetBase ( DataViewer ) : <EOL> """<STR_LIT>""" <EOL> LABEL = "<STR_LIT>" <EOL> _property_set = DataViewer . _property_set + '<STR_LIT>' . split ( ) <EOL> attribute = CurrentComboProperty ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> data = CurrentComboProperty ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> aspect_ratio = CurrentComboProperty ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> rgb_mode = ButtonProperty ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> rgb_viz = Pointer ( '<STR_LIT>' ) <EOL> def __init__ ( self , session , parent = None ) : <EOL> super ( ImageWidgetBase , self ) . __init__ ( session , parent ) <EOL> self . _setup_widgets ( ) <EOL> self . client = self . make_client ( ) <EOL> self . _setup_tools ( ) <EOL> tb = self . make_toolbar ( ) <EOL> self . addToolBar ( tb ) <EOL> self . _connect ( ) <EOL> def _setup_widgets ( self ) : <EOL> self . central_widget = self . make_central_widget ( ) <EOL> self . label_widget = QtGui . QLabel ( "<STR_LIT>" , self . central_widget ) <EOL> self . setCentralWidget ( self . central_widget ) <EOL> self . option_widget = QtGui . QWidget ( ) <EOL> self . ui = load_ui ( '<STR_LIT>' , self . option_widget , <EOL> directory = os . path . dirname ( __file__ ) ) <EOL> self . ui . slice = DataSlice ( ) <EOL> self . ui . slice_layout . addWidget ( self . ui . slice ) <EOL> self . _tweak_geometry ( ) <EOL> self . ui . aspectCombo . addItem ( "<STR_LIT>" , userData = '<STR_LIT>' ) <EOL> self . ui . aspectCombo . addItem ( "<STR_LIT>" , userData = '<STR_LIT>' ) <EOL> def make_client ( self ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( ) <EOL> def make_central_widget ( self ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( ) <EOL> def make_toolbar ( self ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( ) <EOL> @ staticmethod <EOL> def _get_default_tools ( ) : <EOL> return [ ] <EOL> def _setup_tools ( self ) : <EOL> """<STR_LIT>""" <EOL> from glue import config <EOL> self . _tools = [ ] <EOL> for tool in config . tool_registry . members [ self . __class__ ] : <EOL> self . _tools . append ( tool ( self ) ) <EOL> def _tweak_geometry ( self ) : <EOL> self . central_widget . resize ( <NUM_LIT> , <NUM_LIT> ) <EOL> self . resize ( self . central_widget . size ( ) ) <EOL> self . ui . rgb_options . hide ( ) <EOL> self . statusBar ( ) . setSizeGripEnabled ( False ) <EOL> self . setFocusPolicy ( Qt . StrongFocus ) <EOL> @ defer_draw <EOL> def add_data ( self , data ) : <EOL> """<STR_LIT>""" <EOL> with delay_callback ( self . client , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> if data . data . ndim == <NUM_LIT:1> and self . client . display_data is None : <EOL> QtGui . QMessageBox . information ( self . window ( ) , "<STR_LIT>" , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" , <EOL> buttons = QtGui . QMessageBox . Ok ) <EOL> return <EOL> r = self . client . add_layer ( data ) <EOL> if r is not None and self . client . display_data is not None : <EOL> self . add_data_to_combo ( data ) <EOL> if self . client . can_image_data ( data ) : <EOL> self . client . display_data = data <EOL> self . set_attribute_combo ( self . client . display_data ) <EOL> return r is not None <EOL> @ defer_draw <EOL> def add_subset ( self , subset ) : <EOL> self . client . add_scatter_layer ( subset ) <EOL> assert subset in self . client . artists <EOL> def add_data_to_combo ( self , data ) : <EOL> """<STR_LIT>""" <EOL> if not self . client . can_image_data ( data ) : <EOL> return <EOL> combo = self . ui . displayDataCombo <EOL> try : <EOL> pos = _find_combo_data ( combo , data ) <EOL> except ValueError : <EOL> combo . addItem ( data . label , userData = data ) <EOL> @ property <EOL> def ratt ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . ui . rgb_options . attributes [ <NUM_LIT:0> ] <EOL> @ ratt . setter <EOL> def ratt ( self , value ) : <EOL> att = list ( self . ui . rgb_options . attributes ) <EOL> att [ <NUM_LIT:0> ] = value <EOL> self . ui . rgb_options . attributes = att <EOL> @ property <EOL> def gatt ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . ui . rgb_options . attributes [ <NUM_LIT:1> ] <EOL> @ gatt . setter <EOL> def gatt ( self , value ) : <EOL> att = list ( self . ui . rgb_options . attributes ) <EOL> att [ <NUM_LIT:1> ] = value <EOL> self . ui . rgb_options . attributes = att <EOL> @ property <EOL> def batt ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . ui . rgb_options . attributes [ <NUM_LIT:2> ] <EOL> @ batt . setter <EOL> def batt ( self , value ) : <EOL> att = list ( self . ui . rgb_options . attributes ) <EOL> att [ <NUM_LIT:2> ] = value <EOL> self . ui . rgb_options . attributes = att <EOL> @ property <EOL> def slice ( self ) : <EOL> return self . client . slice <EOL> @ slice . setter <EOL> def slice ( self , value ) : <EOL> self . client . slice = value <EOL> def set_attribute_combo ( self , data ) : <EOL> """<STR_LIT>""" <EOL> labeldata = ( ( f . label , f ) for f in data . visible_components ) <EOL> update_combobox ( self . ui . attributeComboBox , labeldata ) <EOL> def _connect ( self ) : <EOL> ui = self . ui <EOL> ui . monochrome . toggled . connect ( self . _update_rgb_console ) <EOL> ui . rgb_options . colors_changed . connect ( self . update_window_title ) <EOL> ui . slice . slice_changed . connect ( lambda : setattr ( self , '<STR_LIT>' , self . ui . slice . slice ) ) <EOL> update_ui_slice = lambda val : setattr ( ui . slice , '<STR_LIT>' , val ) <EOL> add_callback ( self . client , '<STR_LIT>' , update_ui_slice ) <EOL> add_callback ( self . client , '<STR_LIT>' , self . ui . slice . set_data ) <EOL> add_callback ( self . client , '<STR_LIT>' , nonpartial ( self . _display_data_changed ) ) <EOL> add_callback ( self . client , '<STR_LIT>' , nonpartial ( self . _display_attribute_changed ) ) <EOL> add_callback ( self . client , '<STR_LIT>' , nonpartial ( self . client . _update_aspect ) ) <EOL> connect_current_combo ( self . client , '<STR_LIT>' , self . ui . displayDataCombo ) <EOL> connect_current_combo ( self . client , '<STR_LIT>' , self . ui . attributeComboBox ) <EOL> connect_current_combo ( self . client , '<STR_LIT>' , self . ui . aspectCombo ) <EOL> def _display_data_changed ( self ) : <EOL> if self . client . display_data is None : <EOL> self . ui . attributeComboBox . clear ( ) <EOL> return <EOL> with self . client . artists . ignore_empty ( ) : <EOL> self . set_attribute_combo ( self . client . display_data ) <EOL> self . client . add_layer ( self . client . display_data ) <EOL> self . client . _update_and_redraw ( ) <EOL> self . update_window_title ( ) <EOL> def _display_attribute_changed ( self ) : <EOL> if self . client . display_attribute is None : <EOL> return <EOL> self . client . _update_and_redraw ( ) <EOL> self . update_window_title ( ) <EOL> @ defer_draw <EOL> def _update_rgb_console ( self , is_monochrome ) : <EOL> if is_monochrome : <EOL> self . ui . rgb_options . hide ( ) <EOL> self . ui . mono_att_label . show ( ) <EOL> self . ui . attributeComboBox . show ( ) <EOL> self . client . rgb_mode ( False ) <EOL> else : <EOL> self . ui . mono_att_label . hide ( ) <EOL> self . ui . attributeComboBox . hide ( ) <EOL> self . ui . rgb_options . show ( ) <EOL> rgb = self . client . rgb_mode ( True ) <EOL> if rgb is not None : <EOL> self . ui . rgb_options . artist = rgb <EOL> def register_to_hub ( self , hub ) : <EOL> super ( ImageWidgetBase , self ) . register_to_hub ( hub ) <EOL> self . client . register_to_hub ( hub ) <EOL> dc_filt = lambda x : x . sender is self . client . _data <EOL> display_data_filter = lambda x : x . data is self . client . display_data <EOL> hub . subscribe ( self , <EOL> core . message . DataCollectionAddMessage , <EOL> handler = lambda x : self . add_data_to_combo ( x . data ) , <EOL> filter = dc_filt ) <EOL> hub . subscribe ( self , <EOL> core . message . DataCollectionDeleteMessage , <EOL> handler = lambda x : self . remove_data_from_combo ( x . data ) , <EOL> filter = dc_filt ) <EOL> hub . subscribe ( self , <EOL> core . message . DataUpdateMessage , <EOL> handler = lambda x : self . _sync_data_labels ( ) <EOL> ) <EOL> hub . subscribe ( self , <EOL> core . message . ComponentsChangedMessage , <EOL> handler = lambda x : self . set_attribute_combo ( x . data ) , <EOL> filter = display_data_filter ) <EOL> def unregister ( self , hub ) : <EOL> super ( ImageWidgetBase , self ) . unregister ( hub ) <EOL> for obj in [ self , self . client ] : <EOL> hub . unsubscribe_all ( obj ) <EOL> def remove_data_from_combo ( self , data ) : <EOL> """<STR_LIT>""" <EOL> combo = self . ui . displayDataCombo <EOL> pos = combo . findText ( data . label ) <EOL> if pos >= <NUM_LIT:0> : <EOL> combo . removeItem ( pos ) <EOL> def _set_norm ( self , mode ) : <EOL> """<STR_LIT>""" <EOL> clip_lo , clip_hi = mode . get_clip_percentile ( ) <EOL> vmin , vmax = mode . get_vmin_vmax ( ) <EOL> stretch = mode . stretch <EOL> return self . client . set_norm ( clip_lo = clip_lo , clip_hi = clip_hi , <EOL> stretch = stretch , <EOL> vmin = vmin , vmax = vmax , <EOL> bias = mode . bias , contrast = mode . contrast ) <EOL> @ property <EOL> def window_title ( self ) : <EOL> if self . client . display_data is None or self . client . display_attribute is None : <EOL> title = '<STR_LIT>' <EOL> else : <EOL> data = self . client . display_data . label <EOL> a = self . client . rgb_mode ( ) <EOL> if a is None : <EOL> title = "<STR_LIT>" % ( self . client . display_data . label , <EOL> self . client . display_attribute . label ) <EOL> else : <EOL> r = a . r . label if a . r is not None else '<STR_LIT>' <EOL> g = a . g . label if a . g is not None else '<STR_LIT>' <EOL> b = a . b . label if a . b is not None else '<STR_LIT>' <EOL> title = "<STR_LIT>" % ( data , r , g , b ) <EOL> return title <EOL> def _sync_data_combo_labels ( self ) : <EOL> combo = self . ui . displayDataCombo <EOL> for i in range ( combo . count ( ) ) : <EOL> combo . setItemText ( i , combo . itemData ( i ) . label ) <EOL> def _sync_data_labels ( self ) : <EOL> self . update_window_title ( ) <EOL> self . _sync_data_combo_labels ( ) <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT>" <EOL> def _confirm_large_image ( self , data ) : <EOL> """<STR_LIT>""" <EOL> warn_msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" % data . size ) <EOL> title = "<STR_LIT>" <EOL> ok = QtGui . QMessageBox . Ok <EOL> cancel = QtGui . QMessageBox . Cancel <EOL> buttons = ok | cancel <EOL> result = QtGui . QMessageBox . question ( self , title , warn_msg , <EOL> buttons = buttons , <EOL> defaultButton = cancel ) <EOL> return result == ok <EOL> def options_widget ( self ) : <EOL> return self . option_widget <EOL> @ defer_draw <EOL> def restore_layers ( self , rec , context ) : <EOL> with delay_callback ( self . client , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> self . client . restore_layers ( rec , context ) <EOL> for artist in self . layers : <EOL> self . add_data_to_combo ( artist . layer . data ) <EOL> self . set_attribute_combo ( self . client . display_data ) <EOL> self . _sync_data_combo_labels ( ) <EOL> def closeEvent ( self , event ) : <EOL> super ( ImageWidgetBase , self ) . closeEvent ( event ) <EOL> if event . isAccepted ( ) : <EOL> for t in self . _tools : <EOL> t . close ( ) <EOL> class ImageWidget ( ImageWidgetBase ) : <EOL> """<STR_LIT>""" <EOL> def make_client ( self ) : <EOL> return MplImageClient ( self . _data , <EOL> self . central_widget . canvas . fig , <EOL> layer_artist_container = self . _layer_artist_container ) <EOL> def make_central_widget ( self ) : <EOL> return MplWidget ( ) <EOL> def make_toolbar ( self ) : <EOL> result = GlueToolbar ( self . central_widget . canvas , self , name = '<STR_LIT>' ) <EOL> for mode in self . _mouse_modes ( ) : <EOL> result . add_mode ( mode ) <EOL> cmap = _colormap_mode ( self , self . client . set_cmap ) <EOL> result . addWidget ( cmap ) <EOL> cl = self . client <EOL> result . buttons [ '<STR_LIT>' ] . triggered . connect ( nonpartial ( cl . check_update ) ) <EOL> result . buttons [ '<STR_LIT>' ] . triggered . connect ( nonpartial ( <EOL> cl . check_update ) ) <EOL> result . buttons [ '<STR_LIT>' ] . triggered . connect ( nonpartial ( cl . check_update ) ) <EOL> return result <EOL> def _mouse_modes ( self ) : <EOL> axes = self . client . axes <EOL> def apply_mode ( mode ) : <EOL> for roi_mode in roi_modes : <EOL> if roi_mode != mode : <EOL> roi_mode . _roi_tool . reset ( ) <EOL> self . apply_roi ( mode . roi ( ) ) <EOL> rect = RectangleMode ( axes , roi_callback = apply_mode ) <EOL> circ = CircleMode ( axes , roi_callback = apply_mode ) <EOL> poly = PolyMode ( axes , roi_callback = apply_mode ) <EOL> roi_modes = [ rect , circ , poly ] <EOL> contrast = ContrastMode ( axes , move_callback = self . _set_norm ) <EOL> self . _contrast = contrast <EOL> tool_modes = [ ] <EOL> for tool in self . _tools : <EOL> tool_modes += tool . _get_modes ( axes ) <EOL> add_callback ( self . client , '<STR_LIT>' , tool . _display_data_hook ) <EOL> return [ rect , circ , poly , contrast ] + tool_modes <EOL> def paintEvent ( self , event ) : <EOL> super ( ImageWidget , self ) . paintEvent ( event ) <EOL> pos = self . central_widget . canvas . mapFromGlobal ( QtGui . QCursor . pos ( ) ) <EOL> x , y = pos . x ( ) , self . central_widget . canvas . height ( ) - pos . y ( ) <EOL> self . _update_intensity_label ( x , y ) <EOL> def _intensity_label ( self , x , y ) : <EOL> x , y = self . client . axes . transData . inverted ( ) . transform ( [ ( x , y ) ] ) [ <NUM_LIT:0> ] <EOL> value = self . client . point_details ( x , y ) [ '<STR_LIT:value>' ] <EOL> lbl = '<STR_LIT>' if value is None else "<STR_LIT>" % value <EOL> return lbl <EOL> def _update_intensity_label ( self , x , y ) : <EOL> lbl = self . _intensity_label ( x , y ) <EOL> self . label_widget . setText ( lbl ) <EOL> fm = self . label_widget . fontMetrics ( ) <EOL> w , h = fm . width ( lbl ) , fm . height ( ) <EOL> g = QtCore . QRect ( <NUM_LIT:20> , self . central_widget . geometry ( ) . height ( ) - h , w , h ) <EOL> self . label_widget . setGeometry ( g ) <EOL> def _connect ( self ) : <EOL> super ( ImageWidget , self ) . _connect ( ) <EOL> self . ui . rgb_options . current_changed . connect ( lambda : self . _toolbars [ <NUM_LIT:0> ] . set_mode ( self . _contrast ) ) <EOL> self . central_widget . canvas . resize_end . connect ( self . client . check_update ) <EOL> class ColormapAction ( QtGui . QAction ) : <EOL> def __init__ ( self , label , cmap , parent ) : <EOL> super ( ColormapAction , self ) . __init__ ( label , parent ) <EOL> self . cmap = cmap <EOL> pm = cmap2pixmap ( cmap ) <EOL> self . setIcon ( QtGui . QIcon ( pm ) ) <EOL> def _colormap_mode ( parent , on_trigger ) : <EOL> from glue import config <EOL> acts = [ ] <EOL> for label , cmap in config . colormaps : <EOL> a = ColormapAction ( label , cmap , parent ) <EOL> a . triggered . connect ( nonpartial ( on_trigger , cmap ) ) <EOL> acts . append ( a ) <EOL> tb = QtGui . QToolButton ( ) <EOL> tb . setWhatsThis ( "<STR_LIT>" ) <EOL> tb . setToolTip ( "<STR_LIT>" ) <EOL> icon = get_icon ( '<STR_LIT>' ) <EOL> tb . setIcon ( icon ) <EOL> tb . setPopupMode ( QtGui . QToolButton . InstantPopup ) <EOL> tb . addActions ( acts ) <EOL> return tb <EOL> class StandaloneImageWidget ( QtGui . QMainWindow ) : <EOL> """<STR_LIT>""" <EOL> window_closed = QtCore . Signal ( ) <EOL> def __init__ ( self , image = None , wcs = None , parent = None , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> super ( StandaloneImageWidget , self ) . __init__ ( parent ) <EOL> self . central_widget = MplWidget ( ) <EOL> self . setCentralWidget ( self . central_widget ) <EOL> self . _setup_axes ( ) <EOL> self . _im = None <EOL> self . _norm = DS9Normalize ( ) <EOL> self . make_toolbar ( ) <EOL> if image is not None : <EOL> self . set_image ( image = image , wcs = wcs , ** kwargs ) <EOL> def _setup_axes ( self ) : <EOL> from glue . viewers . common . viz_client import init_mpl <EOL> _ , self . _axes = init_mpl ( self . central_widget . canvas . fig , axes = None , wcs = True ) <EOL> self . _axes . set_aspect ( '<STR_LIT>' , adjustable = '<STR_LIT>' ) <EOL> def set_image ( self , image = None , wcs = None , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> if self . _im is not None : <EOL> self . _im . remove ( ) <EOL> self . _im = None <EOL> kwargs . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> if wcs is not None : <EOL> self . _axes . reset_wcs ( wcs ) <EOL> self . _im = imshow ( self . _axes , image , norm = self . _norm , cmap = '<STR_LIT>' , ** kwargs ) <EOL> self . _im_array = image <EOL> self . _wcs = wcs <EOL> self . _redraw ( ) <EOL> @ property <EOL> def axes ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _axes <EOL> def show ( self ) : <EOL> super ( StandaloneImageWidget , self ) . show ( ) <EOL> self . _redraw ( ) <EOL> def _redraw ( self ) : <EOL> self . central_widget . canvas . draw ( ) <EOL> def _set_cmap ( self , cmap ) : <EOL> self . _im . set_cmap ( cmap ) <EOL> self . _redraw ( ) <EOL> def mdi_wrap ( self ) : <EOL> """<STR_LIT>""" <EOL> from glue . app . qt . mdi_area import GlueMdiSubWindow <EOL> sub = GlueMdiSubWindow ( ) <EOL> sub . setWidget ( self ) <EOL> self . destroyed . connect ( sub . close ) <EOL> self . window_closed . connect ( sub . close ) <EOL> sub . resize ( self . size ( ) ) <EOL> self . _mdi_wrapper = sub <EOL> return sub <EOL> def closeEvent ( self , event ) : <EOL> self . window_closed . emit ( ) <EOL> return super ( StandaloneImageWidget , self ) . closeEvent ( event ) <EOL> def _set_norm ( self , mode ) : <EOL> """<STR_LIT>""" <EOL> clip_lo , clip_hi = mode . get_clip_percentile ( ) <EOL> vmin , vmax = mode . get_vmin_vmax ( ) <EOL> stretch = mode . stretch <EOL> self . _norm . clip_lo = clip_lo <EOL> self . _norm . clip_hi = clip_hi <EOL> self . _norm . stretch = stretch <EOL> self . _norm . bias = mode . bias <EOL> self . _norm . contrast = mode . contrast <EOL> self . _norm . vmin = vmin <EOL> self . _norm . vmax = vmax <EOL> self . _im . set_norm ( self . _norm ) <EOL> self . _redraw ( ) <EOL> def make_toolbar ( self ) : <EOL> """<STR_LIT>""" <EOL> result = GlueToolbar ( self . central_widget . canvas , self , <EOL> name = '<STR_LIT>' ) <EOL> result . add_mode ( ContrastMode ( self . _axes , move_callback = self . _set_norm ) ) <EOL> cm = _colormap_mode ( self , self . _set_cmap ) <EOL> result . addWidget ( cm ) <EOL> self . _cmap_actions = cm . actions ( ) <EOL> self . addToolBar ( result ) <EOL> return result </s>
<s> """<STR_LIT>""" <EOL> import os <EOL> __file__ = os . path . abspath ( __file__ ) <EOL> import json <EOL> import copy <EOL> def here ( path ) : <EOL> return os . path . join ( os . path . dirname ( __file__ ) , path ) <EOL> def meta ( platform ) : <EOL> if platform == "<STR_LIT>" : <EOL> return "<STR_LIT>" <EOL> else : <EOL> return "<STR_LIT>" <EOL> def require_setting ( mapping , setting ) : <EOL> mapping . setdefault ( "<STR_LIT>" , [ ] ) . append ( <EOL> dict ( key = setting , <EOL> operator = "<STR_LIT>" , <EOL> operand = True ) ) <EOL> def add_arg ( mapping , name , value ) : <EOL> mapping . setdefault ( "<STR_LIT:args>" , { } ) [ name ] = value <EOL> def new_map ( kmap , platform , conditional ) : <EOL> new = [ ] <EOL> for binding in kmap : <EOL> new . append ( binding ) <EOL> binding [ '<STR_LIT>' ] = [ <EOL> k . replace ( <EOL> "<STR_LIT>" , meta ( platform ) + "<STR_LIT:+>" <EOL> ) for k in binding [ '<STR_LIT>' ] <EOL> ] <EOL> if conditional : <EOL> require_setting ( binding , "<STR_LIT>" ) <EOL> if binding . get ( "<STR_LIT>" ) in [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] : <EOL> clone = copy . deepcopy ( binding ) <EOL> require_setting ( clone , "<STR_LIT>" ) <EOL> add_arg ( clone , "<STR_LIT>" , True ) <EOL> new . append ( clone ) <EOL> return new <EOL> def for_platform ( platform ) : <EOL> return here ( "<STR_LIT>" . format ( platform ) ) <EOL> def all_maps ( conditional = False ) : <EOL> template = json . load ( open ( here ( "<STR_LIT>" ) ) ) <EOL> for platform in "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" : <EOL> cloned = copy . deepcopy ( template ) <EOL> doubleclone = new_map ( cloned , platform , conditional ) <EOL> doubleclone . append ( { <EOL> "<STR_LIT>" : [ <EOL> meta ( platform ) + "<STR_LIT>" , <EOL> ] , <EOL> "<STR_LIT>" : "<STR_LIT>" <EOL> } ) <EOL> fn = for_platform ( platform ) <EOL> tfn = fn + "<STR_LIT>" <EOL> with open ( tfn , "<STR_LIT:wb>" ) as f : <EOL> f . write ( json . dumps ( doubleclone , indent = <NUM_LIT:2> ) ) <EOL> f . write ( "<STR_LIT:\n>" ) <EOL> os . rename ( tfn , fn ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> all_maps ( ) </s>
<s> import calendar <EOL> from collections import namedtuple <EOL> import hashlib <EOL> import simplejson as json <EOL> import time <EOL> from logbook import Logger <EOL> import classifier <EOL> import redis_util <EOL> log = Logger ( '<STR_LIT>' ) <EOL> TSTuple = namedtuple ( "<STR_LIT>" , ( "<STR_LIT>" , "<STR_LIT:count>" ) ) <EOL> SECOND = <NUM_LIT:1> <EOL> MINUTE = <NUM_LIT> <EOL> HOUR = MINUTE * <NUM_LIT> <EOL> DAY = HOUR * <NUM_LIT> <EOL> WEEK = DAY * <NUM_LIT:7> <EOL> TIME_SLICES = { <EOL> "<STR_LIT>" : SECOND , "<STR_LIT>" : MINUTE , "<STR_LIT>" : MINUTE * <NUM_LIT:5> , <EOL> "<STR_LIT>" : MINUTE * <NUM_LIT:10> , "<STR_LIT>" : MINUTE * <NUM_LIT:15> , <EOL> "<STR_LIT>" : MINUTE * <NUM_LIT:30> , "<STR_LIT>" : HOUR , "<STR_LIT>" : HOUR * <NUM_LIT:3> , <EOL> "<STR_LIT>" : HOUR * <NUM_LIT:6> , "<STR_LIT>" : HOUR * <NUM_LIT:12> , "<STR_LIT>" : DAY , <EOL> "<STR_LIT>" : WEEK <EOL> } <EOL> class TimeSeries ( object ) : <EOL> def __init__ ( self , redis_conn , cat_id ) : <EOL> """<STR_LIT>""" <EOL> self . cat_id = cat_id <EOL> self . redis_conn = redis_conn <EOL> def convert_ts_list ( self , ts_list , time_slice = None ) : <EOL> """<STR_LIT>""" <EOL> ret = [ ] <EOL> slice_dict = { } <EOL> if time_slice is None : <EOL> time_slice = "<STR_LIT>" <EOL> time_slice = TIME_SLICES [ time_slice ] <EOL> if not ts_list : <EOL> return [ ] <EOL> for ts_entry in ts_list : <EOL> ts = int ( ts_entry [ <NUM_LIT:1> ] ) <EOL> count = int ( ts_entry [ <NUM_LIT:0> ] . split ( "<STR_LIT::>" ) [ <NUM_LIT:1> ] ) <EOL> key = ts / time_slice <EOL> slice_dict [ key ] = slice_dict . get ( key , <NUM_LIT:0> ) + count <EOL> keys = slice_dict . keys ( ) <EOL> keys . sort ( ) <EOL> for i in range ( keys [ <NUM_LIT:0> ] , keys [ - <NUM_LIT:1> ] ) : <EOL> if i not in slice_dict : <EOL> slice_dict [ i ] = <NUM_LIT:0> <EOL> keys = slice_dict . keys ( ) <EOL> keys . sort ( ) <EOL> for key in keys : <EOL> ret . append ( TSTuple ( key * time_slice , slice_dict [ key ] ) ) <EOL> return ret <EOL> def all ( self , time_slice = None ) : <EOL> """<STR_LIT>""" <EOL> return self . convert_ts_list ( <EOL> self . redis_conn . zrange ( <EOL> "<STR_LIT>" % ( self . cat_id ) , <NUM_LIT:0> , - <NUM_LIT:1> , withscores = True <EOL> ) , time_slice <EOL> ) <EOL> def range ( self , start , end , time_slice = None ) : <EOL> """<STR_LIT>""" <EOL> return self . convert_ts_list ( <EOL> self . redis_conn . zrevrangebyscore ( <EOL> "<STR_LIT>" % ( self . cat_id ) , end , start , withscores = True <EOL> ) , <EOL> time_slice <EOL> ) <EOL> @ staticmethod <EOL> def generate_ts_value ( ts , count ) : <EOL> """<STR_LIT>""" <EOL> return "<STR_LIT>" % ( ts , count ) <EOL> def archive_cat_counts ( self , start_time , preserve = True ) : <EOL> """<STR_LIT>""" <EOL> ts_key = '<STR_LIT>' % ( self . cat_id , ) <EOL> counter_key = '<STR_LIT>' % ( self . cat_id , ) <EOL> check_mark = calendar . timegm ( start_time . timetuple ( ) ) <EOL> now = calendar . timegm ( time . gmtime ( ) ) <EOL> counters_to_delete = [ ] <EOL> count_dict = self . redis_conn . hgetall ( counter_key ) <EOL> interesting_ts = [ <EOL> x for x in count_dict if int ( x ) < check_mark <EOL> ] <EOL> for ts in interesting_ts : <EOL> if ts == now : <EOL> continue <EOL> new_value = count_dict [ ts ] <EOL> if preserve : <EOL> existing_entry = self . range ( ts , ts ) <EOL> if existing_entry : <EOL> new_value += existing_entry [ <NUM_LIT:0> ] . count <EOL> self . redis_conn . zadd ( <EOL> ts_key , self . generate_ts_value ( ts , new_value ) , ts <EOL> ) <EOL> counters_to_delete . append ( ts ) <EOL> for counter in counters_to_delete : <EOL> self . redis_conn . hdel ( counter_key , counter ) <EOL> class Events ( object ) : <EOL> def __init__ ( self , redis_conn , cat_id ) : <EOL> self . cat_id = cat_id <EOL> self . redis_conn = redis_conn <EOL> def add_event ( self , event , timestamp = None , <EOL> event_increment = True , ts_increment = True ) : <EOL> """<STR_LIT>""" <EOL> if timestamp is None : <EOL> timestamp = int ( time . time ( ) ) <EOL> event [ '<STR_LIT>' ] = timestamp <EOL> if event_increment : <EOL> self . redis_conn . zadd ( "<STR_LIT>" + self . cat_id , json . dumps ( event ) , timestamp ) <EOL> if ts_increment : <EOL> self . redis_conn . hincrby ( "<STR_LIT>" + self . cat_id , timestamp , <NUM_LIT:1> ) <EOL> def get_recent ( self , num_events ) : <EOL> """<STR_LIT>""" <EOL> return self . range ( int ( num_events ) . __neg__ ( ) , - <NUM_LIT:1> ) <EOL> def recent_signatures ( self , num_sigs ) : <EOL> """<STR_LIT>""" <EOL> events = self . get_recent ( num_sigs ) <EOL> return [ json . loads ( event ) [ '<STR_LIT>' ] for event in events ] <EOL> def range ( self , start , end ) : <EOL> """<STR_LIT>""" <EOL> return self . redis_conn . zrange ( "<STR_LIT>" % ( self . cat_id , ) , start , end ) <EOL> def _backfill_timeseries ( self , delete = False ) : <EOL> """<STR_LIT>""" <EOL> events = self . redis_conn . zrange ( <EOL> "<STR_LIT>" % self . cat_id , <NUM_LIT:0> , - <NUM_LIT:1> , withscores = True ) <EOL> cat_counter_id = "<STR_LIT>" % ( self . cat_id , ) <EOL> cat_ts_id = "<STR_LIT>" % ( self . cat_id , ) <EOL> if delete : <EOL> self . redis_conn . delete ( cat_ts_id ) <EOL> for _sig , ts in events : <EOL> self . redis_conn . hincrby ( cat_counter_id , int ( ts ) , <NUM_LIT:1> ) <EOL> def delete ( self ) : <EOL> """<STR_LIT>""" <EOL> self . redis_conn . delete ( "<STR_LIT>" % self . cat_id ) <EOL> class Category ( object ) : <EOL> """<STR_LIT>""" <EOL> CAT_META_HASH = "<STR_LIT>" <EOL> SIGNATURE_KEY = "<STR_LIT>" <EOL> HUMAN_NAME_KEY = "<STR_LIT>" <EOL> THRESHOLD_KEY = "<STR_LIT>" <EOL> STDEV_KEY = "<STR_LIT>" <EOL> MEAN_KEY = "<STR_LIT>" <EOL> RE_KEY = "<STR_LIT>" <EOL> keys = [ <EOL> CAT_META_HASH , SIGNATURE_KEY , HUMAN_NAME_KEY , THRESHOLD_KEY , <EOL> STDEV_KEY , MEAN_KEY , RE_KEY <EOL> ] <EOL> def __init__ ( self , redis_conn , signature = None , cat_id = None , event = None ) : <EOL> """<STR_LIT>""" <EOL> self . conn = redis_conn <EOL> if signature : <EOL> self . cat_id = redis_util . Redis . construct_cat_id ( signature ) <EOL> elif cat_id : <EOL> self . cat_id = cat_id <EOL> else : <EOL> self . cat_id = None <EOL> self . timeseries , self . events = None , None <EOL> if self . cat_id : <EOL> self . timeseries = TimeSeries ( self . conn , self . cat_id ) <EOL> self . events = Events ( self . conn , self . cat_id ) <EOL> if event and self . events : <EOL> self . events . add_event ( event ) <EOL> def to_dict ( self , num_recent = <NUM_LIT:5> ) : <EOL> """<STR_LIT>""" <EOL> return { <EOL> self . SIGNATURE_KEY : self . signature , <EOL> self . HUMAN_NAME_KEY : self . human_name , <EOL> self . THRESHOLD_KEY : self . threshold , <EOL> "<STR_LIT>" : self . events . recent_signatures ( num_recent ) <EOL> } <EOL> def recategorise ( self , default_threshold , archive_time = None ) : <EOL> """<STR_LIT>""" <EOL> for key in self . keys : <EOL> self . conn . hdel ( self . CAT_META_HASH , "<STR_LIT>" % ( self . cat_id , key ) ) <EOL> comp = classifier . Levenshtein ( ) <EOL> event_chunk = <NUM_LIT:1000> <EOL> curr_count = <NUM_LIT:0> <EOL> while <NUM_LIT:1> : <EOL> events = self . events . range ( curr_count , ( curr_count + event_chunk - <NUM_LIT:1> ) ) <EOL> if not events : <EOL> break <EOL> for event in events : <EOL> event_dict = json . loads ( event ) <EOL> self . classify ( self . conn , comp , event_dict , default_threshold ) <EOL> curr_count += event_chunk <EOL> if archive_time : <EOL> for cat in self . get_all_categories ( self . conn ) : <EOL> cat . timeseries . archive_cat_counts ( archive_time ) <EOL> self . events . delete ( ) <EOL> self . conn . delete ( "<STR_LIT>" % self . cat_id ) <EOL> self . conn . delete ( "<STR_LIT>" % self . cat_id ) <EOL> @ classmethod <EOL> def classify ( cls , queue , classifiers , error , threshold ) : <EOL> """<STR_LIT>""" <EOL> categories = cls . get_all_categories ( queue ) <EOL> matched_cat = None <EOL> start = time . time ( ) <EOL> for classifier in classifiers : <EOL> matched = False <EOL> for cat in categories : <EOL> if classifier . check_message ( cat , error , threshold ) : <EOL> cat . events . add_event ( error ) <EOL> matched_cat = cat <EOL> matched = True <EOL> break <EOL> if matched : <EOL> break <EOL> else : <EOL> cat_sig = error [ '<STR_LIT>' ] <EOL> matched_cat = cls . create ( queue , cat_sig , event = error ) <EOL> end = time . time ( ) <EOL> log . info ( '<STR_LIT>' % ( <EOL> end - start , matched_cat . cat_id ) ) <EOL> return matched_cat <EOL> @ classmethod <EOL> def create ( cls , redis_conn , signature , event = None ) : <EOL> """<STR_LIT>""" <EOL> redis_conn . zadd ( "<STR_LIT>" , signature , <NUM_LIT:0> ) <EOL> cat_id = cls . construct_cat_id ( signature ) <EOL> cat_fields = ( <EOL> ( cls . SIGNATURE_KEY , signature ) , ( cls . HUMAN_NAME_KEY , cat_id ) , <EOL> ( cls . THRESHOLD_KEY , "<STR_LIT>" ) , <EOL> ) <EOL> for key , value in cat_fields : <EOL> redis_conn . hset ( cls . CAT_META_HASH , "<STR_LIT>" % ( cat_id , key ) , value ) <EOL> kwargs = { "<STR_LIT>" : cat_id } <EOL> if event : <EOL> kwargs [ "<STR_LIT>" ] = event <EOL> return cls ( redis_conn , ** kwargs ) <EOL> @ classmethod <EOL> def get_all_categories ( cls , redis_conn ) : <EOL> """<STR_LIT>""" <EOL> categories = [ ] <EOL> hash_map = redis_conn . hgetall ( cls . CAT_META_HASH ) <EOL> for key in hash_map : <EOL> if key . endswith ( cls . SIGNATURE_KEY ) : <EOL> categories . append ( cls ( <EOL> redis_conn , <EOL> cat_id = key . replace ( "<STR_LIT::>" + cls . SIGNATURE_KEY , "<STR_LIT>" ) <EOL> ) ) <EOL> return categories <EOL> @ staticmethod <EOL> def construct_cat_id ( signature ) : <EOL> """<STR_LIT>""" <EOL> cat_id = hashlib . sha1 ( ) <EOL> cat_id . update ( signature ) <EOL> return cat_id . hexdigest ( ) <EOL> def _get_key ( self , key ) : <EOL> return self . conn . hget ( <EOL> self . CAT_META_HASH , "<STR_LIT>" % ( self . cat_id , key ) <EOL> ) <EOL> def _set_key ( self , key , value ) : <EOL> return self . conn . hset ( <EOL> self . CAT_META_HASH , "<STR_LIT>" % ( self . cat_id , key ) , value <EOL> ) <EOL> def _get_signature ( self ) : <EOL> return self . _get_key ( self . SIGNATURE_KEY ) <EOL> def _set_signature ( self , value ) : <EOL> return self . _set_key ( self . SIGNATURE_KEY , value ) <EOL> signature = property ( _get_signature , _set_signature ) <EOL> def _get_human ( self ) : <EOL> return self . _get_key ( self . HUMAN_NAME_KEY ) <EOL> def _set_human ( self , value ) : <EOL> return self . _set_key ( self . HUMAN_NAME_KEY , value ) <EOL> human_name = property ( _get_human , _set_human ) <EOL> def _get_threshold ( self ) : <EOL> return self . _get_key ( self . THRESHOLD_KEY ) <EOL> def _set_threshold ( self , value ) : <EOL> return self . _set_key ( self . THRESHOLD_KEY , value ) <EOL> threshold = property ( _get_threshold , _set_threshold ) <EOL> def _get_stdev ( self ) : <EOL> return self . _get_key ( self . STDEV_KEY ) <EOL> def _set_stdev ( self , value ) : <EOL> return self . _set_key ( self . STDEV_KEY ) <EOL> stdev = property ( _get_stdev , _set_stdev ) <EOL> def _get_mean ( self ) : <EOL> return self . _get_key ( self . MEAN_KEY ) <EOL> def _set_mean ( self , value ) : <EOL> return self . _set_key ( self . MEAN_KEY , value ) <EOL> mean = property ( _get_mean , _set_mean ) <EOL> def _get_regex ( self ) : <EOL> return self . _get_key ( self . RE_KEY ) <EOL> def _set_regex ( self , value ) : <EOL> return self . _set_key ( self . RE_KEY , value ) <EOL> regex = property ( _get_regex , _set_regex ) </s>
<s> """<STR_LIT>""" <EOL> import contextlib <EOL> import logging <EOL> import uuid <EOL> from consulate . api import base <EOL> from consulate import utils , exceptions <EOL> LOGGER = logging . getLogger ( __name__ ) <EOL> class Lock ( base . Endpoint ) : <EOL> """<STR_LIT>""" <EOL> DEFAULT_PREFIX = '<STR_LIT>' <EOL> def __init__ ( self , uri , adapter , session , datacenter = None , token = None ) : <EOL> """<STR_LIT>""" <EOL> super ( Lock , self ) . __init__ ( uri , adapter , datacenter , token ) <EOL> self . _base_uri = '<STR_LIT>' . format ( uri ) <EOL> self . _session = session <EOL> self . _session_id = None <EOL> self . _item = str ( uuid . uuid4 ( ) ) <EOL> self . _prefix = self . DEFAULT_PREFIX <EOL> @ contextlib . contextmanager <EOL> def acquire ( self , key = None , value = None ) : <EOL> """<STR_LIT>""" <EOL> self . _acquire ( key , value ) <EOL> yield <EOL> self . _release ( ) <EOL> @ property <EOL> def key ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _item <EOL> def prefix ( self , value ) : <EOL> """<STR_LIT>""" <EOL> self . _prefix = value or '<STR_LIT>' <EOL> def _acquire ( self , key = None , value = None ) : <EOL> self . _session_id = self . _session . create ( ) <EOL> self . _item = '<STR_LIT:/>' . join ( [ self . _prefix , ( key or str ( uuid . uuid4 ( ) ) ) ] ) <EOL> LOGGER . debug ( '<STR_LIT>' , <EOL> self . _item , self . _session_id ) <EOL> response = self . _put_response_body ( [ self . _item ] , <EOL> { '<STR_LIT>' : self . _session_id } , <EOL> value ) <EOL> if not response : <EOL> self . _session . destroy ( self . _session_id ) <EOL> raise exceptions . LockFailure ( ) <EOL> def _release ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _put_response_body ( [ self . _item ] , { '<STR_LIT>' : self . _session_id } ) <EOL> self . _adapter . delete ( self . _build_uri ( [ self . _item ] ) ) <EOL> self . _session . destroy ( self . _session_id ) <EOL> self . _item , self . _session_id = None , None </s>
<s> import sys <EOL> import os <EOL> sys . path . insert ( <NUM_LIT:0> , '<STR_LIT:..>' ) <EOL> extensions = [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] <EOL> templates_path = [ '<STR_LIT>' ] <EOL> source_suffix = '<STR_LIT>' <EOL> master_doc = '<STR_LIT:index>' <EOL> project = u'<STR_LIT>' <EOL> copyright = u'<STR_LIT>' <EOL> import hockeyapp <EOL> release = hockeyapp . __version__ <EOL> version = '<STR_LIT:.>' . join ( release . split ( '<STR_LIT:.>' ) [ <NUM_LIT:0> : <NUM_LIT:1> ] ) <EOL> exclude_patterns = [ '<STR_LIT>' ] <EOL> pygments_style = '<STR_LIT>' <EOL> html_theme = '<STR_LIT:default>' <EOL> html_static_path = [ '<STR_LIT>' ] <EOL> htmlhelp_basename = '<STR_LIT>' <EOL> latex_elements = { <EOL> } <EOL> latex_documents = [ <EOL> ( '<STR_LIT:index>' , '<STR_LIT>' , u'<STR_LIT>' , <EOL> u'<STR_LIT>' , '<STR_LIT>' ) , <EOL> ] <EOL> man_pages = [ <EOL> ( '<STR_LIT:index>' , '<STR_LIT>' , u'<STR_LIT>' , <EOL> [ u'<STR_LIT>' ] , <NUM_LIT:1> ) <EOL> ] <EOL> texinfo_documents = [ <EOL> ( '<STR_LIT:index>' , '<STR_LIT>' , u'<STR_LIT>' , <EOL> u'<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' ) , <EOL> ] <EOL> intersphinx_mapping = { '<STR_LIT>' : None } </s>
<s> import mredis <EOL> import time <EOL> ports = [ <NUM_LIT> , <NUM_LIT> ] <EOL> servers = [ ] <EOL> for port in ports : <EOL> servers . append ( { '<STR_LIT:host>' : '<STR_LIT:localhost>' , '<STR_LIT:port>' : port , '<STR_LIT>' : <NUM_LIT:0> } ) <EOL> mr = mredis . MRedis ( servers ) <EOL> print mr . ping ( ) <EOL> keys = set ( ) <EOL> for x in xrange ( <NUM_LIT:0> , <NUM_LIT:100> ) : <EOL> key = '<STR_LIT>' % time . time ( ) <EOL> keys . add ( key ) <EOL> for key in keys : <EOL> mr . set ( key , time . time ( ) ) <EOL> fetched = mr . keys ( '<STR_LIT>' ) <EOL> results = [ ] <EOL> for server in fetched : <EOL> for key in fetched [ server ] : <EOL> results . append ( '<STR_LIT>' % ( key , mr . get ( key ) ) ) <EOL> print '<STR_LIT>' % len ( results ) <EOL> for key in keys : <EOL> mr . delete ( key ) <EOL> print mr . bgrewriteaof ( ) <EOL> print mr . dbsize ( ) <EOL> print mr . lastsave ( ) <EOL> print mr . randomkey ( ) </s>
<s> """<STR_LIT>""" <EOL> import mock <EOL> try : <EOL> import unittest2 as unittest <EOL> except ImportError : <EOL> import unittest <EOL> from rabbitpy import channel <EOL> from rabbitpy import exceptions <EOL> class ServerCapabilitiesTest ( unittest . TestCase ) : <EOL> def setUp ( self ) : <EOL> self . chan = channel . Channel ( <NUM_LIT:1> , { } , None , None , None , None , <NUM_LIT> , None ) <EOL> def test_basic_nack_disabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = False <EOL> self . assertFalse ( self . chan . _supports_basic_nack ) <EOL> def test_basic_nack_enabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = True <EOL> self . assertTrue ( self . chan . _supports_basic_nack ) <EOL> def test_consumer_cancel_notify_disabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = False <EOL> self . assertFalse ( self . chan . _supports_consumer_cancel_notify ) <EOL> def test_consumer_cancel_notify_enabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = True <EOL> self . assertTrue ( self . chan . _supports_consumer_cancel_notify ) <EOL> def test_consumer_priorities_disabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = False <EOL> self . assertFalse ( self . chan . _supports_consumer_priorities ) <EOL> def test_consumer_priorities_enabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = True <EOL> self . assertTrue ( self . chan . _supports_consumer_priorities ) <EOL> def test_per_consumer_qos_disabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = False <EOL> self . assertFalse ( self . chan . _supports_per_consumer_qos ) <EOL> def test_per_consumer_qos_enabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = True <EOL> self . assertTrue ( self . chan . _supports_per_consumer_qos ) <EOL> def test_publisher_confirms_disabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = False <EOL> self . assertFalse ( self . chan . _supports_publisher_confirms ) <EOL> def test_publisher_confirms_enabled ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = True <EOL> self . assertTrue ( self . chan . _supports_publisher_confirms ) <EOL> def test_invoking_consume_raises ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = False <EOL> self . assertRaises ( exceptions . NotSupportedError , <EOL> self . chan . _consume , self , True , <NUM_LIT:100> ) <EOL> def test_invoking_basic_nack_raises ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = False <EOL> self . assertRaises ( exceptions . NotSupportedError , <EOL> self . chan . _multi_nack , <NUM_LIT:100> ) <EOL> def test_invoking_enable_publisher_confirms_raises ( self ) : <EOL> self . chan . _server_capabilities [ b'<STR_LIT>' ] = False <EOL> self . assertRaises ( exceptions . NotSupportedError , <EOL> self . chan . enable_publisher_confirms ) </s>
<s> """<STR_LIT>""" <EOL> import mock <EOL> try : <EOL> import unittest2 as unittest <EOL> except ImportError : <EOL> import unittest <EOL> from rejected import state <EOL> class TestState ( unittest . TestCase ) : <EOL> def setUp ( self ) : <EOL> self . _obj = state . State ( ) <EOL> def test_set_state_invalid_value ( self ) : <EOL> self . assertRaises ( ValueError , self . _obj . set_state , <NUM_LIT> ) <EOL> def test_set_state_expected_assignment ( self ) : <EOL> self . state = self . _obj . STATE_IDLE <EOL> self . _obj . set_state ( self . _obj . STATE_CONNECTING ) <EOL> self . assertEqual ( self . _obj . state , self . _obj . STATE_CONNECTING ) <EOL> def test_set_state_state_start ( self ) : <EOL> self . state = self . _obj . STATE_IDLE <EOL> value = <NUM_LIT> <EOL> with mock . patch ( '<STR_LIT>' , return_value = value ) : <EOL> self . _obj . set_state ( self . _obj . STATE_CONNECTING ) <EOL> self . assertEqual ( self . _obj . state_start , value ) <EOL> def test_state_initializing_desc ( self ) : <EOL> self . _obj . state = self . _obj . STATE_INITIALIZING <EOL> self . assertEqual ( self . _obj . state_description , <EOL> self . _obj . STATES [ self . _obj . STATE_INITIALIZING ] ) <EOL> def test_state_connecting_desc ( self ) : <EOL> self . _obj . state = self . _obj . STATE_CONNECTING <EOL> self . assertEqual ( self . _obj . state_description , <EOL> self . _obj . STATES [ self . _obj . STATE_CONNECTING ] ) <EOL> def test_state_idle_desc ( self ) : <EOL> self . _obj . state = self . _obj . STATE_IDLE <EOL> self . assertEqual ( self . _obj . state_description , <EOL> self . _obj . STATES [ self . _obj . STATE_IDLE ] ) <EOL> def test_state_active_desc ( self ) : <EOL> self . _obj . state = self . _obj . STATE_ACTIVE <EOL> self . assertEqual ( self . _obj . state_description , <EOL> self . _obj . STATES [ self . _obj . STATE_ACTIVE ] ) <EOL> def test_state_stop_requested_desc ( self ) : <EOL> self . _obj . state = self . _obj . STATE_STOP_REQUESTED <EOL> self . assertEqual ( self . _obj . state_description , <EOL> self . _obj . STATES [ self . _obj . STATE_STOP_REQUESTED ] ) <EOL> def test_state_shutting_down_desc ( self ) : <EOL> self . _obj . state = self . _obj . STATE_SHUTTING_DOWN <EOL> self . assertEqual ( self . _obj . state_description , <EOL> self . _obj . STATES [ self . _obj . STATE_SHUTTING_DOWN ] ) <EOL> def test_state_stopped_desc ( self ) : <EOL> self . _obj . state = self . _obj . STATE_STOPPED <EOL> self . assertEqual ( self . _obj . state_description , <EOL> self . _obj . STATES [ self . _obj . STATE_STOPPED ] ) <EOL> def test_is_idle_state_initializing ( self ) : <EOL> self . _obj . state = self . _obj . STATE_INITIALIZING <EOL> self . assertFalse ( self . _obj . is_idle ) <EOL> def test_is_idle_state_connecting ( self ) : <EOL> self . _obj . state = self . _obj . STATE_CONNECTING <EOL> self . assertFalse ( self . _obj . is_idle ) <EOL> def test_is_idle_state_idle ( self ) : <EOL> self . _obj . state = self . _obj . STATE_IDLE <EOL> self . assertTrue ( self . _obj . is_idle ) <EOL> def test_is_idle_state_processing ( self ) : <EOL> self . _obj . state = self . _obj . STATE_ACTIVE <EOL> self . assertFalse ( self . _obj . is_idle ) <EOL> def test_is_idle_state_stop_requested ( self ) : <EOL> self . _obj . state = self . _obj . STATE_STOP_REQUESTED <EOL> self . assertFalse ( self . _obj . is_idle ) <EOL> def test_is_idle_state_shutting_down ( self ) : <EOL> self . _obj . state = self . _obj . STATE_SHUTTING_DOWN <EOL> self . assertFalse ( self . _obj . is_idle ) <EOL> def test_is_idle_state_stopped ( self ) : <EOL> self . _obj . state = self . _obj . STATE_STOPPED <EOL> self . assertFalse ( self . _obj . is_idle ) <EOL> def test_is_running_state_initializing ( self ) : <EOL> self . _obj . state = self . _obj . STATE_INITIALIZING <EOL> self . assertFalse ( self . _obj . is_running ) <EOL> def test_is_running_state_connecting ( self ) : <EOL> self . _obj . state = self . _obj . STATE_CONNECTING <EOL> self . assertFalse ( self . _obj . is_running ) <EOL> def test_is_running_state_idle ( self ) : <EOL> self . _obj . state = self . _obj . STATE_IDLE <EOL> self . assertTrue ( self . _obj . is_running ) <EOL> def test_is_running_state_processing ( self ) : <EOL> self . _obj . state = self . _obj . STATE_ACTIVE <EOL> self . assertTrue ( self . _obj . is_running ) <EOL> def test_is_running_state_stop_requested ( self ) : <EOL> self . _obj . state = self . _obj . STATE_STOP_REQUESTED <EOL> self . assertFalse ( self . _obj . is_running ) <EOL> def test_is_running_state_shutting_down ( self ) : <EOL> self . _obj . state = self . _obj . STATE_SHUTTING_DOWN <EOL> self . assertFalse ( self . _obj . is_running ) <EOL> def test_is_running_state_stopped ( self ) : <EOL> self . _obj . state = self . _obj . STATE_STOPPED <EOL> self . assertFalse ( self . _obj . is_running ) <EOL> def test_is_shutting_down_state_initializing ( self ) : <EOL> self . _obj . state = self . _obj . STATE_INITIALIZING <EOL> self . assertFalse ( self . _obj . is_shutting_down ) <EOL> def test_is_shutting_down_state_connecting ( self ) : <EOL> self . _obj . state = self . _obj . STATE_CONNECTING <EOL> self . assertFalse ( self . _obj . is_shutting_down ) <EOL> def test_is_shutting_down_state_idle ( self ) : <EOL> self . _obj . state = self . _obj . STATE_IDLE <EOL> self . assertFalse ( self . _obj . is_shutting_down ) <EOL> def test_is_shutting_down_state_processing ( self ) : <EOL> self . _obj . state = self . _obj . STATE_ACTIVE <EOL> self . assertFalse ( self . _obj . is_shutting_down ) <EOL> def test_is_shutting_down_state_stop_requested ( self ) : <EOL> self . _obj . state = self . _obj . STATE_STOP_REQUESTED <EOL> self . assertFalse ( self . _obj . is_shutting_down ) <EOL> def test_is_shutting_down_state_shutting_down ( self ) : <EOL> self . _obj . state = self . _obj . STATE_SHUTTING_DOWN <EOL> self . assertTrue ( self . _obj . is_shutting_down ) <EOL> def test_is_shutting_down_state_stopped ( self ) : <EOL> self . _obj . state = self . _obj . STATE_STOPPED <EOL> self . assertFalse ( self . _obj . is_shutting_down ) <EOL> def test_is_stopped_state_initializing ( self ) : <EOL> self . _obj . state = self . _obj . STATE_INITIALIZING <EOL> self . assertFalse ( self . _obj . is_stopped ) <EOL> def test_is_stopped_state_connecting ( self ) : <EOL> self . _obj . state = self . _obj . STATE_CONNECTING <EOL> self . assertFalse ( self . _obj . is_stopped ) <EOL> def test_is_stopped_state_idle ( self ) : <EOL> self . _obj . state = self . _obj . STATE_IDLE <EOL> self . assertFalse ( self . _obj . is_stopped ) <EOL> def test_is_stopped_state_processing ( self ) : <EOL> self . _obj . state = self . _obj . STATE_ACTIVE <EOL> self . assertFalse ( self . _obj . is_stopped ) <EOL> def test_is_stopped_state_stop_requested ( self ) : <EOL> self . _obj . state = self . _obj . STATE_STOP_REQUESTED <EOL> self . assertFalse ( self . _obj . is_stopped ) <EOL> def test_is_stopped_state_shutting_down ( self ) : <EOL> self . _obj . state = self . _obj . STATE_SHUTTING_DOWN <EOL> self . assertFalse ( self . _obj . is_stopped ) </s>
<s> """<STR_LIT>""" <EOL> import warnings <EOL> warnings . warn ( '<STR_LIT>' , <EOL> DeprecationWarning , stacklevel = <NUM_LIT:2> ) <EOL> from tinman . handlers . base import SessionRequestHandler </s>
<s> """<STR_LIT>""" <EOL> class HashesMixin ( object ) : <EOL> """<STR_LIT>""" <EOL> pass </s>
<s> import numpy as np <EOL> import unittest <EOL> from pykernels . graph . shortestpath import ShortestPath <EOL> from pykernels . graph . basic import Graph <EOL> from graphutils import generate_testdata , generate_testanswers , generate_node_labels <EOL> __author__ = '<STR_LIT>' <EOL> """<STR_LIT>""" <EOL> class TestShortestPath ( unittest . TestCase ) : <EOL> def setUp ( self ) : <EOL> self . data = generate_testdata ( ) <EOL> self . answers_unlabeled = generate_testanswers ( '<STR_LIT>' ) <EOL> self . answers_labeled = generate_testanswers ( '<STR_LIT>' ) <EOL> labels = generate_node_labels ( ) <EOL> self . graphs = [ ] <EOL> for i , g_table in enumerate ( self . data ) : <EOL> current_data = [ ] <EOL> for j , g in enumerate ( g_table ) : <EOL> current_data . append ( Graph ( g , node_labels = labels [ i ] [ j ] ) ) <EOL> self . graphs . append ( current_data ) <EOL> def tearDown ( self ) : <EOL> pass <EOL> def testSPKernel ( self ) : <EOL> K = ShortestPath ( ) <EOL> for i , data in enumerate ( self . data ) : <EOL> self . assertTrue ( ( K . gram ( data ) == self . answers_unlabeled [ i ] ) . all ( ) ) <EOL> for i , data in enumerate ( self . graphs ) : <EOL> self . assertTrue ( ( K . gram ( data ) == self . answers_unlabeled [ i ] ) . all ( ) ) <EOL> def testLabeledSPKernel ( self ) : <EOL> K = ShortestPath ( labeled = True ) <EOL> for i , data in enumerate ( self . graphs ) : <EOL> self . assertTrue ( ( K . gram ( data ) == self . answers_labeled [ i ] ) . all ( ) ) </s>
<s> from sqlalchemy import schema as sa_schema , types as sqltypes , sql <EOL> import logging <EOL> from . . import compat <EOL> import re <EOL> from . . compat import string_types <EOL> log = logging . getLogger ( __name__ ) <EOL> try : <EOL> from sqlalchemy . sql . naming import conv <EOL> def _render_gen_name ( autogen_context , name ) : <EOL> if isinstance ( name , conv ) : <EOL> return _f_name ( _alembic_autogenerate_prefix ( autogen_context ) , name ) <EOL> else : <EOL> return name <EOL> except ImportError : <EOL> def _render_gen_name ( autogen_context , name ) : <EOL> return name <EOL> class _f_name ( object ) : <EOL> def __init__ ( self , prefix , name ) : <EOL> self . prefix = prefix <EOL> self . name = name <EOL> def __repr__ ( self ) : <EOL> return "<STR_LIT>" % ( self . prefix , self . name ) <EOL> def _render_potential_expr ( value , autogen_context ) : <EOL> if isinstance ( value , sql . ClauseElement ) : <EOL> if compat . sqla_08 : <EOL> compile_kw = dict ( compile_kwargs = { '<STR_LIT>' : True } ) <EOL> else : <EOL> compile_kw = { } <EOL> return "<STR_LIT>" % { <EOL> "<STR_LIT>" : _sqlalchemy_autogenerate_prefix ( autogen_context ) , <EOL> "<STR_LIT>" : str ( <EOL> value . compile ( dialect = autogen_context [ '<STR_LIT>' ] , <EOL> ** compile_kw ) <EOL> ) <EOL> } <EOL> else : <EOL> return repr ( value ) <EOL> def _add_table ( table , autogen_context ) : <EOL> text = "<STR_LIT>" % { <EOL> '<STR_LIT>' : table . name , <EOL> '<STR_LIT>' : _alembic_autogenerate_prefix ( autogen_context ) , <EOL> '<STR_LIT:args>' : '<STR_LIT>' . join ( <EOL> [ col for col in <EOL> [ _render_column ( col , autogen_context ) for col in table . c ] <EOL> if col ] + <EOL> sorted ( [ rcons for rcons in <EOL> [ _render_constraint ( cons , autogen_context ) for cons in <EOL> table . constraints ] <EOL> if rcons is not None <EOL> ] ) <EOL> ) <EOL> } <EOL> if table . schema : <EOL> text += "<STR_LIT>" % table . schema <EOL> for k in sorted ( table . kwargs ) : <EOL> text += "<STR_LIT>" % ( k . replace ( "<STR_LIT:U+0020>" , "<STR_LIT:_>" ) , table . kwargs [ k ] ) <EOL> text += "<STR_LIT>" <EOL> return text <EOL> def _drop_table ( table , autogen_context ) : <EOL> text = "<STR_LIT>" % { <EOL> "<STR_LIT>" : _alembic_autogenerate_prefix ( autogen_context ) , <EOL> "<STR_LIT>" : table . name <EOL> } <EOL> if table . schema : <EOL> text += "<STR_LIT>" % table . schema <EOL> text += "<STR_LIT:)>" <EOL> return text <EOL> def _add_index ( index , autogen_context ) : <EOL> """<STR_LIT>""" <EOL> from . compare import _get_index_column_names <EOL> text = "<STR_LIT>" "<STR_LIT>" % { <EOL> '<STR_LIT>' : _alembic_autogenerate_prefix ( autogen_context ) , <EOL> '<STR_LIT:name>' : _render_gen_name ( autogen_context , index . name ) , <EOL> '<STR_LIT>' : index . table . name , <EOL> '<STR_LIT>' : _get_index_column_names ( index ) , <EOL> '<STR_LIT>' : index . unique or False , <EOL> '<STR_LIT>' : ( "<STR_LIT>" % index . table . schema ) if index . table . schema else '<STR_LIT>' , <EOL> '<STR_LIT>' : ( '<STR_LIT:U+002CU+0020>' + '<STR_LIT:U+002CU+0020>' . join ( <EOL> [ "<STR_LIT>" % ( key , _render_potential_expr ( val , autogen_context ) ) <EOL> for key , val in index . kwargs . items ( ) ] ) ) if len ( index . kwargs ) else '<STR_LIT>' <EOL> } <EOL> return text <EOL> def _drop_index ( index , autogen_context ) : <EOL> """<STR_LIT>""" <EOL> text = "<STR_LIT>" "<STR_LIT>" % { <EOL> '<STR_LIT>' : _alembic_autogenerate_prefix ( autogen_context ) , <EOL> '<STR_LIT:name>' : _render_gen_name ( autogen_context , index . name ) , <EOL> '<STR_LIT>' : index . table . name , <EOL> '<STR_LIT>' : ( ( "<STR_LIT>" % index . table . schema ) <EOL> if index . table . schema else '<STR_LIT>' ) <EOL> } <EOL> return text <EOL> def _render_unique_constraint ( constraint , autogen_context ) : <EOL> rendered = _user_defined_render ( "<STR_LIT>" , constraint , autogen_context ) <EOL> if rendered is not False : <EOL> return rendered <EOL> return _uq_constraint ( constraint , autogen_context , False ) <EOL> def _add_unique_constraint ( constraint , autogen_context ) : <EOL> """<STR_LIT>""" <EOL> return _uq_constraint ( constraint , autogen_context , True ) <EOL> def _uq_constraint ( constraint , autogen_context , alter ) : <EOL> opts = [ ] <EOL> if constraint . deferrable : <EOL> opts . append ( ( "<STR_LIT>" , str ( constraint . deferrable ) ) ) <EOL> if constraint . initially : <EOL> opts . append ( ( "<STR_LIT>" , str ( constraint . initially ) ) ) <EOL> if alter and constraint . table . schema : <EOL> opts . append ( ( "<STR_LIT>" , str ( constraint . table . schema ) ) ) <EOL> if not alter and constraint . name : <EOL> opts . append ( ( "<STR_LIT:name>" , _render_gen_name ( autogen_context , constraint . name ) ) ) <EOL> if alter : <EOL> args = [ repr ( _render_gen_name ( autogen_context , constraint . name ) ) , <EOL> repr ( constraint . table . name ) ] <EOL> args . append ( repr ( [ col . name for col in constraint . columns ] ) ) <EOL> args . extend ( [ "<STR_LIT>" % ( k , v ) for k , v in opts ] ) <EOL> return "<STR_LIT>" % { <EOL> '<STR_LIT>' : _alembic_autogenerate_prefix ( autogen_context ) , <EOL> '<STR_LIT:args>' : "<STR_LIT:U+002CU+0020>" . join ( args ) <EOL> } <EOL> else : <EOL> args = [ repr ( col . name ) for col in constraint . columns ] <EOL> args . extend ( [ "<STR_LIT>" % ( k , v ) for k , v in opts ] ) <EOL> return "<STR_LIT>" % { <EOL> "<STR_LIT>" : _sqlalchemy_autogenerate_prefix ( autogen_context ) , <EOL> "<STR_LIT:args>" : "<STR_LIT:U+002CU+0020>" . join ( args ) <EOL> } <EOL> def _add_fk_constraint ( constraint , autogen_context ) : <EOL> raise NotImplementedError ( ) <EOL> def _add_pk_constraint ( constraint , autogen_context ) : <EOL> raise NotImplementedError ( ) <EOL> def _add_check_constraint ( constraint , autogen_context ) : <EOL> raise NotImplementedError ( ) <EOL> def _add_constraint ( constraint , autogen_context ) : <EOL> """<STR_LIT>""" <EOL> funcs = { <EOL> "<STR_LIT>" : _add_unique_constraint , <EOL> "<STR_LIT>" : _add_fk_constraint , <EOL> "<STR_LIT>" : _add_pk_constraint , <EOL> "<STR_LIT>" : _add_check_constraint , <EOL> "<STR_LIT>" : _add_check_constraint , <EOL> } <EOL> return funcs [ constraint . __visit_name__ ] ( constraint , autogen_context ) <EOL> def _drop_constraint ( constraint , autogen_context ) : <EOL> """<STR_LIT>""" <EOL> text = "<STR_LIT>" % { <EOL> '<STR_LIT>' : _alembic_autogenerate_prefix ( autogen_context ) , <EOL> '<STR_LIT:name>' : _render_gen_name ( autogen_context , constraint . name ) , <EOL> '<STR_LIT>' : constraint . table . name , <EOL> '<STR_LIT>' : ( "<STR_LIT>" % constraint . table . schema ) <EOL> if constraint . table . schema else '<STR_LIT>' , <EOL> } <EOL> return text <EOL> def _add_column ( schema , tname , column , autogen_context ) : <EOL> text = "<STR_LIT>" % { <EOL> "<STR_LIT>" : _alembic_autogenerate_prefix ( autogen_context ) , <EOL> "<STR_LIT>" : tname , <EOL> "<STR_LIT>" : _render_column ( column , autogen_context ) <EOL> } <EOL> if schema : <EOL> text += "<STR_LIT>" % schema <EOL> text += "<STR_LIT:)>" <EOL> return text <EOL> def _drop_column ( schema , tname , column , autogen_context ) : <EOL> text = "<STR_LIT>" % { <EOL> "<STR_LIT>" : _alembic_autogenerate_prefix ( autogen_context ) , <EOL> "<STR_LIT>" : tname , <EOL> "<STR_LIT>" : column . name <EOL> } <EOL> if schema : <EOL> text += "<STR_LIT>" % schema <EOL> text += "<STR_LIT:)>" <EOL> return text <EOL> def _modify_col ( tname , cname , <EOL> autogen_context , <EOL> server_default = False , <EOL> type_ = None , <EOL> nullable = None , <EOL> existing_type = None , <EOL> existing_nullable = None , <EOL> existing_server_default = False , <EOL> schema = None ) : <EOL> indent = "<STR_LIT:U+0020>" * <NUM_LIT:11> <EOL> text = "<STR_LIT>" % { <EOL> '<STR_LIT>' : _alembic_autogenerate_prefix ( <EOL> autogen_context ) , <EOL> '<STR_LIT>' : tname , <EOL> '<STR_LIT>' : cname } <EOL> text += "<STR_LIT>" % ( indent , <EOL> _repr_type ( existing_type , autogen_context ) ) <EOL> if server_default is not False : <EOL> rendered = _render_server_default ( <EOL> server_default , autogen_context ) <EOL> text += "<STR_LIT>" % ( indent , rendered ) <EOL> if type_ is not None : <EOL> text += "<STR_LIT>" % ( indent , <EOL> _repr_type ( type_ , autogen_context ) ) <EOL> if nullable is not None : <EOL> text += "<STR_LIT>" % ( <EOL> indent , nullable , ) <EOL> if existing_nullable is not None : <EOL> text += "<STR_LIT>" % ( <EOL> indent , existing_nullable ) <EOL> if existing_server_default : <EOL> rendered = _render_server_default ( <EOL> existing_server_default , <EOL> autogen_context ) <EOL> text += "<STR_LIT>" % ( <EOL> indent , rendered ) <EOL> if schema : <EOL> text += "<STR_LIT>" % ( indent , schema ) <EOL> text += "<STR_LIT:)>" <EOL> return text <EOL> def _user_autogenerate_prefix ( autogen_context ) : <EOL> prefix = autogen_context [ '<STR_LIT>' ] [ '<STR_LIT>' ] <EOL> if prefix is None : <EOL> return _sqlalchemy_autogenerate_prefix ( autogen_context ) <EOL> else : <EOL> return prefix <EOL> def _sqlalchemy_autogenerate_prefix ( autogen_context ) : <EOL> return autogen_context [ '<STR_LIT>' ] [ '<STR_LIT>' ] or '<STR_LIT>' <EOL> def _alembic_autogenerate_prefix ( autogen_context ) : <EOL> return autogen_context [ '<STR_LIT>' ] [ '<STR_LIT>' ] or '<STR_LIT>' <EOL> def _user_defined_render ( type_ , object_ , autogen_context ) : <EOL> if '<STR_LIT>' in autogen_context and '<STR_LIT>' in autogen_context [ '<STR_LIT>' ] : <EOL> render = autogen_context [ '<STR_LIT>' ] [ '<STR_LIT>' ] <EOL> if render : <EOL> rendered = render ( type_ , object_ , autogen_context ) <EOL> if rendered is not False : <EOL> return rendered <EOL> return False <EOL> def _render_column ( column , autogen_context ) : <EOL> rendered = _user_defined_render ( "<STR_LIT>" , column , autogen_context ) <EOL> if rendered is not False : <EOL> return rendered <EOL> opts = [ ] <EOL> if column . server_default : <EOL> rendered = _render_server_default ( <EOL> column . server_default , autogen_context <EOL> ) <EOL> if rendered : <EOL> opts . append ( ( "<STR_LIT>" , rendered ) ) <EOL> if not column . autoincrement : <EOL> opts . append ( ( "<STR_LIT>" , column . autoincrement ) ) <EOL> if column . nullable is not None : <EOL> opts . append ( ( "<STR_LIT>" , column . nullable ) ) <EOL> return "<STR_LIT>" % { <EOL> '<STR_LIT>' : _sqlalchemy_autogenerate_prefix ( autogen_context ) , <EOL> '<STR_LIT:name>' : column . name , <EOL> '<STR_LIT:type>' : _repr_type ( column . type , autogen_context ) , <EOL> '<STR_LIT>' : "<STR_LIT:U+002CU+0020>" . join ( [ "<STR_LIT>" % ( kwname , val ) for kwname , val in opts ] ) <EOL> } <EOL> def _render_server_default ( default , autogen_context ) : <EOL> rendered = _user_defined_render ( "<STR_LIT>" , default , autogen_context ) <EOL> if rendered is not False : <EOL> return rendered <EOL> if isinstance ( default , sa_schema . DefaultClause ) : <EOL> if isinstance ( default . arg , string_types ) : <EOL> default = default . arg <EOL> else : <EOL> default = str ( default . arg . compile ( <EOL> dialect = autogen_context [ '<STR_LIT>' ] ) ) <EOL> if isinstance ( default , string_types ) : <EOL> default = re . sub ( r"<STR_LIT>" , "<STR_LIT>" , default ) <EOL> return repr ( default ) <EOL> else : <EOL> return None <EOL> def _repr_type ( type_ , autogen_context ) : <EOL> rendered = _user_defined_render ( "<STR_LIT:type>" , type_ , autogen_context ) <EOL> if rendered is not False : <EOL> return rendered <EOL> mod = type ( type_ ) . __module__ <EOL> imports = autogen_context . get ( '<STR_LIT>' , None ) <EOL> if mod . startswith ( "<STR_LIT>" ) : <EOL> dname = re . match ( r"<STR_LIT>" , mod ) . group ( <NUM_LIT:1> ) <EOL> if imports is not None : <EOL> imports . add ( "<STR_LIT>" % dname ) <EOL> return "<STR_LIT>" % ( dname , type_ ) <EOL> elif mod . startswith ( "<STR_LIT>" ) : <EOL> prefix = _sqlalchemy_autogenerate_prefix ( autogen_context ) <EOL> return "<STR_LIT>" % ( prefix , type_ ) <EOL> else : <EOL> prefix = _user_autogenerate_prefix ( autogen_context ) <EOL> return "<STR_LIT>" % ( prefix , type_ ) <EOL> def _render_constraint ( constraint , autogen_context ) : <EOL> renderer = _constraint_renderers . get ( type ( constraint ) , None ) <EOL> if renderer : <EOL> return renderer ( constraint , autogen_context ) <EOL> else : <EOL> return None <EOL> def _render_primary_key ( constraint , autogen_context ) : <EOL> rendered = _user_defined_render ( "<STR_LIT:primary_key>" , constraint , autogen_context ) <EOL> if rendered is not False : <EOL> return rendered <EOL> if not constraint . columns : <EOL> return None <EOL> opts = [ ] <EOL> if constraint . name : <EOL> opts . append ( ( "<STR_LIT:name>" , repr ( _render_gen_name ( autogen_context , constraint . name ) ) ) ) <EOL> return "<STR_LIT>" % { <EOL> "<STR_LIT>" : _sqlalchemy_autogenerate_prefix ( autogen_context ) , <EOL> "<STR_LIT:args>" : "<STR_LIT:U+002CU+0020>" . join ( <EOL> [ repr ( c . key ) for c in constraint . columns ] + <EOL> [ "<STR_LIT>" % ( kwname , val ) for kwname , val in opts ] <EOL> ) , <EOL> } <EOL> def _fk_colspec ( fk , metadata_schema ) : <EOL> """<STR_LIT>""" <EOL> if metadata_schema is None : <EOL> return fk . _get_colspec ( ) <EOL> else : <EOL> tokens = fk . _colspec . split ( "<STR_LIT:.>" ) <EOL> if len ( tokens ) == <NUM_LIT:2> : <EOL> return "<STR_LIT>" % ( metadata_schema , fk . _colspec ) <EOL> else : <EOL> return fk . _colspec <EOL> def _render_foreign_key ( constraint , autogen_context ) : <EOL> rendered = _user_defined_render ( "<STR_LIT>" , constraint , autogen_context ) <EOL> if rendered is not False : <EOL> return rendered <EOL> opts = [ ] <EOL> if constraint . name : <EOL> opts . append ( ( "<STR_LIT:name>" , repr ( _render_gen_name ( autogen_context , constraint . name ) ) ) ) <EOL> if constraint . onupdate : <EOL> opts . append ( ( "<STR_LIT>" , repr ( constraint . onupdate ) ) ) <EOL> if constraint . ondelete : <EOL> opts . append ( ( "<STR_LIT>" , repr ( constraint . ondelete ) ) ) <EOL> if constraint . initially : <EOL> opts . append ( ( "<STR_LIT>" , repr ( constraint . initially ) ) ) <EOL> if constraint . deferrable : <EOL> opts . append ( ( "<STR_LIT>" , repr ( constraint . deferrable ) ) ) <EOL> if constraint . use_alter : <EOL> opts . append ( ( "<STR_LIT>" , repr ( constraint . use_alter ) ) ) <EOL> apply_metadata_schema = constraint . parent . metadata . schema <EOL> return "<STR_LIT>" "<STR_LIT>" % { <EOL> "<STR_LIT>" : _sqlalchemy_autogenerate_prefix ( autogen_context ) , <EOL> "<STR_LIT>" : "<STR_LIT:U+002CU+0020>" . join ( "<STR_LIT>" % f . parent . key for f in constraint . elements ) , <EOL> "<STR_LIT>" : "<STR_LIT:U+002CU+0020>" . join ( repr ( _fk_colspec ( f , apply_metadata_schema ) ) <EOL> for f in constraint . elements ) , <EOL> "<STR_LIT:args>" : "<STR_LIT:U+002CU+0020>" . join ( <EOL> [ "<STR_LIT>" % ( kwname , val ) for kwname , val in opts ] <EOL> ) , <EOL> } <EOL> def _render_check_constraint ( constraint , autogen_context ) : <EOL> rendered = _user_defined_render ( "<STR_LIT>" , constraint , autogen_context ) <EOL> if rendered is not False : <EOL> return rendered <EOL> if constraint . _create_rule and hasattr ( constraint . _create_rule , '<STR_LIT:target>' ) and isinstance ( constraint . _create_rule . target , <EOL> sqltypes . TypeEngine ) : <EOL> return None <EOL> opts = [ ] <EOL> if constraint . name : <EOL> opts . append ( ( "<STR_LIT:name>" , repr ( _render_gen_name ( autogen_context , constraint . name ) ) ) ) <EOL> return "<STR_LIT>" % { <EOL> "<STR_LIT>" : _sqlalchemy_autogenerate_prefix ( autogen_context ) , <EOL> "<STR_LIT>" : "<STR_LIT:U+002CU+0020>" + ( "<STR_LIT:U+002CU+0020>" . join ( "<STR_LIT>" % ( k , v ) <EOL> for k , v in opts ) ) if opts else "<STR_LIT>" , <EOL> "<STR_LIT>" : str ( <EOL> constraint . sqltext . compile ( <EOL> dialect = autogen_context [ '<STR_LIT>' ] <EOL> ) <EOL> ) <EOL> } <EOL> _constraint_renderers = { <EOL> sa_schema . PrimaryKeyConstraint : _render_primary_key , <EOL> sa_schema . ForeignKeyConstraint : _render_foreign_key , <EOL> sa_schema . UniqueConstraint : _render_unique_constraint , <EOL> sa_schema . CheckConstraint : _render_check_constraint <EOL> } </s>
<s> import warnings <EOL> try : <EOL> from paste . registry import StackedObjectProxy <EOL> beaker_session = StackedObjectProxy ( name = "<STR_LIT>" ) <EOL> beaker_cache = StackedObjectProxy ( name = "<STR_LIT>" ) <EOL> except : <EOL> beaker_cache = None <EOL> beaker_session = None <EOL> from beaker . cache import CacheManager <EOL> from beaker . session import Session , SessionObject <EOL> from beaker . util import coerce_cache_params , coerce_session_params , parse_cache_config_options <EOL> class CacheMiddleware ( object ) : <EOL> cache = beaker_cache <EOL> def __init__ ( self , app , config = None , environ_key = '<STR_LIT>' , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> self . app = app <EOL> config = config or { } <EOL> self . options = { } <EOL> self . options . update ( parse_cache_config_options ( config ) ) <EOL> self . options . update ( <EOL> parse_cache_config_options ( kwargs , include_defaults = False ) ) <EOL> if not self . options and config : <EOL> self . options = config <EOL> self . options . update ( kwargs ) <EOL> self . cache_manager = CacheManager ( ** self . options ) <EOL> self . environ_key = environ_key <EOL> def __call__ ( self , environ , start_response ) : <EOL> if environ . get ( '<STR_LIT>' ) : <EOL> if environ [ '<STR_LIT>' ] . reglist : <EOL> environ [ '<STR_LIT>' ] . register ( self . cache , <EOL> self . cache_manager ) <EOL> environ [ self . environ_key ] = self . cache_manager <EOL> return self . app ( environ , start_response ) <EOL> class SessionMiddleware ( object ) : <EOL> session = beaker_session <EOL> def __init__ ( self , wrap_app , config = None , environ_key = '<STR_LIT>' , <EOL> ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> config = config or { } <EOL> self . options = dict ( invalidate_corrupt = True , type = None , <EOL> data_dir = None , key = '<STR_LIT>' , <EOL> timeout = None , secret = None , log_file = None ) <EOL> for dct in [ config , kwargs ] : <EOL> for key , val in dct . iteritems ( ) : <EOL> if key . startswith ( '<STR_LIT>' ) : <EOL> self . options [ key [ <NUM_LIT:15> : ] ] = val <EOL> if key . startswith ( '<STR_LIT>' ) : <EOL> self . options [ key [ <NUM_LIT:8> : ] ] = val <EOL> if key . startswith ( '<STR_LIT>' ) : <EOL> warnings . warn ( '<STR_LIT>' <EOL> '<STR_LIT>' , DeprecationWarning , <NUM_LIT:2> ) <EOL> self . options [ key [ <NUM_LIT:8> : ] ] = val <EOL> coerce_session_params ( self . options ) <EOL> if not self . options and config : <EOL> self . options = config <EOL> self . options . update ( kwargs ) <EOL> self . wrap_app = self . app = wrap_app <EOL> self . environ_key = environ_key <EOL> def __call__ ( self , environ , start_response ) : <EOL> session = SessionObject ( environ , ** self . options ) <EOL> if environ . get ( '<STR_LIT>' ) : <EOL> if environ [ '<STR_LIT>' ] . reglist : <EOL> environ [ '<STR_LIT>' ] . register ( self . session , session ) <EOL> environ [ self . environ_key ] = session <EOL> environ [ '<STR_LIT>' ] = self . _get_session <EOL> if '<STR_LIT>' in environ and '<STR_LIT>' in self . options : <EOL> environ [ '<STR_LIT>' ] [ self . options [ '<STR_LIT>' ] ] = session <EOL> def session_start_response ( status , headers , exc_info = None ) : <EOL> if session . accessed ( ) : <EOL> session . persist ( ) <EOL> if session . __dict__ [ '<STR_LIT>' ] [ '<STR_LIT>' ] : <EOL> cookie = session . __dict__ [ '<STR_LIT>' ] [ '<STR_LIT>' ] <EOL> if cookie : <EOL> headers . append ( ( '<STR_LIT>' , cookie ) ) <EOL> return start_response ( status , headers , exc_info ) <EOL> return self . wrap_app ( environ , session_start_response ) <EOL> def _get_session ( self ) : <EOL> return Session ( { } , use_cookies = False , ** self . options ) <EOL> def session_filter_factory ( global_conf , ** kwargs ) : <EOL> def filter ( app ) : <EOL> return SessionMiddleware ( app , global_conf , ** kwargs ) <EOL> return filter <EOL> def session_filter_app_factory ( app , global_conf , ** kwargs ) : <EOL> return SessionMiddleware ( app , global_conf , ** kwargs ) </s>
<s> """<STR_LIT>""" <EOL> import re <EOL> from . mysqldb import MySQLDialect_mysqldb <EOL> from . base import ( BIT , MySQLDialect ) <EOL> from ... import util <EOL> class _cymysqlBIT ( BIT ) : <EOL> def result_processor ( self , dialect , coltype ) : <EOL> """<STR_LIT>""" <EOL> def process ( value ) : <EOL> if value is not None : <EOL> v = <NUM_LIT:0> <EOL> for i in util . iterbytes ( value ) : <EOL> v = v << <NUM_LIT:8> | i <EOL> return v <EOL> return value <EOL> return process <EOL> class MySQLDialect_cymysql ( MySQLDialect_mysqldb ) : <EOL> driver = '<STR_LIT>' <EOL> description_encoding = None <EOL> supports_sane_rowcount = True <EOL> supports_sane_multi_rowcount = False <EOL> supports_unicode_statements = True <EOL> colspecs = util . update_copy ( <EOL> MySQLDialect . colspecs , <EOL> { <EOL> BIT : _cymysqlBIT , <EOL> } <EOL> ) <EOL> @ classmethod <EOL> def dbapi ( cls ) : <EOL> return __import__ ( '<STR_LIT>' ) <EOL> def _get_server_version_info ( self , connection ) : <EOL> dbapi_con = connection . connection <EOL> version = [ ] <EOL> r = re . compile ( '<STR_LIT>' ) <EOL> for n in r . split ( dbapi_con . server_version ) : <EOL> try : <EOL> version . append ( int ( n ) ) <EOL> except ValueError : <EOL> version . append ( n ) <EOL> return tuple ( version ) <EOL> def _detect_charset ( self , connection ) : <EOL> return connection . connection . charset <EOL> def _extract_error_code ( self , exception ) : <EOL> return exception . errno <EOL> def is_disconnect ( self , e , connection , cursor ) : <EOL> if isinstance ( e , self . dbapi . OperationalError ) : <EOL> return self . _extract_error_code ( e ) in ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) <EOL> elif isinstance ( e , self . dbapi . InterfaceError ) : <EOL> return True <EOL> else : <EOL> return False <EOL> dialect = MySQLDialect_cymysql </s>
<s> from sqlalchemy . dialects . sybase import base , pysybase , pyodbc <EOL> base . dialect = pyodbc . dialect <EOL> from . base import CHAR , VARCHAR , TIME , NCHAR , NVARCHAR , TEXT , DATE , DATETIME , FLOAT , NUMERIC , BIGINT , INT , INTEGER , SMALLINT , BINARY , VARBINARY , UNITEXT , UNICHAR , UNIVARCHAR , IMAGE , BIT , MONEY , SMALLMONEY , TINYINT , dialect <EOL> __all__ = ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' <EOL> ) </s>
<s> """<STR_LIT>""" <EOL> from . api import declarative_base , synonym_for , comparable_using , instrument_declarative , ConcreteBase , AbstractConcreteBase , DeclarativeMeta , DeferredReflection , has_inherited_table , declared_attr , as_declarative <EOL> __all__ = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' ] </s>
<s> """<STR_LIT>""" <EOL> from __future__ import absolute_import <EOL> import types <EOL> import weakref <EOL> from itertools import chain <EOL> from collections import deque <EOL> from . . import sql , util , log , exc as sa_exc , event , schema , inspection <EOL> from . . sql import expression , visitors , operators , util as sql_util <EOL> from . import instrumentation , attributes , exc as orm_exc , loading <EOL> from . import properties <EOL> from . interfaces import MapperProperty , _InspectionAttr , _MappedAttribute <EOL> from . base import _class_to_mapper , _state_mapper , class_mapper , state_str , _INSTRUMENTOR <EOL> from . path_registry import PathRegistry <EOL> import sys <EOL> _mapper_registry = weakref . WeakKeyDictionary ( ) <EOL> _already_compiling = False <EOL> _memoized_configured_property = util . group_expirable_memoized_property ( ) <EOL> NO_ATTRIBUTE = util . symbol ( '<STR_LIT>' ) <EOL> _CONFIGURE_MUTEX = util . threading . RLock ( ) <EOL> @ inspection . _self_inspects <EOL> @ log . class_logger <EOL> class Mapper ( _InspectionAttr ) : <EOL> """<STR_LIT>""" <EOL> _new_mappers = False <EOL> def __init__ ( self , <EOL> class_ , <EOL> local_table = None , <EOL> properties = None , <EOL> primary_key = None , <EOL> non_primary = False , <EOL> inherits = None , <EOL> inherit_condition = None , <EOL> inherit_foreign_keys = None , <EOL> extension = None , <EOL> order_by = False , <EOL> always_refresh = False , <EOL> version_id_col = None , <EOL> version_id_generator = None , <EOL> polymorphic_on = None , <EOL> _polymorphic_map = None , <EOL> polymorphic_identity = None , <EOL> concrete = False , <EOL> with_polymorphic = None , <EOL> allow_partial_pks = True , <EOL> batch = True , <EOL> column_prefix = None , <EOL> include_properties = None , <EOL> exclude_properties = None , <EOL> passive_updates = True , <EOL> confirm_deleted_rows = True , <EOL> eager_defaults = False , <EOL> legacy_is_orphan = False , <EOL> _compiled_cache_size = <NUM_LIT:100> , <EOL> ) : <EOL> """<STR_LIT>""" <EOL> self . class_ = util . assert_arg_type ( class_ , type , '<STR_LIT>' ) <EOL> self . class_manager = None <EOL> self . _primary_key_argument = util . to_list ( primary_key ) <EOL> self . non_primary = non_primary <EOL> if order_by is not False : <EOL> self . order_by = util . to_list ( order_by ) <EOL> else : <EOL> self . order_by = order_by <EOL> self . always_refresh = always_refresh <EOL> if isinstance ( version_id_col , MapperProperty ) : <EOL> self . version_id_prop = version_id_col <EOL> self . version_id_col = None <EOL> else : <EOL> self . version_id_col = version_id_col <EOL> if version_id_generator is False : <EOL> self . version_id_generator = False <EOL> elif version_id_generator is None : <EOL> self . version_id_generator = lambda x : ( x or <NUM_LIT:0> ) + <NUM_LIT:1> <EOL> else : <EOL> self . version_id_generator = version_id_generator <EOL> self . concrete = concrete <EOL> self . single = False <EOL> self . inherits = inherits <EOL> self . local_table = local_table <EOL> self . inherit_condition = inherit_condition <EOL> self . inherit_foreign_keys = inherit_foreign_keys <EOL> self . _init_properties = properties or { } <EOL> self . _delete_orphans = [ ] <EOL> self . batch = batch <EOL> self . eager_defaults = eager_defaults <EOL> self . column_prefix = column_prefix <EOL> self . polymorphic_on = expression . _clause_element_as_expr ( <EOL> polymorphic_on ) <EOL> self . _dependency_processors = [ ] <EOL> self . validators = util . immutabledict ( ) <EOL> self . passive_updates = passive_updates <EOL> self . legacy_is_orphan = legacy_is_orphan <EOL> self . _clause_adapter = None <EOL> self . _requires_row_aliasing = False <EOL> self . _inherits_equated_pairs = None <EOL> self . _memoized_values = { } <EOL> self . _compiled_cache_size = _compiled_cache_size <EOL> self . _reconstructor = None <EOL> self . _deprecated_extensions = util . to_list ( extension or [ ] ) <EOL> self . allow_partial_pks = allow_partial_pks <EOL> if self . inherits and not self . concrete : <EOL> self . confirm_deleted_rows = False <EOL> else : <EOL> self . confirm_deleted_rows = confirm_deleted_rows <EOL> self . _set_with_polymorphic ( with_polymorphic ) <EOL> if isinstance ( self . local_table , expression . SelectBase ) : <EOL> raise sa_exc . InvalidRequestError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> ) <EOL> if self . with_polymorphic and isinstance ( self . with_polymorphic [ <NUM_LIT:1> ] , <EOL> expression . SelectBase ) : <EOL> self . with_polymorphic = ( self . with_polymorphic [ <NUM_LIT:0> ] , <EOL> self . with_polymorphic [ <NUM_LIT:1> ] . alias ( ) ) <EOL> self . polymorphic_identity = polymorphic_identity <EOL> if _polymorphic_map is None : <EOL> self . polymorphic_map = { } <EOL> else : <EOL> self . polymorphic_map = _polymorphic_map <EOL> if include_properties is not None : <EOL> self . include_properties = util . to_set ( include_properties ) <EOL> else : <EOL> self . include_properties = None <EOL> if exclude_properties : <EOL> self . exclude_properties = util . to_set ( exclude_properties ) <EOL> else : <EOL> self . exclude_properties = None <EOL> self . configured = False <EOL> _CONFIGURE_MUTEX . acquire ( ) <EOL> try : <EOL> self . dispatch . _events . _new_mapper_instance ( class_ , self ) <EOL> self . _configure_inheritance ( ) <EOL> self . _configure_legacy_instrument_class ( ) <EOL> self . _configure_class_instrumentation ( ) <EOL> self . _configure_listeners ( ) <EOL> self . _configure_properties ( ) <EOL> self . _configure_polymorphic_setter ( ) <EOL> self . _configure_pks ( ) <EOL> Mapper . _new_mappers = True <EOL> self . _log ( "<STR_LIT>" ) <EOL> self . _expire_memoizations ( ) <EOL> finally : <EOL> _CONFIGURE_MUTEX . release ( ) <EOL> is_mapper = True <EOL> """<STR_LIT>""" <EOL> @ property <EOL> def mapper ( self ) : <EOL> """<STR_LIT>""" <EOL> return self <EOL> @ property <EOL> def entity ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . class_ <EOL> local_table = None <EOL> """<STR_LIT>""" <EOL> mapped_table = None <EOL> """<STR_LIT>""" <EOL> inherits = None <EOL> """<STR_LIT>""" <EOL> configured = None <EOL> """<STR_LIT>""" <EOL> concrete = None <EOL> """<STR_LIT>""" <EOL> tables = None <EOL> """<STR_LIT>""" <EOL> primary_key = None <EOL> """<STR_LIT>""" <EOL> class_ = None <EOL> """<STR_LIT>""" <EOL> class_manager = None <EOL> """<STR_LIT>""" <EOL> single = None <EOL> """<STR_LIT>""" <EOL> non_primary = None <EOL> """<STR_LIT>""" <EOL> polymorphic_on = None <EOL> """<STR_LIT>""" <EOL> polymorphic_map = None <EOL> """<STR_LIT>""" <EOL> polymorphic_identity = None <EOL> """<STR_LIT>""" <EOL> base_mapper = None <EOL> """<STR_LIT>""" <EOL> columns = None <EOL> """<STR_LIT>""" <EOL> validators = None <EOL> """<STR_LIT>""" <EOL> c = None <EOL> """<STR_LIT>""" <EOL> @ util . memoized_property <EOL> def _path_registry ( self ) : <EOL> return PathRegistry . per_mapper ( self ) <EOL> def _configure_inheritance ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _inheriting_mappers = util . WeakSequence ( ) <EOL> if self . inherits : <EOL> if isinstance ( self . inherits , type ) : <EOL> self . inherits = class_mapper ( self . inherits , configure = False ) <EOL> if not issubclass ( self . class_ , self . inherits . class_ ) : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" % <EOL> ( self . class_ . __name__ , self . inherits . class_ . __name__ ) ) <EOL> if self . non_primary != self . inherits . non_primary : <EOL> np = not self . non_primary and "<STR_LIT>" or "<STR_LIT>" <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> ( np , self . class_ . __name__ , np ) ) <EOL> if self . local_table is None : <EOL> self . local_table = self . inherits . local_table <EOL> self . mapped_table = self . inherits . mapped_table <EOL> self . single = True <EOL> elif self . local_table is not self . inherits . local_table : <EOL> if self . concrete : <EOL> self . mapped_table = self . local_table <EOL> for mapper in self . iterate_to_root ( ) : <EOL> if mapper . polymorphic_on is not None : <EOL> mapper . _requires_row_aliasing = True <EOL> else : <EOL> if self . inherit_condition is None : <EOL> self . inherit_condition = sql_util . join_condition ( <EOL> self . inherits . local_table , <EOL> self . local_table ) <EOL> self . mapped_table = sql . join ( <EOL> self . inherits . mapped_table , <EOL> self . local_table , <EOL> self . inherit_condition ) <EOL> fks = util . to_set ( self . inherit_foreign_keys ) <EOL> self . _inherits_equated_pairs = sql_util . criterion_as_pairs ( <EOL> self . mapped_table . onclause , <EOL> consider_as_foreign_keys = fks ) <EOL> else : <EOL> self . mapped_table = self . local_table <EOL> if self . polymorphic_identity is not None and not self . concrete : <EOL> self . _identity_class = self . inherits . _identity_class <EOL> else : <EOL> self . _identity_class = self . class_ <EOL> if self . version_id_col is None : <EOL> self . version_id_col = self . inherits . version_id_col <EOL> self . version_id_generator = self . inherits . version_id_generator <EOL> elif self . inherits . version_id_col is not None and self . version_id_col is not self . inherits . version_id_col : <EOL> util . warn ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> ( self . version_id_col . description , <EOL> self . inherits . version_id_col . description ) <EOL> ) <EOL> if self . order_by is False and not self . concrete and self . inherits . order_by is not False : <EOL> self . order_by = self . inherits . order_by <EOL> self . polymorphic_map = self . inherits . polymorphic_map <EOL> self . batch = self . inherits . batch <EOL> self . inherits . _inheriting_mappers . append ( self ) <EOL> self . base_mapper = self . inherits . base_mapper <EOL> self . passive_updates = self . inherits . passive_updates <EOL> self . _all_tables = self . inherits . _all_tables <EOL> if self . polymorphic_identity is not None : <EOL> self . polymorphic_map [ self . polymorphic_identity ] = self <EOL> else : <EOL> self . _all_tables = set ( ) <EOL> self . base_mapper = self <EOL> self . mapped_table = self . local_table <EOL> if self . polymorphic_identity is not None : <EOL> self . polymorphic_map [ self . polymorphic_identity ] = self <EOL> self . _identity_class = self . class_ <EOL> if self . mapped_table is None : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> % self ) <EOL> def _set_with_polymorphic ( self , with_polymorphic ) : <EOL> if with_polymorphic == '<STR_LIT:*>' : <EOL> self . with_polymorphic = ( '<STR_LIT:*>' , None ) <EOL> elif isinstance ( with_polymorphic , ( tuple , list ) ) : <EOL> if isinstance ( <EOL> with_polymorphic [ <NUM_LIT:0> ] , util . string_types + ( tuple , list ) ) : <EOL> self . with_polymorphic = with_polymorphic <EOL> else : <EOL> self . with_polymorphic = ( with_polymorphic , None ) <EOL> elif with_polymorphic is not None : <EOL> raise sa_exc . ArgumentError ( "<STR_LIT>" ) <EOL> else : <EOL> self . with_polymorphic = None <EOL> if isinstance ( self . local_table , expression . SelectBase ) : <EOL> raise sa_exc . InvalidRequestError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> ) <EOL> if self . with_polymorphic and isinstance ( self . with_polymorphic [ <NUM_LIT:1> ] , <EOL> expression . SelectBase ) : <EOL> self . with_polymorphic = ( self . with_polymorphic [ <NUM_LIT:0> ] , <EOL> self . with_polymorphic [ <NUM_LIT:1> ] . alias ( ) ) <EOL> if self . configured : <EOL> self . _expire_memoizations ( ) <EOL> def _set_concrete_base ( self , mapper ) : <EOL> """<STR_LIT>""" <EOL> assert self . concrete <EOL> assert not self . inherits <EOL> assert isinstance ( mapper , Mapper ) <EOL> self . inherits = mapper <EOL> self . inherits . polymorphic_map . update ( self . polymorphic_map ) <EOL> self . polymorphic_map = self . inherits . polymorphic_map <EOL> for mapper in self . iterate_to_root ( ) : <EOL> if mapper . polymorphic_on is not None : <EOL> mapper . _requires_row_aliasing = True <EOL> self . batch = self . inherits . batch <EOL> for mp in self . self_and_descendants : <EOL> mp . base_mapper = self . inherits . base_mapper <EOL> self . inherits . _inheriting_mappers . append ( self ) <EOL> self . passive_updates = self . inherits . passive_updates <EOL> self . _all_tables = self . inherits . _all_tables <EOL> for key , prop in mapper . _props . items ( ) : <EOL> if key not in self . _props and not self . _should_exclude ( key , key , local = False , <EOL> column = None ) : <EOL> self . _adapt_inherited_property ( key , prop , False ) <EOL> def _set_polymorphic_on ( self , polymorphic_on ) : <EOL> self . polymorphic_on = polymorphic_on <EOL> self . _configure_polymorphic_setter ( True ) <EOL> def _configure_legacy_instrument_class ( self ) : <EOL> if self . inherits : <EOL> self . dispatch . _update ( self . inherits . dispatch ) <EOL> super_extensions = set ( <EOL> chain ( * [ m . _deprecated_extensions <EOL> for m in self . inherits . iterate_to_root ( ) ] ) ) <EOL> else : <EOL> super_extensions = set ( ) <EOL> for ext in self . _deprecated_extensions : <EOL> if ext not in super_extensions : <EOL> ext . _adapt_instrument_class ( self , ext ) <EOL> def _configure_listeners ( self ) : <EOL> if self . inherits : <EOL> super_extensions = set ( <EOL> chain ( * [ m . _deprecated_extensions <EOL> for m in self . inherits . iterate_to_root ( ) ] ) ) <EOL> else : <EOL> super_extensions = set ( ) <EOL> for ext in self . _deprecated_extensions : <EOL> if ext not in super_extensions : <EOL> ext . _adapt_listener ( self , ext ) <EOL> def _configure_class_instrumentation ( self ) : <EOL> """<STR_LIT>""" <EOL> manager = attributes . manager_of_class ( self . class_ ) <EOL> if self . non_primary : <EOL> if not manager or not manager . is_mapped : <EOL> raise sa_exc . InvalidRequestError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % self . class_ ) <EOL> self . class_manager = manager <EOL> self . _identity_class = manager . mapper . _identity_class <EOL> _mapper_registry [ self ] = True <EOL> return <EOL> if manager is not None : <EOL> assert manager . class_ is self . class_ <EOL> if manager . is_mapped : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> self . class_ ) <EOL> _mapper_registry [ self ] = True <EOL> self . dispatch . instrument_class ( self , self . class_ ) <EOL> if manager is None : <EOL> manager = instrumentation . register_class ( self . class_ ) <EOL> self . class_manager = manager <EOL> manager . mapper = self <EOL> manager . deferred_scalar_loader = util . partial ( <EOL> loading . load_scalar_attributes , self ) <EOL> if manager . info . get ( _INSTRUMENTOR , False ) : <EOL> return <EOL> event . listen ( manager , '<STR_LIT>' , _event_on_first_init , raw = True ) <EOL> event . listen ( manager , '<STR_LIT>' , _event_on_init , raw = True ) <EOL> event . listen ( manager , '<STR_LIT>' , _event_on_resurrect , raw = True ) <EOL> for key , method in util . iterate_attributes ( self . class_ ) : <EOL> if isinstance ( method , types . FunctionType ) : <EOL> if hasattr ( method , '<STR_LIT>' ) : <EOL> self . _reconstructor = method <EOL> event . listen ( manager , '<STR_LIT>' , _event_on_load , raw = True ) <EOL> elif hasattr ( method , '<STR_LIT>' ) : <EOL> validation_opts = method . __sa_validation_opts__ <EOL> for name in method . __sa_validators__ : <EOL> self . validators = self . validators . union ( <EOL> { name : ( method , validation_opts ) } <EOL> ) <EOL> manager . info [ _INSTRUMENTOR ] = self <EOL> @ classmethod <EOL> def _configure_all ( cls ) : <EOL> """<STR_LIT>""" <EOL> configure_mappers ( ) <EOL> def dispose ( self ) : <EOL> self . configured = True <EOL> if hasattr ( self , '<STR_LIT>' ) : <EOL> del self . _configure_failed <EOL> if not self . non_primary and self . class_manager is not None and self . class_manager . is_mapped and self . class_manager . mapper is self : <EOL> instrumentation . unregister_class ( self . class_ ) <EOL> def _configure_pks ( self ) : <EOL> self . tables = sql_util . find_tables ( self . mapped_table ) <EOL> self . _pks_by_table = { } <EOL> self . _cols_by_table = { } <EOL> all_cols = util . column_set ( chain ( * [ <EOL> col . proxy_set for col in <EOL> self . _columntoproperty ] ) ) <EOL> pk_cols = util . column_set ( c for c in all_cols if c . primary_key ) <EOL> tables = set ( self . tables + [ self . mapped_table ] ) <EOL> self . _all_tables . update ( tables ) <EOL> for t in tables : <EOL> if t . primary_key and pk_cols . issuperset ( t . primary_key ) : <EOL> self . _pks_by_table [ t ] = util . ordered_column_set ( t . primary_key ) . intersection ( pk_cols ) <EOL> self . _cols_by_table [ t ] = util . ordered_column_set ( t . c ) . intersection ( all_cols ) <EOL> self . _readonly_props = set ( <EOL> self . _columntoproperty [ col ] <EOL> for col in self . _columntoproperty <EOL> if not hasattr ( col , '<STR_LIT>' ) or <EOL> col . table not in self . _cols_by_table ) <EOL> if self . _primary_key_argument : <EOL> for k in self . _primary_key_argument : <EOL> if k . table not in self . _pks_by_table : <EOL> self . _pks_by_table [ k . table ] = util . OrderedSet ( ) <EOL> self . _pks_by_table [ k . table ] . add ( k ) <EOL> elif self . mapped_table not in self . _pks_by_table or len ( self . _pks_by_table [ self . mapped_table ] ) == <NUM_LIT:0> : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> ( self , self . mapped_table . description ) ) <EOL> elif self . local_table not in self . _pks_by_table and isinstance ( self . local_table , schema . Table ) : <EOL> util . warn ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> % self . local_table . description ) <EOL> if self . inherits and not self . concrete and not self . _primary_key_argument : <EOL> self . primary_key = self . inherits . primary_key <EOL> else : <EOL> if self . _primary_key_argument : <EOL> primary_key = sql_util . reduce_columns ( <EOL> [ self . mapped_table . corresponding_column ( c ) for c in <EOL> self . _primary_key_argument ] , <EOL> ignore_nonexistent_tables = True ) <EOL> else : <EOL> primary_key = sql_util . reduce_columns ( <EOL> self . _pks_by_table [ self . mapped_table ] , <EOL> ignore_nonexistent_tables = True ) <EOL> if len ( primary_key ) == <NUM_LIT:0> : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> ( self , self . mapped_table . description ) ) <EOL> self . primary_key = tuple ( primary_key ) <EOL> self . _log ( "<STR_LIT>" , primary_key ) <EOL> def _configure_properties ( self ) : <EOL> self . columns = self . c = util . OrderedProperties ( ) <EOL> self . _props = util . OrderedDict ( ) <EOL> self . _columntoproperty = _ColumnMapping ( self ) <EOL> if self . _init_properties : <EOL> for key , prop in self . _init_properties . items ( ) : <EOL> self . _configure_property ( key , prop , False ) <EOL> if self . inherits : <EOL> for key , prop in self . inherits . _props . items ( ) : <EOL> if key not in self . _props and not self . _should_exclude ( key , key , local = False , <EOL> column = None ) : <EOL> self . _adapt_inherited_property ( key , prop , False ) <EOL> for column in self . mapped_table . columns : <EOL> if column in self . _columntoproperty : <EOL> continue <EOL> column_key = ( self . column_prefix or '<STR_LIT>' ) + column . key <EOL> if self . _should_exclude ( <EOL> column . key , column_key , <EOL> local = self . local_table . c . contains_column ( column ) , <EOL> column = column <EOL> ) : <EOL> continue <EOL> for mapper in self . iterate_to_root ( ) : <EOL> if column in mapper . _columntoproperty : <EOL> column_key = mapper . _columntoproperty [ column ] . key <EOL> self . _configure_property ( column_key , <EOL> column , <EOL> init = False , <EOL> setparent = True ) <EOL> def _configure_polymorphic_setter ( self , init = False ) : <EOL> """<STR_LIT>""" <EOL> setter = False <EOL> if self . polymorphic_on is not None : <EOL> setter = True <EOL> if isinstance ( self . polymorphic_on , util . string_types ) : <EOL> try : <EOL> self . polymorphic_on = self . _props [ self . polymorphic_on ] <EOL> except KeyError : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % self . polymorphic_on ) <EOL> if self . polymorphic_on in self . _columntoproperty : <EOL> prop = self . _columntoproperty [ self . polymorphic_on ] <EOL> polymorphic_key = prop . key <EOL> self . polymorphic_on = prop . columns [ <NUM_LIT:0> ] <EOL> polymorphic_key = prop . key <EOL> elif isinstance ( self . polymorphic_on , MapperProperty ) : <EOL> if not isinstance ( self . polymorphic_on , <EOL> properties . ColumnProperty ) : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> prop = self . polymorphic_on <EOL> self . polymorphic_on = prop . columns [ <NUM_LIT:0> ] <EOL> polymorphic_key = prop . key <EOL> elif not expression . _is_column ( self . polymorphic_on ) : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> ) <EOL> else : <EOL> col = self . mapped_table . corresponding_column ( <EOL> self . polymorphic_on ) <EOL> if col is None : <EOL> setter = False <EOL> instrument = False <EOL> col = self . polymorphic_on <EOL> if isinstance ( col , schema . Column ) and ( <EOL> self . with_polymorphic is None or <EOL> self . with_polymorphic [ <NUM_LIT:1> ] . <EOL> corresponding_column ( col ) is None ) : <EOL> raise sa_exc . InvalidRequestError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> % col . description ) <EOL> else : <EOL> instrument = True <EOL> key = getattr ( col , '<STR_LIT:key>' , None ) <EOL> if key : <EOL> if self . _should_exclude ( col . key , col . key , False , col ) : <EOL> raise sa_exc . InvalidRequestError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> col . key ) <EOL> else : <EOL> self . polymorphic_on = col = col . label ( "<STR_LIT>" ) <EOL> key = col . key <EOL> self . _configure_property ( <EOL> key , <EOL> properties . ColumnProperty ( col , <EOL> _instrument = instrument ) , <EOL> init = init , setparent = True ) <EOL> polymorphic_key = key <EOL> else : <EOL> for mapper in self . iterate_to_root ( ) : <EOL> if mapper . polymorphic_on is not None : <EOL> if self . mapped_table is mapper . mapped_table : <EOL> self . polymorphic_on = mapper . polymorphic_on <EOL> else : <EOL> self . polymorphic_on = self . mapped_table . corresponding_column ( <EOL> mapper . polymorphic_on ) <EOL> if self . polymorphic_on is not None : <EOL> self . _set_polymorphic_identity = mapper . _set_polymorphic_identity <EOL> self . _validate_polymorphic_identity = mapper . _validate_polymorphic_identity <EOL> else : <EOL> self . _set_polymorphic_identity = None <EOL> return <EOL> if setter : <EOL> def _set_polymorphic_identity ( state ) : <EOL> dict_ = state . dict <EOL> state . get_impl ( polymorphic_key ) . set ( <EOL> state , dict_ , <EOL> state . manager . mapper . polymorphic_identity , <EOL> None ) <EOL> def _validate_polymorphic_identity ( mapper , state , dict_ ) : <EOL> if polymorphic_key in dict_ and dict_ [ polymorphic_key ] not in mapper . _acceptable_polymorphic_identities : <EOL> util . warn ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( <EOL> state_str ( state ) , <EOL> dict_ [ polymorphic_key ] <EOL> ) <EOL> ) <EOL> self . _set_polymorphic_identity = _set_polymorphic_identity <EOL> self . _validate_polymorphic_identity = _validate_polymorphic_identity <EOL> else : <EOL> self . _set_polymorphic_identity = None <EOL> _validate_polymorphic_identity = None <EOL> @ _memoized_configured_property <EOL> def _version_id_prop ( self ) : <EOL> if self . version_id_col is not None : <EOL> return self . _columntoproperty [ self . version_id_col ] <EOL> else : <EOL> return None <EOL> @ _memoized_configured_property <EOL> def _acceptable_polymorphic_identities ( self ) : <EOL> identities = set ( ) <EOL> stack = deque ( [ self ] ) <EOL> while stack : <EOL> item = stack . popleft ( ) <EOL> if item . mapped_table is self . mapped_table : <EOL> identities . add ( item . polymorphic_identity ) <EOL> stack . extend ( item . _inheriting_mappers ) <EOL> return identities <EOL> def _adapt_inherited_property ( self , key , prop , init ) : <EOL> if not self . concrete : <EOL> self . _configure_property ( key , prop , init = False , setparent = False ) <EOL> elif key not in self . _props : <EOL> self . _configure_property ( <EOL> key , <EOL> properties . ConcreteInheritedProperty ( ) , <EOL> init = init , setparent = True ) <EOL> def _configure_property ( self , key , prop , init = True , setparent = True ) : <EOL> self . _log ( "<STR_LIT>" , key , prop . __class__ . __name__ ) <EOL> if not isinstance ( prop , MapperProperty ) : <EOL> prop = self . _property_from_column ( key , prop ) <EOL> if isinstance ( prop , properties . ColumnProperty ) : <EOL> col = self . mapped_table . corresponding_column ( prop . columns [ <NUM_LIT:0> ] ) <EOL> if col is None and self . inherits : <EOL> path = [ self ] <EOL> for m in self . inherits . iterate_to_root ( ) : <EOL> col = m . local_table . corresponding_column ( prop . columns [ <NUM_LIT:0> ] ) <EOL> if col is not None : <EOL> for m2 in path : <EOL> m2 . mapped_table . _reset_exported ( ) <EOL> col = self . mapped_table . corresponding_column ( <EOL> prop . columns [ <NUM_LIT:0> ] ) <EOL> break <EOL> path . append ( m ) <EOL> if col is None : <EOL> col = prop . columns [ <NUM_LIT:0> ] <EOL> if hasattr ( self , '<STR_LIT>' ) and ( not hasattr ( col , '<STR_LIT>' ) or <EOL> col . table not in self . _cols_by_table ) : <EOL> self . _readonly_props . add ( prop ) <EOL> else : <EOL> if hasattr ( self , '<STR_LIT>' ) and col . table in self . _cols_by_table and col not in self . _cols_by_table [ col . table ] : <EOL> self . _cols_by_table [ col . table ] . add ( col ) <EOL> if not hasattr ( prop , '<STR_LIT>' ) : <EOL> prop . _is_polymorphic_discriminator = ( col is self . polymorphic_on or <EOL> prop . columns [ <NUM_LIT:0> ] is self . polymorphic_on ) <EOL> self . columns [ key ] = col <EOL> for col in prop . columns + prop . _orig_columns : <EOL> for col in col . proxy_set : <EOL> self . _columntoproperty [ col ] = prop <EOL> prop . key = key <EOL> if setparent : <EOL> prop . set_parent ( self , init ) <EOL> if key in self . _props and getattr ( self . _props [ key ] , '<STR_LIT>' , False ) : <EOL> syn = self . _props [ key ] . _mapped_by_synonym <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( syn , key , key , syn ) <EOL> ) <EOL> if key in self . _props and not isinstance ( prop , properties . ColumnProperty ) and not isinstance ( self . _props [ key ] , properties . ColumnProperty ) : <EOL> util . warn ( "<STR_LIT>" <EOL> "<STR_LIT>" % ( <EOL> self . _props [ key ] , <EOL> self , <EOL> prop , <EOL> ) ) <EOL> self . _props [ key ] = prop <EOL> if not self . non_primary : <EOL> prop . instrument_class ( self ) <EOL> for mapper in self . _inheriting_mappers : <EOL> mapper . _adapt_inherited_property ( key , prop , init ) <EOL> if init : <EOL> prop . init ( ) <EOL> prop . post_instrument_class ( self ) <EOL> if self . configured : <EOL> self . _expire_memoizations ( ) <EOL> def _property_from_column ( self , key , prop ) : <EOL> """<STR_LIT>""" <EOL> columns = util . to_list ( prop ) <EOL> column = columns [ <NUM_LIT:0> ] <EOL> if not expression . _is_column ( column ) : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> % ( key , prop ) ) <EOL> prop = self . _props . get ( key , None ) <EOL> if isinstance ( prop , properties . ColumnProperty ) : <EOL> if ( <EOL> not self . _inherits_equated_pairs or <EOL> ( prop . columns [ <NUM_LIT:0> ] , column ) not in self . _inherits_equated_pairs <EOL> ) and not prop . columns [ <NUM_LIT:0> ] . shares_lineage ( column ) and prop . columns [ <NUM_LIT:0> ] is not self . version_id_col and column is not self . version_id_col : <EOL> warn_only = prop . parent is not self <EOL> msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( prop . columns [ - <NUM_LIT:1> ] , column , key ) ) <EOL> if warn_only : <EOL> util . warn ( msg ) <EOL> else : <EOL> raise sa_exc . InvalidRequestError ( msg ) <EOL> prop = prop . copy ( ) <EOL> prop . columns . insert ( <NUM_LIT:0> , column ) <EOL> self . _log ( "<STR_LIT>" <EOL> "<STR_LIT>" % ( key ) ) <EOL> return prop <EOL> elif prop is None or isinstance ( prop , <EOL> properties . ConcreteInheritedProperty ) : <EOL> mapped_column = [ ] <EOL> for c in columns : <EOL> mc = self . mapped_table . corresponding_column ( c ) <EOL> if mc is None : <EOL> mc = self . local_table . corresponding_column ( c ) <EOL> if mc is not None : <EOL> self . mapped_table . _reset_exported ( ) <EOL> mc = self . mapped_table . corresponding_column ( c ) <EOL> if mc is None : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( key , self , c ) ) <EOL> mapped_column . append ( mc ) <EOL> return properties . ColumnProperty ( * mapped_column ) <EOL> else : <EOL> raise sa_exc . ArgumentError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> ( key , self , column . key , prop ) ) <EOL> def _post_configure_properties ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _log ( "<STR_LIT>" ) <EOL> l = [ ( key , prop ) for key , prop in self . _props . items ( ) ] <EOL> for key , prop in l : <EOL> self . _log ( "<STR_LIT>" , key ) <EOL> if prop . parent is self and not prop . _configure_started : <EOL> prop . init ( ) <EOL> if prop . _configure_finished : <EOL> prop . post_instrument_class ( self ) <EOL> self . _log ( "<STR_LIT>" ) <EOL> self . configured = True <EOL> def add_properties ( self , dict_of_properties ) : <EOL> """<STR_LIT>""" <EOL> for key , value in dict_of_properties . items ( ) : <EOL> self . add_property ( key , value ) <EOL> def add_property ( self , key , prop ) : <EOL> """<STR_LIT>""" <EOL> self . _init_properties [ key ] = prop <EOL> self . _configure_property ( key , prop , init = self . configured ) <EOL> def _expire_memoizations ( self ) : <EOL> for mapper in self . iterate_to_root ( ) : <EOL> _memoized_configured_property . expire_instance ( mapper ) <EOL> @ property <EOL> def _log_desc ( self ) : <EOL> return "<STR_LIT:(>" + self . class_ . __name__ + "<STR_LIT:|>" + ( self . local_table is not None and <EOL> self . local_table . description or <EOL> str ( self . local_table ) ) + ( self . non_primary and <EOL> "<STR_LIT>" or "<STR_LIT>" ) + "<STR_LIT:)>" <EOL> def _log ( self , msg , * args ) : <EOL> self . logger . info ( <EOL> "<STR_LIT>" + msg , * ( ( self . _log_desc , ) + args ) <EOL> ) <EOL> def _log_debug ( self , msg , * args ) : <EOL> self . logger . debug ( <EOL> "<STR_LIT>" + msg , * ( ( self . _log_desc , ) + args ) <EOL> ) <EOL> def __repr__ ( self ) : <EOL> return '<STR_LIT>' % ( <EOL> id ( self ) , self . class_ . __name__ ) <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT>" % ( <EOL> self . class_ . __name__ , <EOL> self . local_table is not None and <EOL> self . local_table . description or None , <EOL> self . non_primary and "<STR_LIT>" or "<STR_LIT>" <EOL> ) <EOL> def _is_orphan ( self , state ) : <EOL> orphan_possible = False <EOL> for mapper in self . iterate_to_root ( ) : <EOL> for ( key , cls ) in mapper . _delete_orphans : <EOL> orphan_possible = True <EOL> has_parent = attributes . manager_of_class ( cls ) . has_parent ( <EOL> state , key , optimistic = state . has_identity ) <EOL> if self . legacy_is_orphan and has_parent : <EOL> return False <EOL> elif not self . legacy_is_orphan and not has_parent : <EOL> return True <EOL> if self . legacy_is_orphan : <EOL> return orphan_possible <EOL> else : <EOL> return False <EOL> def has_property ( self , key ) : <EOL> return key in self . _props <EOL> def get_property ( self , key , _configure_mappers = True ) : <EOL> """<STR_LIT>""" <EOL> if _configure_mappers and Mapper . _new_mappers : <EOL> configure_mappers ( ) <EOL> try : <EOL> return self . _props [ key ] <EOL> except KeyError : <EOL> raise sa_exc . InvalidRequestError ( <EOL> "<STR_LIT>" % ( self , key ) ) <EOL> def get_property_by_column ( self , column ) : <EOL> """<STR_LIT>""" <EOL> return self . _columntoproperty [ column ] <EOL> @ property <EOL> def iterate_properties ( self ) : <EOL> """<STR_LIT>""" <EOL> if Mapper . _new_mappers : <EOL> configure_mappers ( ) <EOL> return iter ( self . _props . values ( ) ) <EOL> def _mappers_from_spec ( self , spec , selectable ) : <EOL> """<STR_LIT>""" <EOL> if spec == '<STR_LIT:*>' : <EOL> mappers = list ( self . self_and_descendants ) <EOL> elif spec : <EOL> mappers = set ( ) <EOL> for m in util . to_list ( spec ) : <EOL> m = _class_to_mapper ( m ) <EOL> if not m . isa ( self ) : <EOL> raise sa_exc . InvalidRequestError ( <EOL> "<STR_LIT>" % <EOL> ( m , self ) ) <EOL> if selectable is None : <EOL> mappers . update ( m . iterate_to_root ( ) ) <EOL> else : <EOL> mappers . add ( m ) <EOL> mappers = [ m for m in self . self_and_descendants if m in mappers ] <EOL> else : <EOL> mappers = [ ] <EOL> if selectable is not None : <EOL> tables = set ( sql_util . find_tables ( selectable , <EOL> include_aliases = True ) ) <EOL> mappers = [ m for m in mappers if m . local_table in tables ] <EOL> return mappers <EOL> def _selectable_from_mappers ( self , mappers , innerjoin ) : <EOL> """<STR_LIT>""" <EOL> from_obj = self . mapped_table <EOL> for m in mappers : <EOL> if m is self : <EOL> continue <EOL> if m . concrete : <EOL> raise sa_exc . InvalidRequestError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> elif not m . single : <EOL> if innerjoin : <EOL> from_obj = from_obj . join ( m . local_table , <EOL> m . inherit_condition ) <EOL> else : <EOL> from_obj = from_obj . outerjoin ( m . local_table , <EOL> m . inherit_condition ) <EOL> return from_obj <EOL> @ _memoized_configured_property <EOL> def _single_table_criterion ( self ) : <EOL> if self . single and self . inherits and self . polymorphic_on is not None : <EOL> return self . polymorphic_on . in_ ( <EOL> m . polymorphic_identity <EOL> for m in self . self_and_descendants ) <EOL> else : <EOL> return None <EOL> @ _memoized_configured_property <EOL> def _with_polymorphic_mappers ( self ) : <EOL> if Mapper . _new_mappers : <EOL> configure_mappers ( ) <EOL> if not self . with_polymorphic : <EOL> return [ ] <EOL> return self . _mappers_from_spec ( * self . with_polymorphic ) <EOL> @ _memoized_configured_property <EOL> def _with_polymorphic_selectable ( self ) : <EOL> if not self . with_polymorphic : <EOL> return self . mapped_table <EOL> spec , selectable = self . with_polymorphic <EOL> if selectable is not None : <EOL> return selectable <EOL> else : <EOL> return self . _selectable_from_mappers ( <EOL> self . _mappers_from_spec ( spec , selectable ) , <EOL> False ) <EOL> with_polymorphic_mappers = _with_polymorphic_mappers <EOL> """<STR_LIT>""" <EOL> @ property <EOL> def selectable ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _with_polymorphic_selectable <EOL> def _with_polymorphic_args ( self , spec = None , selectable = False , <EOL> innerjoin = False ) : <EOL> if self . with_polymorphic : <EOL> if not spec : <EOL> spec = self . with_polymorphic [ <NUM_LIT:0> ] <EOL> if selectable is False : <EOL> selectable = self . with_polymorphic [ <NUM_LIT:1> ] <EOL> elif selectable is False : <EOL> selectable = None <EOL> mappers = self . _mappers_from_spec ( spec , selectable ) <EOL> if selectable is not None : <EOL> return mappers , selectable <EOL> else : <EOL> return mappers , self . _selectable_from_mappers ( mappers , <EOL> innerjoin ) <EOL> @ _memoized_configured_property <EOL> def _polymorphic_properties ( self ) : <EOL> return list ( self . _iterate_polymorphic_properties ( <EOL> self . _with_polymorphic_mappers ) ) <EOL> def _iterate_polymorphic_properties ( self , mappers = None ) : <EOL> """<STR_LIT>""" <EOL> if mappers is None : <EOL> mappers = self . _with_polymorphic_mappers <EOL> if not mappers : <EOL> for c in self . iterate_properties : <EOL> yield c <EOL> else : <EOL> for c in util . unique_list ( <EOL> chain ( * [ <EOL> list ( mapper . iterate_properties ) for mapper in <EOL> [ self ] + mappers <EOL> ] ) <EOL> ) : <EOL> if getattr ( c , '<STR_LIT>' , False ) and ( self . polymorphic_on is None or <EOL> c . columns [ <NUM_LIT:0> ] is not self . polymorphic_on ) : <EOL> continue <EOL> yield c <EOL> @ util . memoized_property <EOL> def attrs ( self ) : <EOL> """<STR_LIT>""" <EOL> if Mapper . _new_mappers : <EOL> configure_mappers ( ) <EOL> return util . ImmutableProperties ( self . _props ) <EOL> @ util . memoized_property <EOL> def all_orm_descriptors ( self ) : <EOL> """<STR_LIT>""" <EOL> return util . ImmutableProperties ( <EOL> dict ( self . class_manager . _all_sqla_attributes ( ) ) ) <EOL> @ _memoized_configured_property <EOL> def synonyms ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _filter_properties ( properties . SynonymProperty ) <EOL> @ _memoized_configured_property <EOL> def column_attrs ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _filter_properties ( properties . ColumnProperty ) <EOL> @ _memoized_configured_property <EOL> def relationships ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _filter_properties ( properties . RelationshipProperty ) <EOL> @ _memoized_configured_property <EOL> def composites ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _filter_properties ( properties . CompositeProperty ) <EOL> def _filter_properties ( self , type_ ) : <EOL> if Mapper . _new_mappers : <EOL> configure_mappers ( ) <EOL> return util . ImmutableProperties ( util . OrderedDict ( <EOL> ( k , v ) for k , v in self . _props . items ( ) <EOL> if isinstance ( v , type_ ) <EOL> ) ) <EOL> @ _memoized_configured_property <EOL> def _get_clause ( self ) : <EOL> """<STR_LIT>""" <EOL> params = [ ( primary_key , sql . bindparam ( None , type_ = primary_key . type ) ) <EOL> for primary_key in self . primary_key ] <EOL> return sql . and_ ( * [ k == v for ( k , v ) in params ] ) , util . column_dict ( params ) <EOL> @ _memoized_configured_property <EOL> def _equivalent_columns ( self ) : <EOL> """<STR_LIT>""" <EOL> result = util . column_dict ( ) <EOL> def visit_binary ( binary ) : <EOL> if binary . operator == operators . eq : <EOL> if binary . left in result : <EOL> result [ binary . left ] . add ( binary . right ) <EOL> else : <EOL> result [ binary . left ] = util . column_set ( ( binary . right , ) ) <EOL> if binary . right in result : <EOL> result [ binary . right ] . add ( binary . left ) <EOL> else : <EOL> result [ binary . right ] = util . column_set ( ( binary . left , ) ) <EOL> for mapper in self . base_mapper . self_and_descendants : <EOL> if mapper . inherit_condition is not None : <EOL> visitors . traverse ( <EOL> mapper . inherit_condition , { } , <EOL> { '<STR_LIT>' : visit_binary } ) <EOL> return result <EOL> def _is_userland_descriptor ( self , obj ) : <EOL> if isinstance ( obj , ( _MappedAttribute , <EOL> instrumentation . ClassManager , <EOL> expression . ColumnElement ) ) : <EOL> return False <EOL> else : <EOL> return True <EOL> def _should_exclude ( self , name , assigned_name , local , column ) : <EOL> """<STR_LIT>""" <EOL> if local : <EOL> if self . class_ . __dict__ . get ( assigned_name , None ) is not None and self . _is_userland_descriptor ( <EOL> self . class_ . __dict__ [ assigned_name ] ) : <EOL> return True <EOL> else : <EOL> if getattr ( self . class_ , assigned_name , None ) is not None and self . _is_userland_descriptor ( <EOL> getattr ( self . class_ , assigned_name ) ) : <EOL> return True <EOL> if self . include_properties is not None and name not in self . include_properties and ( column is None or column not in self . include_properties ) : <EOL> self . _log ( "<STR_LIT>" % ( name ) ) <EOL> return True <EOL> if self . exclude_properties is not None and ( <EOL> name in self . exclude_properties or <EOL> ( column is not None and column in self . exclude_properties ) <EOL> ) : <EOL> self . _log ( "<STR_LIT>" % ( name ) ) <EOL> return True <EOL> return False <EOL> def common_parent ( self , other ) : <EOL> """<STR_LIT>""" <EOL> return self . base_mapper is other . base_mapper <EOL> def _canload ( self , state , allow_subtypes ) : <EOL> s = self . primary_mapper ( ) <EOL> if self . polymorphic_on is not None or allow_subtypes : <EOL> return _state_mapper ( state ) . isa ( s ) <EOL> else : <EOL> return _state_mapper ( state ) is s <EOL> def isa ( self , other ) : <EOL> """<STR_LIT>""" <EOL> m = self <EOL> while m and m is not other : <EOL> m = m . inherits <EOL> return bool ( m ) <EOL> def iterate_to_root ( self ) : <EOL> m = self <EOL> while m : <EOL> yield m <EOL> m = m . inherits <EOL> @ _memoized_configured_property <EOL> def self_and_descendants ( self ) : <EOL> """<STR_LIT>""" <EOL> descendants = [ ] <EOL> stack = deque ( [ self ] ) <EOL> while stack : <EOL> item = stack . popleft ( ) <EOL> descendants . append ( item ) <EOL> stack . extend ( item . _inheriting_mappers ) <EOL> return util . WeakSequence ( descendants ) <EOL> def polymorphic_iterator ( self ) : <EOL> """<STR_LIT>""" <EOL> return iter ( self . self_and_descendants ) <EOL> def primary_mapper ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . class_manager . mapper <EOL> @ property <EOL> def primary_base_mapper ( self ) : <EOL> return self . class_manager . mapper . base_mapper <EOL> def identity_key_from_row ( self , row , adapter = None ) : <EOL> """<STR_LIT>""" <EOL> pk_cols = self . primary_key <EOL> if adapter : <EOL> pk_cols = [ adapter . columns [ c ] for c in pk_cols ] <EOL> return self . _identity_class , tuple ( row [ column ] for column in pk_cols ) <EOL> def identity_key_from_primary_key ( self , primary_key ) : <EOL> """<STR_LIT>""" <EOL> return self . _identity_class , tuple ( primary_key ) <EOL> def identity_key_from_instance ( self , instance ) : <EOL> """<STR_LIT>""" <EOL> return self . identity_key_from_primary_key ( <EOL> self . primary_key_from_instance ( instance ) ) <EOL> def _identity_key_from_state ( self , state ) : <EOL> dict_ = state . dict <EOL> manager = state . manager <EOL> return self . _identity_class , tuple ( [ <EOL> manager [ self . _columntoproperty [ col ] . key ] . <EOL> impl . get ( state , dict_ , attributes . PASSIVE_OFF ) <EOL> for col in self . primary_key <EOL> ] ) <EOL> def primary_key_from_instance ( self , instance ) : <EOL> """<STR_LIT>""" <EOL> state = attributes . instance_state ( instance ) <EOL> return self . _primary_key_from_state ( state ) <EOL> def _primary_key_from_state ( self , state ) : <EOL> dict_ = state . dict <EOL> manager = state . manager <EOL> return [ <EOL> manager [ self . _columntoproperty [ col ] . key ] . <EOL> impl . get ( state , dict_ , attributes . PASSIVE_OFF ) <EOL> for col in self . primary_key <EOL> ] <EOL> def _get_state_attr_by_column ( self , state , dict_ , column , <EOL> passive = attributes . PASSIVE_OFF ) : <EOL> prop = self . _columntoproperty [ column ] <EOL> return state . manager [ prop . key ] . impl . get ( state , dict_ , passive = passive ) <EOL> def _set_state_attr_by_column ( self , state , dict_ , column , value ) : <EOL> prop = self . _columntoproperty [ column ] <EOL> state . manager [ prop . key ] . impl . set ( state , dict_ , value , None ) <EOL> def _get_committed_attr_by_column ( self , obj , column ) : <EOL> state = attributes . instance_state ( obj ) <EOL> dict_ = attributes . instance_dict ( obj ) <EOL> return self . _get_committed_state_attr_by_column ( state , dict_ , column ) <EOL> def _get_committed_state_attr_by_column ( <EOL> self , <EOL> state , <EOL> dict_ , <EOL> column , <EOL> passive = attributes . PASSIVE_OFF ) : <EOL> prop = self . _columntoproperty [ column ] <EOL> return state . manager [ prop . key ] . impl . get_committed_value ( state , dict_ , passive = passive ) <EOL> def _optimized_get_statement ( self , state , attribute_names ) : <EOL> """<STR_LIT>""" <EOL> props = self . _props <EOL> tables = set ( chain ( <EOL> * [ sql_util . find_tables ( c , check_columns = True ) <EOL> for key in attribute_names <EOL> for c in props [ key ] . columns ] <EOL> ) ) <EOL> if self . base_mapper . local_table in tables : <EOL> return None <EOL> class ColumnsNotAvailable ( Exception ) : <EOL> pass <EOL> def visit_binary ( binary ) : <EOL> leftcol = binary . left <EOL> rightcol = binary . right <EOL> if leftcol is None or rightcol is None : <EOL> return <EOL> if leftcol . table not in tables : <EOL> leftval = self . _get_committed_state_attr_by_column ( <EOL> state , state . dict , <EOL> leftcol , <EOL> passive = attributes . PASSIVE_NO_INITIALIZE ) <EOL> if leftval is attributes . PASSIVE_NO_RESULT or leftval is None : <EOL> raise ColumnsNotAvailable ( ) <EOL> binary . left = sql . bindparam ( None , leftval , <EOL> type_ = binary . right . type ) <EOL> elif rightcol . table not in tables : <EOL> rightval = self . _get_committed_state_attr_by_column ( <EOL> state , state . dict , <EOL> rightcol , <EOL> passive = attributes . PASSIVE_NO_INITIALIZE ) <EOL> if rightval is attributes . PASSIVE_NO_RESULT or rightval is None : <EOL> raise ColumnsNotAvailable ( ) <EOL> binary . right = sql . bindparam ( None , rightval , <EOL> type_ = binary . right . type ) <EOL> allconds = [ ] <EOL> try : <EOL> start = False <EOL> for mapper in reversed ( list ( self . iterate_to_root ( ) ) ) : <EOL> if mapper . local_table in tables : <EOL> start = True <EOL> elif not isinstance ( mapper . local_table , <EOL> expression . TableClause ) : <EOL> return None <EOL> if start and not mapper . single : <EOL> allconds . append ( visitors . cloned_traverse ( <EOL> mapper . inherit_condition , <EOL> { } , <EOL> { '<STR_LIT>' : visit_binary } <EOL> ) <EOL> ) <EOL> except ColumnsNotAvailable : <EOL> return None <EOL> cond = sql . and_ ( * allconds ) <EOL> cols = [ ] <EOL> for key in attribute_names : <EOL> cols . extend ( props [ key ] . columns ) <EOL> return sql . select ( cols , cond , use_labels = True ) <EOL> def cascade_iterator ( self , type_ , state , halt_on = None ) : <EOL> """<STR_LIT>""" <EOL> visited_states = set ( ) <EOL> prp , mpp = object ( ) , object ( ) <EOL> visitables = deque ( [ ( deque ( self . _props . values ( ) ) , prp , <EOL> state , state . dict ) ] ) <EOL> while visitables : <EOL> iterator , item_type , parent_state , parent_dict = visitables [ - <NUM_LIT:1> ] <EOL> if not iterator : <EOL> visitables . pop ( ) <EOL> continue <EOL> if item_type is prp : <EOL> prop = iterator . popleft ( ) <EOL> if type_ not in prop . cascade : <EOL> continue <EOL> queue = deque ( prop . cascade_iterator ( <EOL> type_ , parent_state , parent_dict , <EOL> visited_states , halt_on ) ) <EOL> if queue : <EOL> visitables . append ( ( queue , mpp , None , None ) ) <EOL> elif item_type is mpp : <EOL> instance , instance_mapper , corresponding_state , corresponding_dict = iterator . popleft ( ) <EOL> yield instance , instance_mapper , corresponding_state , corresponding_dict <EOL> visitables . append ( ( deque ( instance_mapper . _props . values ( ) ) , <EOL> prp , corresponding_state , <EOL> corresponding_dict ) ) <EOL> @ _memoized_configured_property <EOL> def _compiled_cache ( self ) : <EOL> return util . LRUCache ( self . _compiled_cache_size ) <EOL> @ _memoized_configured_property <EOL> def _sorted_tables ( self ) : <EOL> table_to_mapper = { } <EOL> for mapper in self . base_mapper . self_and_descendants : <EOL> for t in mapper . tables : <EOL> table_to_mapper . setdefault ( t , mapper ) <EOL> extra_dependencies = [ ] <EOL> for table , mapper in table_to_mapper . items ( ) : <EOL> super_ = mapper . inherits <EOL> if super_ : <EOL> extra_dependencies . extend ( [ <EOL> ( super_table , table ) <EOL> for super_table in super_ . tables <EOL> ] ) <EOL> def skip ( fk ) : <EOL> parent = table_to_mapper . get ( fk . parent . table ) <EOL> dep = table_to_mapper . get ( fk . column . table ) <EOL> if parent is not None and dep is not None and dep is not parent and dep . inherit_condition is not None : <EOL> cols = set ( sql_util . _find_columns ( dep . inherit_condition ) ) <EOL> if parent . inherit_condition is not None : <EOL> cols = cols . union ( sql_util . _find_columns ( <EOL> parent . inherit_condition ) ) <EOL> return fk . parent not in cols and fk . column not in cols <EOL> else : <EOL> return fk . parent not in cols <EOL> return False <EOL> sorted_ = sql_util . sort_tables ( table_to_mapper , <EOL> skip_fn = skip , <EOL> extra_dependencies = extra_dependencies ) <EOL> ret = util . OrderedDict ( ) <EOL> for t in sorted_ : <EOL> ret [ t ] = table_to_mapper [ t ] <EOL> return ret <EOL> def _memo ( self , key , callable_ ) : <EOL> if key in self . _memoized_values : <EOL> return self . _memoized_values [ key ] <EOL> else : <EOL> self . _memoized_values [ key ] = value = callable_ ( ) <EOL> return value <EOL> @ util . memoized_property <EOL> def _table_to_equated ( self ) : <EOL> """<STR_LIT>""" <EOL> result = util . defaultdict ( list ) <EOL> for table in self . _sorted_tables : <EOL> cols = set ( table . c ) <EOL> for m in self . iterate_to_root ( ) : <EOL> if m . _inherits_equated_pairs and cols . intersection ( <EOL> util . reduce ( set . union , <EOL> [ l . proxy_set for l , r in <EOL> m . _inherits_equated_pairs ] ) <EOL> ) : <EOL> result [ table ] . append ( ( m , m . _inherits_equated_pairs ) ) <EOL> return result <EOL> def configure_mappers ( ) : <EOL> """<STR_LIT>""" <EOL> if not Mapper . _new_mappers : <EOL> return <EOL> _CONFIGURE_MUTEX . acquire ( ) <EOL> try : <EOL> global _already_compiling <EOL> if _already_compiling : <EOL> return <EOL> _already_compiling = True <EOL> try : <EOL> if not Mapper . _new_mappers : <EOL> return <EOL> Mapper . dispatch ( Mapper ) . before_configured ( ) <EOL> for mapper in list ( _mapper_registry ) : <EOL> if getattr ( mapper , '<STR_LIT>' , False ) : <EOL> e = sa_exc . InvalidRequestError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> % mapper . _configure_failed ) <EOL> e . _configure_failed = mapper . _configure_failed <EOL> raise e <EOL> if not mapper . configured : <EOL> try : <EOL> mapper . _post_configure_properties ( ) <EOL> mapper . _expire_memoizations ( ) <EOL> mapper . dispatch . mapper_configured ( <EOL> mapper , mapper . class_ ) <EOL> except : <EOL> exc = sys . exc_info ( ) [ <NUM_LIT:1> ] <EOL> if not hasattr ( exc , '<STR_LIT>' ) : <EOL> mapper . _configure_failed = exc <EOL> raise <EOL> Mapper . _new_mappers = False <EOL> finally : <EOL> _already_compiling = False <EOL> finally : <EOL> _CONFIGURE_MUTEX . release ( ) <EOL> Mapper . dispatch ( Mapper ) . after_configured ( ) <EOL> def reconstructor ( fn ) : <EOL> """<STR_LIT>""" <EOL> fn . __sa_reconstructor__ = True <EOL> return fn <EOL> def validates ( * names , ** kw ) : <EOL> """<STR_LIT>""" <EOL> include_removes = kw . pop ( '<STR_LIT>' , False ) <EOL> include_backrefs = kw . pop ( '<STR_LIT>' , True ) <EOL> def wrap ( fn ) : <EOL> fn . __sa_validators__ = names <EOL> fn . __sa_validation_opts__ = { <EOL> "<STR_LIT>" : include_removes , <EOL> "<STR_LIT>" : include_backrefs <EOL> } <EOL> return fn <EOL> return wrap <EOL> def _event_on_load ( state , ctx ) : <EOL> instrumenting_mapper = state . manager . info [ _INSTRUMENTOR ] <EOL> if instrumenting_mapper . _reconstructor : <EOL> instrumenting_mapper . _reconstructor ( state . obj ( ) ) <EOL> def _event_on_first_init ( manager , cls ) : <EOL> """<STR_LIT>""" <EOL> instrumenting_mapper = manager . info . get ( _INSTRUMENTOR ) <EOL> if instrumenting_mapper : <EOL> if Mapper . _new_mappers : <EOL> configure_mappers ( ) <EOL> def _event_on_init ( state , args , kwargs ) : <EOL> """<STR_LIT>""" <EOL> instrumenting_mapper = state . manager . info . get ( _INSTRUMENTOR ) <EOL> if instrumenting_mapper : <EOL> if Mapper . _new_mappers : <EOL> configure_mappers ( ) <EOL> if instrumenting_mapper . _set_polymorphic_identity : <EOL> instrumenting_mapper . _set_polymorphic_identity ( state ) <EOL> def _event_on_resurrect ( state ) : <EOL> instrumenting_mapper = state . manager . info . get ( _INSTRUMENTOR ) <EOL> if instrumenting_mapper : <EOL> for col , val in zip ( instrumenting_mapper . primary_key , state . key [ <NUM_LIT:1> ] ) : <EOL> instrumenting_mapper . _set_state_attr_by_column ( <EOL> state , state . dict , col , val ) <EOL> class _ColumnMapping ( dict ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , mapper ) : <EOL> self . mapper = mapper <EOL> def __missing__ ( self , column ) : <EOL> prop = self . mapper . _props . get ( column ) <EOL> if prop : <EOL> raise orm_exc . UnmappedColumnError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( <EOL> column . table . name , column . name , column . key , prop ) ) <EOL> raise orm_exc . UnmappedColumnError ( <EOL> "<STR_LIT>" % <EOL> ( column , self . mapper ) ) </s>
<s> from . . util import jython , pypy , defaultdict , decorator , py2k <EOL> import decimal <EOL> import gc <EOL> import time <EOL> import random <EOL> import sys <EOL> import types <EOL> if jython : <EOL> def jython_gc_collect ( * args ) : <EOL> """<STR_LIT>""" <EOL> gc . collect ( ) <EOL> time . sleep ( <NUM_LIT:0.1> ) <EOL> gc . collect ( ) <EOL> gc . collect ( ) <EOL> return <NUM_LIT:0> <EOL> gc_collect = lazy_gc = jython_gc_collect <EOL> elif pypy : <EOL> def pypy_gc_collect ( * args ) : <EOL> gc . collect ( ) <EOL> gc . collect ( ) <EOL> gc_collect = lazy_gc = pypy_gc_collect <EOL> else : <EOL> gc_collect = gc . collect <EOL> def lazy_gc ( ) : <EOL> pass <EOL> def picklers ( ) : <EOL> picklers = set ( ) <EOL> if py2k : <EOL> try : <EOL> import cPickle <EOL> picklers . add ( cPickle ) <EOL> except ImportError : <EOL> pass <EOL> import pickle <EOL> picklers . add ( pickle ) <EOL> for pickle_ in picklers : <EOL> for protocol in - <NUM_LIT:1> , <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:2> : <EOL> yield pickle_ . loads , lambda d : pickle_ . dumps ( d , protocol ) <EOL> def round_decimal ( value , prec ) : <EOL> if isinstance ( value , float ) : <EOL> return round ( value , prec ) <EOL> return ( value * decimal . Decimal ( "<STR_LIT:1>" + "<STR_LIT:0>" * prec ) <EOL> ) . to_integral ( decimal . ROUND_FLOOR ) / pow ( <NUM_LIT:10> , prec ) <EOL> class RandomSet ( set ) : <EOL> def __iter__ ( self ) : <EOL> l = list ( set . __iter__ ( self ) ) <EOL> random . shuffle ( l ) <EOL> return iter ( l ) <EOL> def pop ( self ) : <EOL> index = random . randint ( <NUM_LIT:0> , len ( self ) - <NUM_LIT:1> ) <EOL> item = list ( set . __iter__ ( self ) ) [ index ] <EOL> self . remove ( item ) <EOL> return item <EOL> def union ( self , other ) : <EOL> return RandomSet ( set . union ( self , other ) ) <EOL> def difference ( self , other ) : <EOL> return RandomSet ( set . difference ( self , other ) ) <EOL> def intersection ( self , other ) : <EOL> return RandomSet ( set . intersection ( self , other ) ) <EOL> def copy ( self ) : <EOL> return RandomSet ( self ) <EOL> def conforms_partial_ordering ( tuples , sorted_elements ) : <EOL> """<STR_LIT>""" <EOL> deps = defaultdict ( set ) <EOL> for parent , child in tuples : <EOL> deps [ parent ] . add ( child ) <EOL> for i , node in enumerate ( sorted_elements ) : <EOL> for n in sorted_elements [ i : ] : <EOL> if node in deps [ n ] : <EOL> return False <EOL> else : <EOL> return True <EOL> def all_partial_orderings ( tuples , elements ) : <EOL> edges = defaultdict ( set ) <EOL> for parent , child in tuples : <EOL> edges [ child ] . add ( parent ) <EOL> def _all_orderings ( elements ) : <EOL> if len ( elements ) == <NUM_LIT:1> : <EOL> yield list ( elements ) <EOL> else : <EOL> for elem in elements : <EOL> subset = set ( elements ) . difference ( [ elem ] ) <EOL> if not subset . intersection ( edges [ elem ] ) : <EOL> for sub_ordering in _all_orderings ( subset ) : <EOL> yield [ elem ] + sub_ordering <EOL> return iter ( _all_orderings ( elements ) ) <EOL> def function_named ( fn , name ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> fn . __name__ = name <EOL> except TypeError : <EOL> fn = types . FunctionType ( fn . __code__ , fn . __globals__ , name , <EOL> fn . __defaults__ , fn . __closure__ ) <EOL> return fn <EOL> def run_as_contextmanager ( ctx , fn , * arg , ** kw ) : <EOL> """<STR_LIT>""" <EOL> obj = ctx . __enter__ ( ) <EOL> try : <EOL> result = fn ( obj , * arg , ** kw ) <EOL> ctx . __exit__ ( None , None , None ) <EOL> return result <EOL> except : <EOL> exc_info = sys . exc_info ( ) <EOL> raise_ = ctx . __exit__ ( * exc_info ) <EOL> if raise_ is None : <EOL> raise <EOL> else : <EOL> return raise_ <EOL> def rowset ( results ) : <EOL> """<STR_LIT>""" <EOL> return set ( [ tuple ( row ) for row in results ] ) <EOL> def fail ( msg ) : <EOL> assert False , msg <EOL> @ decorator <EOL> def provide_metadata ( fn , * args , ** kw ) : <EOL> """<STR_LIT>""" <EOL> from . import config <EOL> from sqlalchemy import schema <EOL> metadata = schema . MetaData ( config . db ) <EOL> self = args [ <NUM_LIT:0> ] <EOL> prev_meta = getattr ( self , '<STR_LIT>' , None ) <EOL> self . metadata = metadata <EOL> try : <EOL> return fn ( * args , ** kw ) <EOL> finally : <EOL> metadata . drop_all ( ) <EOL> self . metadata = prev_meta <EOL> class adict ( dict ) : <EOL> """<STR_LIT>""" <EOL> def __getattribute__ ( self , key ) : <EOL> try : <EOL> return self [ key ] <EOL> except KeyError : <EOL> return dict . __getattribute__ ( self , key ) <EOL> def get_all ( self , * keys ) : <EOL> return tuple ( [ self [ key ] for key in keys ] ) </s>
<s> import re , getpass <EOL> from kokoropy import request <EOL> from kokoropy . model import DB_Model , or_ , and_ , Column , ForeignKey , func , Integer , String , Date , DateTime , Boolean , Text , relationship , backref , association_proxy <EOL> from _config import session , encrypt_password <EOL> from _all import engine , Cms , Group , Third_Party_Authenticator , Page , Page_Groups , Theme , Layout , Widget , Widget_Groups , User , User_Third_Party_Identities , User_Groups , Language , Language_Detail , Configuration <EOL> def do_login ( identity , password ) : <EOL> user_list = User . get ( and_ ( or_ ( User . username == identity , User . email == identity ) , User . encrypted_password == encrypt_password ( password ) ) ) <EOL> if len ( user_list ) > <NUM_LIT:0> : <EOL> user = user_list [ <NUM_LIT:0> ] <EOL> request . SESSION [ '<STR_LIT>' ] = user . id <EOL> return True <EOL> else : <EOL> return False <EOL> def do_logout ( ) : <EOL> request . SESSION . pop ( '<STR_LIT>' , None ) <EOL> def get_current_user ( ) : <EOL> if '<STR_LIT>' in request . SESSION : <EOL> user_id = request . SESSION [ '<STR_LIT>' ] <EOL> user = User . find ( user_id ) <EOL> return user <EOL> return None <EOL> def get_pages ( * criterion ) : <EOL> current_user = get_current_user ( ) <EOL> is_super_admin = current_user . super_admin if current_user is not None else False <EOL> current_user_id = current_user . id if current_user is not None else None <EOL> try : <EOL> subquery = session . query ( func . count ( Group . id ) . label ( '<STR_LIT>' ) , Page_Groups . fk_page ) . join ( User_Groups ) . join ( User ) . join ( Page_Groups ) . filter ( User . id == current_user_id ) . subquery ( "<STR_LIT>" ) <EOL> return session . query ( Page ) . filter ( Page . active == True ) . filter ( * criterion ) . filter ( <EOL> or_ ( <EOL> Page . authorization == '<STR_LIT>' , <EOL> and_ ( Page . authorization == '<STR_LIT>' , current_user is None ) , <EOL> and_ ( Page . authorization == '<STR_LIT>' , current_user is not None ) , <EOL> and_ ( Page . authorization == '<STR_LIT>' , is_super_admin ) , <EOL> and_ ( <EOL> or_ ( <EOL> Page . authorization == '<STR_LIT>' , <EOL> Page . authorization == '<STR_LIT>' <EOL> ) , <EOL> and_ ( <EOL> subquery . c . group_count > <NUM_LIT:0> , <EOL> subquery . c . fk_page == Page . _real_id <EOL> ) <EOL> ) <EOL> ) <EOL> ) . all ( ) <EOL> except Exception , e : <EOL> session . rollback ( ) <EOL> raise <EOL> def get_widgets ( * criterion ) : <EOL> current_user = get_current_user ( ) <EOL> is_super_admin = current_user . super_admin if current_user is not None else False <EOL> current_user_id = current_user . id if current_user is not None else None <EOL> try : <EOL> subquery = session . query ( func . count ( Group . id ) . label ( '<STR_LIT>' ) , Widget_Groups . fk_widget ) . join ( User_Groups ) . join ( User ) . join ( Widget_Groups ) . filter ( User . id == current_user_id ) . subquery ( "<STR_LIT>" ) <EOL> return session . query ( Widget ) . filter ( Widget . active == True ) . filter ( * criterion ) . filter ( <EOL> or_ ( <EOL> Widget . authorization == '<STR_LIT>' , <EOL> and_ ( Widget . authorization == '<STR_LIT>' , current_user is None ) , <EOL> and_ ( Widget . authorization == '<STR_LIT>' , current_user is not None ) , <EOL> and_ ( Widget . authorization == '<STR_LIT>' , is_super_admin ) , <EOL> and_ ( <EOL> or_ ( <EOL> Widget . authorization == '<STR_LIT>' , <EOL> Widget . authorization == '<STR_LIT>' <EOL> ) , <EOL> and_ ( <EOL> subquery . c . group_count > <NUM_LIT:0> , <EOL> subquery . c . fk_widget == Widget . _real_id <EOL> ) <EOL> ) <EOL> ) <EOL> ) . all ( ) <EOL> except Exception , e : <EOL> session . rollback ( ) <EOL> raise <EOL> def insert_default ( ) : <EOL> if Group . count ( ) == <NUM_LIT:0> : <EOL> super_admin = Group ( ) <EOL> super_admin . name = '<STR_LIT>' <EOL> super_admin . save ( ) <EOL> else : <EOL> super_admin = Group . get ( ) [ <NUM_LIT:0> ] <EOL> if User . count ( ) == <NUM_LIT:0> : <EOL> print ( '<STR_LIT>' ) <EOL> username = raw_input ( '<STR_LIT>' ) <EOL> realname = raw_input ( '<STR_LIT>' ) <EOL> email = '<STR_LIT>' <EOL> password = '<STR_LIT>' <EOL> confirm_password = '<STR_LIT>' <EOL> while True : <EOL> email = raw_input ( '<STR_LIT>' ) <EOL> if re . match ( r'<STR_LIT>' , email ) : <EOL> break <EOL> else : <EOL> print ( '<STR_LIT>' ) <EOL> while True : <EOL> password = getpass . getpass ( '<STR_LIT>' ) <EOL> confirm_password = getpass . getpass ( '<STR_LIT>' ) <EOL> if password == confirm_password : <EOL> break <EOL> else : <EOL> print ( '<STR_LIT>' ) <EOL> super_user = User ( ) <EOL> super_user . username = username <EOL> super_user . realname = realname <EOL> super_user . email = email <EOL> super_user . password = password <EOL> super_user . groups . append ( super_admin ) <EOL> super_user . save ( ) </s>
<s> import json <EOL> merchant_json = json . loads ( """<STR_LIT>""" ) <EOL> subscription_json = json . loads ( """<STR_LIT>""" ) <EOL> bill_json = json . loads ( """<STR_LIT>""" ) <EOL> preauth_json = json . loads ( """<STR_LIT>""" ) </s>
<s> import logging <EOL> from thespian . actors import ActorSystemMessage , ActorSystemFailure <EOL> try : <EOL> from logging . config import dictConfig <EOL> except ImportError : <EOL> from thespian . system . dictconfig import dictConfig <EOL> from datetime import timedelta , datetime <EOL> import multiprocessing <EOL> import traceback <EOL> from thespian . system . utilis import setProcName , thesplog_control <EOL> from thespian . system . messages . multiproc import * <EOL> from thespian . system . transport import TransmitIntent <EOL> MAX_LOGGING_STARTUP_DELAY = timedelta ( seconds = <NUM_LIT:3> ) <EOL> MAX_LOGGING_EXCEPTIONS_PER_SECOND = <NUM_LIT:20> <EOL> class LoggerExitRequest ( ActorSystemMessage ) : pass <EOL> class LoggerFileDup ( ActorSystemMessage ) : pass <EOL> def startupASLogger ( addrOfStarter , logEndpoint , logDefs , <EOL> transportClass , aggregatorAddress ) : <EOL> logging . root = logging . RootLogger ( logging . WARNING ) <EOL> logging . Logger . root = logging . root <EOL> logging . Logger . manager = logging . Manager ( logging . Logger . root ) <EOL> if logDefs : <EOL> dictConfig ( logDefs ) <EOL> else : <EOL> logging . basicConfig ( ) <EOL> thesplog_control ( logging . WARNING , False , <NUM_LIT:0> ) <EOL> transport = transportClass ( logEndpoint ) <EOL> setProcName ( '<STR_LIT>' , transport . myAddress ) <EOL> transport . scheduleTransmit ( None , TransmitIntent ( addrOfStarter , LoggerConnected ( ) ) ) <EOL> fdup = None <EOL> last_exception = None <EOL> last_exception_time = None <EOL> exception_count = <NUM_LIT:0> <EOL> while True : <EOL> try : <EOL> r = transport . run ( None ) <EOL> logrecord = r . message <EOL> if isinstance ( logrecord , LoggerExitRequest ) : <EOL> logging . info ( '<STR_LIT>' ) <EOL> return <EOL> elif isinstance ( logrecord , LoggerFileDup ) : <EOL> fdup = getattr ( logrecord , '<STR_LIT>' , None ) <EOL> elif isinstance ( logrecord , logging . LogRecord ) : <EOL> logging . getLogger ( logrecord . name ) . handle ( logrecord ) <EOL> if fdup : <EOL> with open ( fdup , '<STR_LIT:a>' ) as ldf : ldf . write ( '<STR_LIT>' % str ( logrecord ) ) <EOL> if aggregatorAddress and logrecord . levelno >= logging . WARNING : <EOL> transport . scheduleTransmit ( None , TransmitIntent ( aggregatorAddress , <EOL> logrecord ) ) <EOL> else : <EOL> logging . warn ( '<STR_LIT>' % str ( logrecord ) ) <EOL> except Exception : <EOL> logging . error ( '<STR_LIT>' , exception_count , exc_info = True ) <EOL> if last_exception is None or datetime . now ( ) - last_exception_time > timedelta ( seconds = <NUM_LIT:1> ) : <EOL> last_exception_time = datetime . now ( ) <EOL> exception_count = <NUM_LIT:0> <EOL> else : <EOL> exception_count += <NUM_LIT:1> <EOL> if exception_count >= MAX_LOGGING_EXCEPTIONS_PER_SECOND : <EOL> logging . error ( '<STR_LIT>' , <EOL> exception_count , datetime . now ( ) - last_exception_time ) <EOL> return <EOL> class ThespianLogForwardHandler ( logging . Handler ) : <EOL> def __init__ ( self , toAddr , transport ) : <EOL> logging . Handler . __init__ ( self , <NUM_LIT:1> ) <EOL> self . _name = '<STR_LIT>' <EOL> self . _fwdAddr = toAddr <EOL> if not self . _fwdAddr : <EOL> raise NotImplemented ( '<STR_LIT>' ) <EOL> self . _transport = transport <EOL> def handle ( self , record ) : <EOL> if record . exc_info : <EOL> if not record . exc_text : <EOL> excinfo = traceback . format_exception ( record . exc_info [ <NUM_LIT:0> ] , <EOL> record . exc_info [ <NUM_LIT:1> ] , <EOL> record . exc_info [ <NUM_LIT:2> ] ) <EOL> record . exc_text = '<STR_LIT:\n>' . join ( excinfo ) <EOL> record . exc_info = None <EOL> record . __dict__ [ '<STR_LIT>' ] = str ( self . _transport . myAddress ) <EOL> msg = record . getMessage ( ) <EOL> record . msg = msg <EOL> record . args = None <EOL> self . _transport . scheduleTransmit ( None , TransmitIntent ( self . _fwdAddr , record ) ) <EOL> class ThespianLogForwarder ( logging . Logger ) : <EOL> def __init__ ( self , toAddr , transport ) : <EOL> logging . Logger . __init__ ( self , '<STR_LIT:root>' , <NUM_LIT:1> ) <EOL> logging . Logger . addHandler ( self , ThespianLogForwardHandler ( toAddr , transport ) ) <EOL> def addHandler ( self , hdlr ) : <EOL> raise NotImplementedError ( '<STR_LIT>' ) <EOL> def removeHandler ( self , hdlr ) : <EOL> raise NotImplementedError ( '<STR_LIT>' ) </s>
<s> from thespian . actors import ActorAddress <EOL> from thespian . system . transport . asyncTransportBase import ( asyncTransportBase , <EOL> MAX_PENDING_TRANSMITS ) <EOL> from thespian . system . transport import TransmitIntent , SendStatus <EOL> import unittest <EOL> class FakeTransport ( asyncTransportBase ) : <EOL> def __init__ ( self ) : <EOL> super ( FakeTransport , self ) . __init__ ( ) <EOL> self . intents = [ ] <EOL> def _scheduleTransmitActual ( self , intent ) : <EOL> self . intents . append ( intent ) <EOL> def serializer ( self , intent ) : <EOL> intent . serialized = True <EOL> return intent <EOL> def forTestingCompleteAPendingIntent ( self , result ) : <EOL> for I in self . intents : <EOL> if I . result is None : <EOL> I . result = result <EOL> I . completionCallback ( ) <EOL> return <EOL> class TestAsyncTransportBase ( unittest . TestCase ) : <EOL> scope = '<STR_LIT>' <EOL> def setUp ( self ) : <EOL> self . testTrans = FakeTransport ( ) <EOL> def resetCounters ( self ) : <EOL> self . successCBcalls = <NUM_LIT:0> <EOL> self . failureCBcalls = <NUM_LIT:0> <EOL> def successCB ( self , result , arg ) : self . successCBcalls += <NUM_LIT:1> <EOL> def failureCB ( self , result , arg ) : self . failureCBcalls += <NUM_LIT:1> <EOL> def test_sendIntentToTransport ( self ) : <EOL> testIntent = TransmitIntent ( ActorAddress ( None ) , '<STR_LIT:message>' , <EOL> self . successCB , self . failureCB ) <EOL> self . testTrans . scheduleTransmit ( None , testIntent ) <EOL> self . assertEqual ( <NUM_LIT:1> , len ( self . testTrans . intents ) ) <EOL> def test_sendIntentToTransportSuccessCallback ( self ) : <EOL> self . resetCounters ( ) <EOL> testIntent = TransmitIntent ( ActorAddress ( <NUM_LIT:0> ) , '<STR_LIT:message>' , <EOL> self . successCB , self . failureCB ) <EOL> self . testTrans . scheduleTransmit ( None , testIntent ) <EOL> self . assertEqual ( <NUM_LIT:1> , len ( self . testTrans . intents ) ) <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Sent ) <EOL> self . assertEqual ( self . successCBcalls , <NUM_LIT:1> ) <EOL> self . assertEqual ( self . failureCBcalls , <NUM_LIT:0> ) <EOL> def test_sendIntentToTransportFailureCallback ( self ) : <EOL> self . resetCounters ( ) <EOL> testIntent = TransmitIntent ( ActorAddress ( None ) , '<STR_LIT:message>' , <EOL> self . successCB , self . failureCB ) <EOL> self . testTrans . scheduleTransmit ( None , testIntent ) <EOL> self . assertEqual ( <NUM_LIT:1> , len ( self . testTrans . intents ) ) <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Failed ) <EOL> self . assertEqual ( self . successCBcalls , <NUM_LIT:0> ) <EOL> self . assertEqual ( self . failureCBcalls , <NUM_LIT:1> ) <EOL> extraTransmitIds = range ( <NUM_LIT> , <NUM_LIT> ) <EOL> def test_sendIntentToTransportUpToLimitAndThenQueueInternally ( self ) : <EOL> for count in range ( MAX_PENDING_TRANSMITS ) : <EOL> self . testTrans . scheduleTransmit ( <EOL> None , <EOL> TransmitIntent ( ActorAddress ( '<STR_LIT>' ) , '<STR_LIT>' % count , <EOL> self . successCB , self . failureCB ) ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS , len ( self . testTrans . intents ) ) <EOL> for count in self . extraTransmitIds : <EOL> self . testTrans . scheduleTransmit ( <EOL> None , <EOL> TransmitIntent ( ActorAddress ( <NUM_LIT:9> ) , count , <EOL> self . successCB , self . failureCB ) ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS , len ( self . testTrans . intents ) ) <EOL> self . assertFalse ( [ I for I in self . testTrans . intents <EOL> if I . message in self . extraTransmitIds ] ) <EOL> def test_queueSendIntentIsSentOnSuccessCallbackOfPending ( self ) : <EOL> self . resetCounters ( ) <EOL> self . test_sendIntentToTransportUpToLimitAndThenQueueInternally ( ) <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Sent ) <EOL> self . assertEqual ( self . successCBcalls , <NUM_LIT:1> ) <EOL> self . assertEqual ( self . failureCBcalls , <NUM_LIT:0> ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS + <NUM_LIT:1> , len ( self . testTrans . intents ) ) <EOL> self . assertEqual ( <NUM_LIT:1> , len ( [ I for I in self . testTrans . intents <EOL> if I . message in self . extraTransmitIds ] ) ) <EOL> def test_queueSendIntentIsSentOnFailureCallbackOfPending ( self ) : <EOL> self . resetCounters ( ) <EOL> self . test_sendIntentToTransportUpToLimitAndThenQueueInternally ( ) <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Failed ) <EOL> self . assertEqual ( self . successCBcalls , <NUM_LIT:0> ) <EOL> self . assertEqual ( self . failureCBcalls , <NUM_LIT:1> ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS + <NUM_LIT:1> , len ( self . testTrans . intents ) ) <EOL> self . assertEqual ( <NUM_LIT:1> , len ( [ I for I in self . testTrans . intents <EOL> if I . message in self . extraTransmitIds ] ) ) <EOL> def test_allQueueSendIntentsAreSentOnEnoughPendingCallbackCompletions ( self ) : <EOL> numExtras = len ( self . extraTransmitIds ) <EOL> self . resetCounters ( ) <EOL> self . test_sendIntentToTransportUpToLimitAndThenQueueInternally ( ) <EOL> self . assertTrue ( MAX_PENDING_TRANSMITS > numExtras ) <EOL> for _extras in range ( numExtras ) : <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Sent ) <EOL> self . assertEqual ( self . successCBcalls , numExtras ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS + numExtras , len ( self . testTrans . intents ) ) <EOL> self . assertEqual ( numExtras , len ( [ I for I in self . testTrans . intents <EOL> if I . message in self . extraTransmitIds ] ) ) <EOL> def test_extraPendingCallbackCompletionsDoNothing ( self ) : <EOL> numExtras = len ( self . extraTransmitIds ) <EOL> self . resetCounters ( ) <EOL> self . test_sendIntentToTransportUpToLimitAndThenQueueInternally ( ) <EOL> self . assertTrue ( MAX_PENDING_TRANSMITS > numExtras + <NUM_LIT:3> ) <EOL> for _extras in range ( numExtras + <NUM_LIT:3> ) : <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Sent ) <EOL> self . assertEqual ( self . successCBcalls , numExtras + <NUM_LIT:3> ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS + numExtras , len ( self . testTrans . intents ) ) <EOL> self . assertEqual ( numExtras , len ( [ I for I in self . testTrans . intents <EOL> if I . message in self . extraTransmitIds ] ) ) <EOL> def test_pendingCallbacksClearQueueAndMoreRunsRunAdditionalQueuedOnMoreCompletions ( self ) : <EOL> numExtras = len ( self . extraTransmitIds ) <EOL> self . test_extraPendingCallbackCompletionsDoNothing ( ) <EOL> for _moreExtras in range ( numExtras + <NUM_LIT:3> ) : <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Sent ) <EOL> expectedCBCount = <NUM_LIT:2> * ( numExtras + <NUM_LIT:3> ) <EOL> self . assertEqual ( self . successCBcalls , expectedCBCount ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS + numExtras , len ( self . testTrans . intents ) ) <EOL> self . assertEqual ( numExtras , len ( [ I for I in self . testTrans . intents <EOL> if I . message in self . extraTransmitIds ] ) ) <EOL> for count in self . extraTransmitIds : <EOL> self . testTrans . scheduleTransmit ( <EOL> None , <EOL> TransmitIntent ( ActorAddress ( <NUM_LIT> ) , count , <EOL> self . successCB , self . failureCB ) ) <EOL> self . assertEqual ( self . successCBcalls , expectedCBCount ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS + <NUM_LIT:2> * numExtras , len ( self . testTrans . intents ) ) <EOL> self . assertEqual ( <NUM_LIT:2> * numExtras , len ( [ I for I in self . testTrans . intents <EOL> if I . message in self . extraTransmitIds ] ) ) <EOL> for _extras in range ( numExtras ) : <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Sent ) <EOL> expectedCBCount += numExtras <EOL> self . assertEqual ( self . successCBcalls , expectedCBCount ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS + numExtras + numExtras , <EOL> len ( self . testTrans . intents ) ) <EOL> self . assertEqual ( <NUM_LIT:2> * numExtras , len ( [ I for I in self . testTrans . intents <EOL> if I . message in self . extraTransmitIds ] ) ) <EOL> def test_transmitsCompletingWithCallbackDoNotQueue ( self ) : <EOL> self . resetCounters ( ) <EOL> for count in range ( MAX_PENDING_TRANSMITS ) : <EOL> self . testTrans . scheduleTransmit ( <EOL> None , <EOL> TransmitIntent ( ActorAddress ( self ) , '<STR_LIT>' % count , <EOL> self . successCB , self . failureCB ) ) <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Sent ) <EOL> self . assertEqual ( self . successCBcalls , MAX_PENDING_TRANSMITS ) <EOL> numExtras = len ( self . extraTransmitIds ) <EOL> for count in self . extraTransmitIds : <EOL> self . testTrans . scheduleTransmit ( <EOL> None , <EOL> TransmitIntent ( ActorAddress ( self . testTrans ) , count , <EOL> self . successCB , self . failureCB ) ) <EOL> self . testTrans . forTestingCompleteAPendingIntent ( SendStatus . Sent ) <EOL> self . assertEqual ( MAX_PENDING_TRANSMITS + numExtras , len ( self . testTrans . intents ) ) <EOL> self . assertEqual ( numExtras , len ( [ I for I in self . testTrans . intents <EOL> if I . message in self . extraTransmitIds ] ) ) </s>
<s> from unittest import TestCase <EOL> from thespian . actors import requireCapability <EOL> class TestRequireCapability ( TestCase ) : <EOL> scope = "<STR_LIT>" <EOL> @ requireCapability ( '<STR_LIT>' ) <EOL> class req1 : pass <EOL> def test_oneReq ( self ) : <EOL> self . assertFalse ( TestRequireCapability . req1 . actorSystemCapabilityCheck ( { } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req1 . actorSystemCapabilityCheck ( { '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertTrue ( TestRequireCapability . req1 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertTrue ( TestRequireCapability . req1 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertTrue ( TestRequireCapability . req1 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertTrue ( TestRequireCapability . req1 . actorSystemCapabilityCheck ( { '<STR_LIT>' : False , '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertTrue ( TestRequireCapability . req1 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req1 . actorSystemCapabilityCheck ( { '<STR_LIT>' : False , '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req1 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> @ requireCapability ( '<STR_LIT>' ) <EOL> @ requireCapability ( '<STR_LIT>' ) <EOL> class req2 : pass <EOL> def test_twoReq ( self ) : <EOL> self . assertFalse ( TestRequireCapability . req2 . actorSystemCapabilityCheck ( { } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2 . actorSystemCapabilityCheck ( { '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertTrue ( TestRequireCapability . req2 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2 . actorSystemCapabilityCheck ( { '<STR_LIT>' : False , '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertTrue ( TestRequireCapability . req2 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2 . actorSystemCapabilityCheck ( { '<STR_LIT>' : False , '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2 . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> @ requireCapability ( '<STR_LIT>' ) <EOL> @ requireCapability ( '<STR_LIT>' ) <EOL> class req2rev : pass <EOL> def test_twoReqReverse ( self ) : <EOL> self . assertFalse ( TestRequireCapability . req2rev . actorSystemCapabilityCheck ( { } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2rev . actorSystemCapabilityCheck ( { '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2rev . actorSystemCapabilityCheck ( { '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2rev . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertTrue ( TestRequireCapability . req2rev . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2rev . actorSystemCapabilityCheck ( { '<STR_LIT>' : False , '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertTrue ( TestRequireCapability . req2rev . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2rev . actorSystemCapabilityCheck ( { '<STR_LIT>' : False , '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( TestRequireCapability . req2rev . actorSystemCapabilityCheck ( { '<STR_LIT>' : True , '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> @ requireCapability ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> class req3rev : pass <EOL> def test_threeReq ( self ) : <EOL> check3 = TestRequireCapability . req3rev . actorSystemCapabilityCheck <EOL> self . assertTrue ( check3 ( { '<STR_LIT>' : '<STR_LIT>' } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( check3 ( { '<STR_LIT>' : '<STR_LIT>' } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( check3 ( { '<STR_LIT>' : True } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( check3 ( { '<STR_LIT>' : False } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( check3 ( { '<STR_LIT>' : <NUM_LIT:1> } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( check3 ( { '<STR_LIT>' : <NUM_LIT:0> } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( check3 ( { '<STR_LIT>' : None } , <NUM_LIT:0> ) ) <EOL> self . assertFalse ( check3 ( { '<STR_LIT>' : '<STR_LIT>' } , <NUM_LIT:0> ) ) <EOL> class TestRequireRequirements ( TestCase ) : <EOL> scope = "<STR_LIT>" <EOL> class req1 : <EOL> @ staticmethod <EOL> def actorSystemCapabilityCheck ( cap , req ) : <EOL> return req . get ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) == '<STR_LIT>' <EOL> def test_ActorReqs ( self ) : <EOL> reqCheck = TestRequireRequirements . req1 . actorSystemCapabilityCheck <EOL> self . assertFalse ( reqCheck ( { } , { } ) ) <EOL> self . assertFalse ( reqCheck ( { } , { '<STR_LIT:foo>' : None } ) ) <EOL> self . assertFalse ( reqCheck ( { } , { '<STR_LIT:foo>' : True } ) ) <EOL> self . assertFalse ( reqCheck ( { } , { '<STR_LIT:foo>' : '<STR_LIT>' } ) ) <EOL> self . assertFalse ( reqCheck ( { } , { '<STR_LIT>' : '<STR_LIT>' } ) ) <EOL> self . assertTrue ( reqCheck ( { } , { '<STR_LIT:foo>' : '<STR_LIT>' } ) ) <EOL> self . assertTrue ( reqCheck ( { } , { '<STR_LIT:foo>' : '<STR_LIT>' , '<STR_LIT:bar>' : '<STR_LIT:foo>' } ) ) </s>
<s> from docker_squash . version import version <EOL> __version__ = version </s>
<s> import sys <EOL> from PyQt5 import QtWidgets <EOL> from PyQt5 import QtPrintSupport <EOL> from PyQt5 import QtGui , QtCore <EOL> from PyQt5 . QtCore import Qt <EOL> from ext import * <EOL> class Main ( QtWidgets . QMainWindow ) : <EOL> def __init__ ( self , parent = None ) : <EOL> QtWidgets . QMainWindow . __init__ ( self , parent ) <EOL> self . filename = "<STR_LIT>" <EOL> self . initUI ( ) <EOL> def initToolbar ( self ) : <EOL> self . newAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . newAction . setShortcut ( "<STR_LIT>" ) <EOL> self . newAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . newAction . triggered . connect ( self . new ) <EOL> self . openAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . openAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . openAction . setShortcut ( "<STR_LIT>" ) <EOL> self . openAction . triggered . connect ( self . open ) <EOL> self . saveAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . saveAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . saveAction . setShortcut ( "<STR_LIT>" ) <EOL> self . saveAction . triggered . connect ( self . save ) <EOL> self . printAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . printAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . printAction . setShortcut ( "<STR_LIT>" ) <EOL> self . printAction . triggered . connect ( self . printHandler ) <EOL> self . previewAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . previewAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . previewAction . setShortcut ( "<STR_LIT>" ) <EOL> self . previewAction . triggered . connect ( self . preview ) <EOL> self . findAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . findAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . findAction . setShortcut ( "<STR_LIT>" ) <EOL> self . findAction . triggered . connect ( find . Find ( self ) . show ) <EOL> self . cutAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . cutAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . cutAction . setShortcut ( "<STR_LIT>" ) <EOL> self . cutAction . triggered . connect ( self . text . cut ) <EOL> self . copyAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . copyAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . copyAction . setShortcut ( "<STR_LIT>" ) <EOL> self . copyAction . triggered . connect ( self . text . copy ) <EOL> self . pasteAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . pasteAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . pasteAction . setShortcut ( "<STR_LIT>" ) <EOL> self . pasteAction . triggered . connect ( self . text . paste ) <EOL> self . undoAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . undoAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . undoAction . setShortcut ( "<STR_LIT>" ) <EOL> self . undoAction . triggered . connect ( self . text . undo ) <EOL> self . redoAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> self . redoAction . setStatusTip ( "<STR_LIT>" ) <EOL> self . redoAction . setShortcut ( "<STR_LIT>" ) <EOL> self . redoAction . triggered . connect ( self . text . redo ) <EOL> wordCountAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> wordCountAction . setStatusTip ( "<STR_LIT>" ) <EOL> wordCountAction . setShortcut ( "<STR_LIT>" ) <EOL> wordCountAction . triggered . connect ( self . wordCount ) <EOL> imageAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> imageAction . setStatusTip ( "<STR_LIT>" ) <EOL> imageAction . setShortcut ( "<STR_LIT>" ) <EOL> imageAction . triggered . connect ( self . insertImage ) <EOL> bulletAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> bulletAction . setStatusTip ( "<STR_LIT>" ) <EOL> bulletAction . setShortcut ( "<STR_LIT>" ) <EOL> bulletAction . triggered . connect ( self . bulletList ) <EOL> numberedAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> numberedAction . setStatusTip ( "<STR_LIT>" ) <EOL> numberedAction . setShortcut ( "<STR_LIT>" ) <EOL> numberedAction . triggered . connect ( self . numberList ) <EOL> self . toolbar = self . addToolBar ( "<STR_LIT>" ) <EOL> self . toolbar . addAction ( self . newAction ) <EOL> self . toolbar . addAction ( self . openAction ) <EOL> self . toolbar . addAction ( self . saveAction ) <EOL> self . toolbar . addSeparator ( ) <EOL> self . toolbar . addAction ( self . printAction ) <EOL> self . toolbar . addAction ( self . previewAction ) <EOL> self . toolbar . addSeparator ( ) <EOL> self . toolbar . addAction ( self . cutAction ) <EOL> self . toolbar . addAction ( self . copyAction ) <EOL> self . toolbar . addAction ( self . pasteAction ) <EOL> self . toolbar . addAction ( self . undoAction ) <EOL> self . toolbar . addAction ( self . redoAction ) <EOL> self . toolbar . addSeparator ( ) <EOL> self . toolbar . addAction ( self . findAction ) <EOL> self . toolbar . addAction ( wordCountAction ) <EOL> self . toolbar . addAction ( imageAction ) <EOL> self . toolbar . addSeparator ( ) <EOL> self . toolbar . addAction ( bulletAction ) <EOL> self . toolbar . addAction ( numberedAction ) <EOL> self . addToolBarBreak ( ) <EOL> def initFormatbar ( self ) : <EOL> fontBox = QtWidgets . QFontComboBox ( self ) <EOL> fontBox . currentFontChanged . connect ( lambda font : self . text . setCurrentFont ( font ) ) <EOL> fontSize = QtWidgets . QSpinBox ( self ) <EOL> fontSize . setSuffix ( "<STR_LIT>" ) <EOL> fontSize . valueChanged . connect ( lambda size : self . text . setFontPointSize ( size ) ) <EOL> fontSize . setValue ( <NUM_LIT> ) <EOL> fontColor = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> fontColor . triggered . connect ( self . fontColorChanged ) <EOL> boldAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> boldAction . triggered . connect ( self . bold ) <EOL> italicAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> italicAction . triggered . connect ( self . italic ) <EOL> underlAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> underlAction . triggered . connect ( self . underline ) <EOL> strikeAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> strikeAction . triggered . connect ( self . strike ) <EOL> superAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> superAction . triggered . connect ( self . superScript ) <EOL> subAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> subAction . triggered . connect ( self . subScript ) <EOL> alignLeft = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> alignLeft . triggered . connect ( self . alignLeft ) <EOL> alignCenter = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> alignCenter . triggered . connect ( self . alignCenter ) <EOL> alignRight = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> alignRight . triggered . connect ( self . alignRight ) <EOL> alignJustify = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> alignJustify . triggered . connect ( self . alignJustify ) <EOL> indentAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> indentAction . setShortcut ( "<STR_LIT>" ) <EOL> indentAction . triggered . connect ( self . indent ) <EOL> dedentAction = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> dedentAction . setShortcut ( "<STR_LIT>" ) <EOL> dedentAction . triggered . connect ( self . dedent ) <EOL> backColor = QtWidgets . QAction ( QtGui . QIcon ( "<STR_LIT>" ) , "<STR_LIT>" , self ) <EOL> backColor . triggered . connect ( self . highlight ) <EOL> self . formatbar = self . addToolBar ( "<STR_LIT>" ) <EOL> self . formatbar . addWidget ( fontBox ) <EOL> self . formatbar . addWidget ( fontSize ) <EOL> self . formatbar . addSeparator ( ) <EOL> self . formatbar . addAction ( fontColor ) <EOL> self . formatbar . addAction ( backColor ) <EOL> self . formatbar . addSeparator ( ) <EOL> self . formatbar . addAction ( boldAction ) <EOL> self . formatbar . addAction ( italicAction ) <EOL> self . formatbar . addAction ( underlAction ) <EOL> self . formatbar . addAction ( strikeAction ) <EOL> self . formatbar . addAction ( superAction ) <EOL> self . formatbar . addAction ( subAction ) <EOL> self . formatbar . addSeparator ( ) <EOL> self . formatbar . addAction ( alignLeft ) <EOL> self . formatbar . addAction ( alignCenter ) <EOL> self . formatbar . addAction ( alignRight ) <EOL> self . formatbar . addAction ( alignJustify ) <EOL> self . formatbar . addSeparator ( ) <EOL> self . formatbar . addAction ( indentAction ) <EOL> self . formatbar . addAction ( dedentAction ) <EOL> def initMenubar ( self ) : <EOL> menubar = self . menuBar ( ) <EOL> file = menubar . addMenu ( "<STR_LIT>" ) <EOL> edit = menubar . addMenu ( "<STR_LIT>" ) <EOL> view = menubar . addMenu ( "<STR_LIT>" ) <EOL> file . addAction ( self . newAction ) <EOL> file . addAction ( self . openAction ) <EOL> file . addAction ( self . saveAction ) <EOL> file . addAction ( self . printAction ) <EOL> file . addAction ( self . previewAction ) <EOL> edit . addAction ( self . undoAction ) <EOL> edit . addAction ( self . redoAction ) <EOL> edit . addAction ( self . cutAction ) <EOL> edit . addAction ( self . copyAction ) <EOL> edit . addAction ( self . pasteAction ) <EOL> edit . addAction ( self . findAction ) <EOL> toolbarAction = QtWidgets . QAction ( "<STR_LIT>" , self ) <EOL> toolbarAction . triggered . connect ( self . toggleToolbar ) <EOL> formatbarAction = QtWidgets . QAction ( "<STR_LIT>" , self ) <EOL> formatbarAction . triggered . connect ( self . toggleFormatbar ) <EOL> statusbarAction = QtWidgets . QAction ( "<STR_LIT>" , self ) <EOL> statusbarAction . triggered . connect ( self . toggleStatusbar ) <EOL> view . addAction ( toolbarAction ) <EOL> view . addAction ( formatbarAction ) <EOL> view . addAction ( statusbarAction ) <EOL> def initUI ( self ) : <EOL> self . text = QtWidgets . QTextEdit ( self ) <EOL> self . text . setTabStopWidth ( <NUM_LIT> ) <EOL> self . initToolbar ( ) <EOL> self . initFormatbar ( ) <EOL> self . initMenubar ( ) <EOL> self . setCentralWidget ( self . text ) <EOL> self . statusbar = self . statusBar ( ) <EOL> self . text . cursorPositionChanged . connect ( self . cursorPosition ) <EOL> self . setGeometry ( <NUM_LIT:100> , <NUM_LIT:100> , <NUM_LIT> , <NUM_LIT> ) <EOL> self . setWindowTitle ( "<STR_LIT>" ) <EOL> self . setWindowIcon ( QtGui . QIcon ( "<STR_LIT>" ) ) <EOL> def toggleToolbar ( self ) : <EOL> state = self . toolbar . isVisible ( ) <EOL> self . toolbar . setVisible ( not state ) <EOL> def toggleFormatbar ( self ) : <EOL> state = self . formatbar . isVisible ( ) <EOL> self . formatbar . setVisible ( not state ) <EOL> def toggleStatusbar ( self ) : <EOL> state = self . statusbar . isVisible ( ) <EOL> self . statusbar . setVisible ( not state ) <EOL> def new ( self ) : <EOL> spawn = Main ( ) <EOL> spawn . show ( ) <EOL> def open ( self ) : <EOL> self . filename = QtWidgets . QFileDialog . getOpenFileName ( self , '<STR_LIT>' , "<STR_LIT:.>" , "<STR_LIT>" ) [ <NUM_LIT:0> ] <EOL> if self . filename : <EOL> with open ( self . filename , "<STR_LIT>" ) as file : <EOL> self . text . setText ( file . read ( ) ) <EOL> def save ( self ) : <EOL> if not self . filename : <EOL> self . filename = QtWidgets . QFileDialog . getSaveFileName ( self , '<STR_LIT>' ) [ <NUM_LIT:0> ] <EOL> if self . filename : <EOL> if not self . filename . endswith ( "<STR_LIT>" ) : <EOL> self . filename += "<STR_LIT>" <EOL> with open ( self . filename , "<STR_LIT>" ) as file : <EOL> file . write ( self . text . toHtml ( ) ) <EOL> self . changesSaved = True <EOL> def preview ( self ) : <EOL> preview = QtPrintSupport . QPrintPreviewDialog ( ) <EOL> preview . paintRequested . connect ( lambda p : self . text . print_ ( p ) ) <EOL> preview . exec_ ( ) <EOL> def printHandler ( self ) : <EOL> dialog = QtPrintSupport . QPrintDialog ( ) <EOL> if dialog . exec_ ( ) == QtWidgets . QDialog . Accepted : <EOL> self . text . document ( ) . print_ ( dialog . printer ( ) ) <EOL> def cursorPosition ( self ) : <EOL> cursor = self . text . textCursor ( ) <EOL> line = cursor . blockNumber ( ) + <NUM_LIT:1> <EOL> col = cursor . columnNumber ( ) <EOL> self . statusbar . showMessage ( "<STR_LIT>" . format ( line , col ) ) <EOL> def wordCount ( self ) : <EOL> wc = wordcount . WordCount ( self ) <EOL> wc . getText ( ) <EOL> wc . show ( ) <EOL> def insertImage ( self ) : <EOL> filename = QtWidgets . QFileDialog . getOpenFileName ( self , '<STR_LIT>' , "<STR_LIT:.>" , "<STR_LIT>" ) <EOL> if filename : <EOL> image = QtGui . QImage ( filename ) <EOL> if image . isNull ( ) : <EOL> popup = QtWidgets . QMessageBox ( QtWidgets . QMessageBox . Critical , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> QtWidgets . QMessageBox . Ok , <EOL> self ) <EOL> popup . show ( ) <EOL> else : <EOL> cursor = self . text . textCursor ( ) <EOL> cursor . insertImage ( image , filename ) <EOL> def fontColorChanged ( self ) : <EOL> color = QtWidgets . QColorDialog . getColor ( ) <EOL> self . text . setTextColor ( color ) <EOL> def highlight ( self ) : <EOL> color = QtWidgets . QColorDialog . getColor ( ) <EOL> self . text . setTextBackgroundColor ( color ) <EOL> def bold ( self ) : <EOL> if self . text . fontWeight ( ) == QtGui . QFont . Bold : <EOL> self . text . setFontWeight ( QtGui . QFont . Normal ) <EOL> else : <EOL> self . text . setFontWeight ( QtGui . QFont . Bold ) <EOL> def italic ( self ) : <EOL> state = self . text . fontItalic ( ) <EOL> self . text . setFontItalic ( not state ) <EOL> def underline ( self ) : <EOL> state = self . text . fontUnderline ( ) <EOL> self . text . setFontUnderline ( not state ) <EOL> def strike ( self ) : <EOL> fmt = self . text . currentCharFormat ( ) <EOL> fmt . setFontStrikeOut ( not fmt . fontStrikeOut ( ) ) <EOL> self . text . setCurrentCharFormat ( fmt ) <EOL> def superScript ( self ) : <EOL> fmt = self . text . currentCharFormat ( ) <EOL> align = fmt . verticalAlignment ( ) <EOL> if align == QtGui . QTextCharFormat . AlignNormal : <EOL> fmt . setVerticalAlignment ( QtGui . QTextCharFormat . AlignSuperScript ) <EOL> else : <EOL> fmt . setVerticalAlignment ( QtGui . QTextCharFormat . AlignNormal ) <EOL> self . text . setCurrentCharFormat ( fmt ) <EOL> def subScript ( self ) : <EOL> fmt = self . text . currentCharFormat ( ) <EOL> align = fmt . verticalAlignment ( ) <EOL> if align == QtGui . QTextCharFormat . AlignNormal : <EOL> fmt . setVerticalAlignment ( QtGui . QTextCharFormat . AlignSubScript ) <EOL> else : <EOL> fmt . setVerticalAlignment ( QtGui . QTextCharFormat . AlignNormal ) <EOL> self . text . setCurrentCharFormat ( fmt ) <EOL> def alignLeft ( self ) : <EOL> self . text . setAlignment ( Qt . AlignLeft ) <EOL> def alignRight ( self ) : <EOL> self . text . setAlignment ( Qt . AlignRight ) <EOL> def alignCenter ( self ) : <EOL> self . text . setAlignment ( Qt . AlignCenter ) <EOL> def alignJustify ( self ) : <EOL> self . text . setAlignment ( Qt . AlignJustify ) <EOL> def indent ( self ) : <EOL> cursor = self . text . textCursor ( ) <EOL> if cursor . hasSelection ( ) : <EOL> temp = cursor . blockNumber ( ) <EOL> cursor . setPosition ( cursor . anchor ( ) ) <EOL> diff = cursor . blockNumber ( ) - temp <EOL> direction = QtGui . QTextCursor . Up if diff > <NUM_LIT:0> else QtGui . QTextCursor . Down <EOL> for n in range ( abs ( diff ) + <NUM_LIT:1> ) : <EOL> cursor . movePosition ( QtGui . QTextCursor . StartOfLine ) <EOL> cursor . insertText ( "<STR_LIT:\t>" ) <EOL> cursor . movePosition ( direction ) <EOL> else : <EOL> cursor . insertText ( "<STR_LIT:\t>" ) <EOL> def handleDedent ( self , cursor ) : <EOL> cursor . movePosition ( QtGui . QTextCursor . StartOfLine ) <EOL> line = cursor . block ( ) . text ( ) <EOL> if line . startswith ( "<STR_LIT:\t>" ) : <EOL> cursor . deleteChar ( ) <EOL> else : <EOL> for char in line [ : <NUM_LIT:8> ] : <EOL> if char != "<STR_LIT:U+0020>" : <EOL> break <EOL> cursor . deleteChar ( ) <EOL> def dedent ( self ) : <EOL> cursor = self . text . textCursor ( ) <EOL> if cursor . hasSelection ( ) : <EOL> temp = cursor . blockNumber ( ) <EOL> cursor . setPosition ( cursor . anchor ( ) ) <EOL> diff = cursor . blockNumber ( ) - temp <EOL> direction = QtGui . QTextCursor . Up if diff > <NUM_LIT:0> else QtGui . QTextCursor . Down <EOL> for n in range ( abs ( diff ) + <NUM_LIT:1> ) : <EOL> self . handleDedent ( cursor ) <EOL> cursor . movePosition ( direction ) <EOL> else : <EOL> self . handleDedent ( cursor ) <EOL> def bulletList ( self ) : <EOL> cursor = self . text . textCursor ( ) <EOL> cursor . insertList ( QtGui . QTextListFormat . ListDisc ) <EOL> def numberList ( self ) : <EOL> cursor = self . text . textCursor ( ) <EOL> cursor . insertList ( QtGui . QTextListFormat . ListDecimal ) <EOL> def main ( ) : <EOL> app = QtWidgets . QApplication ( sys . argv ) <EOL> main = Main ( ) <EOL> main . show ( ) <EOL> sys . exit ( app . exec_ ( ) ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> main ( ) </s>
<s> """<STR_LIT>""" <EOL> import argparse <EOL> import datetime <EOL> import glob <EOL> import logging <EOL> import os <EOL> import simplejson <EOL> import sys <EOL> import yaml <EOL> from smoker . client import Client <EOL> import smoker . logger <EOL> from smoker . client . out_junit import plugins_to_xml <EOL> from smoker . util . tap import TapTest , Tap <EOL> smoker . logger . init ( syslog = False ) <EOL> lg = logging . getLogger ( '<STR_LIT>' ) <EOL> COLORS = { <EOL> '<STR_LIT:default>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } <EOL> EXIT_CODES = { <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : <NUM_LIT:0> <EOL> } <EOL> CONFIG_FILE = '<STR_LIT>' <EOL> def _get_plugins ( ) : <EOL> """<STR_LIT>""" <EOL> plugins = [ ] <EOL> conf_file = os . path . expanduser ( '<STR_LIT>' ) <EOL> if not os . path . exists ( conf_file ) : <EOL> conf_file = CONFIG_FILE <EOL> if not os . path . exists ( conf_file ) : <EOL> return plugins <EOL> with open ( conf_file ) as f : <EOL> config = yaml . safe_load ( f ) <EOL> if config and '<STR_LIT>' in config : <EOL> paths = config [ '<STR_LIT>' ] <EOL> else : <EOL> raise Exception ( '<STR_LIT>' ) <EOL> for path in paths : <EOL> try : <EOL> module = __import__ ( path ) <EOL> except ImportError : <EOL> raise Exception ( '<STR_LIT>' ) <EOL> toplevel = os . path . dirname ( module . __file__ ) <EOL> submodule = '<STR_LIT:/>' . join ( path . split ( '<STR_LIT:.>' ) [ <NUM_LIT:1> : ] ) <EOL> plugin_dir = os . path . join ( toplevel , submodule , '<STR_LIT>' ) <EOL> modules = [ os . path . basename ( name ) [ : - <NUM_LIT:3> ] for name in <EOL> glob . glob ( plugin_dir ) ] <EOL> modules . remove ( '<STR_LIT>' ) <EOL> plugins += [ '<STR_LIT>' % ( path , name ) for name in modules ] <EOL> return plugins <EOL> def _get_plugin_arguments ( name ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> plugin = __import__ ( name , globals ( ) , locals ( ) , [ '<STR_LIT>' ] ) <EOL> except ImportError as e : <EOL> lg . error ( "<STR_LIT>" % ( name , e ) ) <EOL> raise <EOL> return plugin . HostDiscoveryPlugin . arguments <EOL> def _add_plugin_arguments ( parser ) : <EOL> """<STR_LIT>""" <EOL> plugins = _get_plugins ( ) <EOL> if not plugins : <EOL> return <EOL> argument_group = parser . add_argument_group ( '<STR_LIT>' ) <EOL> for plugin in plugins : <EOL> args = _get_plugin_arguments ( plugin ) <EOL> for argument in args : <EOL> argument_group . add_argument ( * argument . args , ** argument . kwargs ) <EOL> def _run_discovery_plugin ( name , args ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> this_plugin = __import__ ( name , globals ( ) , locals ( ) , <EOL> [ '<STR_LIT>' ] ) <EOL> except ImportError as e : <EOL> lg . error ( "<STR_LIT>" % ( name , e ) ) <EOL> raise <EOL> plugin = this_plugin . HostDiscoveryPlugin ( ) <EOL> return plugin . get_hosts ( args ) <EOL> def _host_discovery ( args ) : <EOL> """<STR_LIT>""" <EOL> discovered = [ ] <EOL> for plugin in _get_plugins ( ) : <EOL> hosts = _run_discovery_plugin ( plugin , args ) <EOL> if hosts : <EOL> discovered += hosts <EOL> return discovered <EOL> def main ( ) : <EOL> """<STR_LIT>""" <EOL> parser = argparse . ArgumentParser ( <EOL> description = '<STR_LIT>' , add_help = False ) <EOL> group_action = parser . add_argument_group ( '<STR_LIT>' ) <EOL> group_action . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_action . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT:list>' , action = '<STR_LIT:store_true>' , help = "<STR_LIT>" ) <EOL> group_action . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_main = parser . add_argument_group ( '<STR_LIT>' ) <EOL> group_main . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT>' , nargs = '<STR_LIT:+>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters = parser . add_argument_group ( '<STR_LIT>' ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT>' , nargs = '<STR_LIT:+>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , nargs = '<STR_LIT:+>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , default = [ ] , nargs = '<STR_LIT:+>' , <EOL> help = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , default = [ ] , nargs = '<STR_LIT:+>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_filters . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_output = parser . add_argument_group ( '<STR_LIT>' ) <EOL> group_output . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT>' , default = '<STR_LIT>' , <EOL> help = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) ) <EOL> group_output . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_output . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_output . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_output . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_output . add_argument ( <EOL> '<STR_LIT>' , '<STR_LIT>' , dest = '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> help = "<STR_LIT>" ) <EOL> group_output . add_argument ( <EOL> '<STR_LIT>' , dest = '<STR_LIT>' , <EOL> help = "<STR_LIT>" ) <EOL> _add_plugin_arguments ( parser ) <EOL> args = parser . parse_args ( ) <EOL> if args . verbose : <EOL> lg . setLevel ( logging . INFO ) <EOL> args . no_progress = True <EOL> if args . debug : <EOL> lg . setLevel ( logging . DEBUG ) <EOL> args . no_progress = True <EOL> if args . help : <EOL> parser . print_help ( ) <EOL> sys . exit ( <NUM_LIT:0> ) <EOL> if args . pretty == '<STR_LIT>' : <EOL> if not args . no_colors : <EOL> format_host = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS <EOL> } <EOL> format_plugin_component = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> else : <EOL> format_host = '<STR_LIT>' <EOL> format_plugin = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> format_plugin_component = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } <EOL> format_plugin_msg = '<STR_LIT>' <EOL> format_plugin_component_msg = '<STR_LIT>' <EOL> format_plugin_run = '<STR_LIT>' <EOL> format_plugin_param = '<STR_LIT>' <EOL> elif args . pretty == '<STR_LIT>' : <EOL> if not args . no_colors : <EOL> format_host = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS <EOL> } <EOL> format_plugin_msg = { <EOL> '<STR_LIT:info>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT:error>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin_component = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin_component_msg = { <EOL> '<STR_LIT:info>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT:error>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> else : <EOL> format_host = '<STR_LIT>' <EOL> format_plugin = '<STR_LIT>' <EOL> format_plugin_msg = { <EOL> '<STR_LIT:info>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT:error>' : '<STR_LIT>' , <EOL> } <EOL> format_plugin_component = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } <EOL> format_plugin_component_msg = { <EOL> '<STR_LIT:info>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT:error>' : '<STR_LIT>' , <EOL> } <EOL> format_plugin_run = '<STR_LIT>' <EOL> format_plugin_param = '<STR_LIT>' <EOL> elif args . pretty == '<STR_LIT>' : <EOL> if not args . no_colors : <EOL> format_host = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS <EOL> } <EOL> format_plugin_msg = { <EOL> '<STR_LIT:info>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT:error>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin_component = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin_component_msg = { <EOL> '<STR_LIT:info>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT:error>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> else : <EOL> format_host = '<STR_LIT>' <EOL> format_plugin = '<STR_LIT>' <EOL> format_plugin_msg = '<STR_LIT>' <EOL> format_plugin_component = '<STR_LIT>' <EOL> format_plugin_component_msg = '<STR_LIT>' <EOL> format_plugin_run = '<STR_LIT>' <EOL> format_plugin_param = '<STR_LIT>' <EOL> elif args . pretty == '<STR_LIT>' : <EOL> if not args . no_colors : <EOL> format_host = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS <EOL> } <EOL> format_plugin_msg = { <EOL> '<STR_LIT:info>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT:error>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin_component = { <EOL> '<STR_LIT:OK>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> format_plugin_component_msg = { <EOL> '<STR_LIT:info>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT>' : '<STR_LIT>' % COLORS , <EOL> '<STR_LIT:error>' : '<STR_LIT>' % COLORS , <EOL> } <EOL> else : <EOL> format_host = '<STR_LIT>' <EOL> format_plugin = '<STR_LIT>' <EOL> format_plugin_msg = '<STR_LIT>' <EOL> format_plugin_component = '<STR_LIT>' <EOL> format_plugin_component_msg = '<STR_LIT>' <EOL> format_plugin_run = '<STR_LIT>' <EOL> format_plugin_param = '<STR_LIT>' <EOL> elif args . pretty in [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] : <EOL> pass <EOL> else : <EOL> lg . error ( "<STR_LIT>" % args . pretty ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> if args . category : <EOL> args . filter . append ( '<STR_LIT>' % args . category ) <EOL> if args . component : <EOL> args . filter . append ( '<STR_LIT>' % args . component ) <EOL> if args . health or args . smoke : <EOL> if args . health : <EOL> args . filter . append ( '<STR_LIT>' ) <EOL> if args . smoke : <EOL> args . filter . append ( '<STR_LIT>' ) <EOL> filters = [ ] <EOL> if args . filter : <EOL> for f in args . filter : <EOL> filter = { } <EOL> try : <EOL> filter = { <EOL> '<STR_LIT:key>' : f . split ( '<STR_LIT:U+0020>' ) [ <NUM_LIT:0> ] , <EOL> '<STR_LIT:value>' : f . split ( '<STR_LIT:U+0020>' ) [ <NUM_LIT:1> ] <EOL> } <EOL> except : <EOL> lg . error ( "<STR_LIT>" ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> filters . append ( filter ) <EOL> if filters and args . plugins : <EOL> lg . warn ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> if args . plugins : <EOL> filters . append ( args . plugins ) <EOL> states = [ ] <EOL> if args . filter_status : <EOL> states = args . filter_status <EOL> elif args . state_nook : <EOL> states = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> else : <EOL> if args . state_ok : <EOL> states . append ( '<STR_LIT:OK>' ) <EOL> if args . state_error : <EOL> states . append ( '<STR_LIT>' ) <EOL> if args . state_warn : <EOL> states . append ( '<STR_LIT>' ) <EOL> if args . state_unknown : <EOL> states . append ( '<STR_LIT>' ) <EOL> if not states : <EOL> states = [ '<STR_LIT:OK>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> filters . append ( ( '<STR_LIT:status>' , states ) ) <EOL> hosts = [ '<STR_LIT:localhost>' ] <EOL> discovered_hosts = _host_discovery ( args ) <EOL> if args . hosts : <EOL> hosts = args . hosts <EOL> if discovered_hosts : <EOL> hosts += discovered_hosts <EOL> elif discovered_hosts : <EOL> hosts = discovered_hosts <EOL> client = Client ( hosts ) <EOL> plugins = client . get_plugins ( filters , filters_negative = args . exclude , <EOL> exclude_plugins = args . exclude_plugins ) <EOL> if not plugins : <EOL> lg . error ( "<STR_LIT>" ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> if args . list : <EOL> plugins_tuple = plugins . get_host_plugins ( ) <EOL> if plugins . count_hosts ( ) > <NUM_LIT:1> : <EOL> for host , plugin in plugins_tuple : <EOL> print "<STR_LIT>" % ( host [ '<STR_LIT:name>' ] , plugin [ '<STR_LIT:name>' ] ) <EOL> else : <EOL> for host , plugin in plugins_tuple : <EOL> print "<STR_LIT:%s>" % plugin [ '<STR_LIT:name>' ] <EOL> sys . exit ( <NUM_LIT:0> ) <EOL> if args . force : <EOL> plugins = client . force_run ( <EOL> plugins , progress = not args . no_progress ) <EOL> if args . pretty == '<STR_LIT>' : <EOL> from pprint import pprint <EOL> pprint ( plugins ) <EOL> sys . exit ( <NUM_LIT:0> ) <EOL> elif args . pretty == '<STR_LIT>' : <EOL> class JSONEncoder ( simplejson . JSONEncoder ) : <EOL> """<STR_LIT>""" <EOL> def default ( self , obj ) : <EOL> if isinstance ( obj , datetime . datetime ) : <EOL> return obj . isoformat ( ) <EOL> return simplejson . JSONEncoder . default ( self , obj ) <EOL> print simplejson . dumps ( plugins , cls = JSONEncoder ) <EOL> sys . exit ( <NUM_LIT:0> ) <EOL> elif args . pretty == '<STR_LIT>' : <EOL> dump = dump_tap ( plugins ) <EOL> print dump . encode ( '<STR_LIT:ascii>' , '<STR_LIT:ignore>' ) <EOL> sys . exit ( <NUM_LIT:0> ) <EOL> elif args . pretty == '<STR_LIT>' : <EOL> dump = plugins_to_xml ( plugins , args . junit_config_file ) <EOL> print dump <EOL> sys . exit ( <NUM_LIT:0> ) <EOL> output = [ ] <EOL> hosts_printed = [ ] <EOL> for host , plugin in plugins . get_host_plugins ( ) : <EOL> if host [ '<STR_LIT:name>' ] not in hosts_printed : <EOL> if hosts_printed : output . append ( "<STR_LIT:U+0020>" ) <EOL> if isinstance ( format_host , dict ) : <EOL> output . append ( format_host [ host [ '<STR_LIT:status>' ] ] . format ( ** host ) ) <EOL> else : <EOL> output . append ( format_host . format ( ** host ) ) <EOL> hosts_printed . append ( host [ '<STR_LIT:name>' ] ) <EOL> if not isinstance ( plugin , dict ) : <EOL> continue <EOL> if isinstance ( format_plugin , basestring ) : <EOL> output . append ( format_plugin . format ( ** plugin ) ) <EOL> else : <EOL> output . append ( format_plugin [ plugin [ '<STR_LIT>' ] [ '<STR_LIT:status>' ] ] . format ( ** plugin ) ) <EOL> output . append ( format_plugin_run . format ( ** plugin ) ) <EOL> for key , value in plugin [ '<STR_LIT>' ] . iteritems ( ) : <EOL> output . append ( format_plugin_param . format ( key = key , value = value ) ) <EOL> if plugin [ '<STR_LIT>' ] [ '<STR_LIT>' ] : <EOL> for level , message in plugin [ '<STR_LIT>' ] [ '<STR_LIT>' ] . iteritems ( ) : <EOL> for msg in message : <EOL> if isinstance ( format_plugin_msg , basestring ) : <EOL> output . append ( format_plugin_msg . format ( level = level , msg = msg . encode ( '<STR_LIT:utf8>' ) ) ) <EOL> else : <EOL> output . append ( format_plugin_msg [ level ] . format ( level = level , msg = msg . encode ( '<STR_LIT:utf8>' ) ) ) <EOL> if plugin [ '<STR_LIT>' ] [ '<STR_LIT>' ] : <EOL> for component in plugin [ '<STR_LIT>' ] [ '<STR_LIT>' ] : <EOL> component = component [ '<STR_LIT>' ] <EOL> if isinstance ( format_plugin_component , basestring ) : <EOL> output . append ( format_plugin_component . format ( ** component ) ) <EOL> else : <EOL> output . append ( format_plugin_component [ component [ '<STR_LIT:status>' ] ] . format ( ** component ) ) <EOL> if component [ '<STR_LIT>' ] : <EOL> for level , message in component [ '<STR_LIT>' ] . iteritems ( ) : <EOL> for msg in message : <EOL> if isinstance ( format_plugin_component_msg , basestring ) : <EOL> output . append ( format_plugin_component_msg . format ( level = level , msg = msg . encode ( '<STR_LIT:utf8>' ) ) ) <EOL> else : <EOL> output . append ( format_plugin_component_msg [ level ] . format ( level = level , msg = msg . encode ( '<STR_LIT:utf8>' ) ) ) <EOL> for line in output : <EOL> if line : <EOL> print line <EOL> if args . exitcode : <EOL> statuses = [ host [ '<STR_LIT:status>' ] for host , _ in plugins . get_host_plugins ( ) ] <EOL> for status in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> if status in statuses : <EOL> sys . exit ( EXIT_CODES [ status ] ) <EOL> def dump_tap ( plugins ) : <EOL> """<STR_LIT>""" <EOL> tap = Tap ( ) <EOL> for name in sorted ( plugins ) : <EOL> host = plugins [ name ] <EOL> if host [ '<STR_LIT:status>' ] in [ '<STR_LIT:OK>' , '<STR_LIT>' ] : <EOL> host_ok = True <EOL> else : <EOL> host_ok = False <EOL> tap_host = TapTest ( name , host_ok ) <EOL> tap . add_test ( tap_host ) <EOL> for key in sorted ( host [ '<STR_LIT>' ] ) : <EOL> plugin = host [ '<STR_LIT>' ] [ key ] <EOL> if not plugin [ '<STR_LIT>' ] : <EOL> plugin_ok = False <EOL> else : <EOL> if plugin [ '<STR_LIT>' ] [ '<STR_LIT:status>' ] in [ '<STR_LIT:OK>' , '<STR_LIT>' ] : <EOL> plugin_ok = True <EOL> else : <EOL> plugin_ok = False <EOL> messages = [ ] <EOL> if plugin [ '<STR_LIT>' ] : <EOL> if plugin [ '<STR_LIT>' ] [ '<STR_LIT>' ] : <EOL> messages = plugin [ '<STR_LIT>' ] [ '<STR_LIT>' ] <EOL> tap_plugin = TapTest ( plugin [ '<STR_LIT:name>' ] , plugin_ok , messages ) <EOL> tap_host . add_subtest ( tap_plugin ) <EOL> if ( plugin [ '<STR_LIT>' ] and <EOL> plugin [ '<STR_LIT>' ] [ '<STR_LIT>' ] ) : <EOL> for component in plugin [ '<STR_LIT>' ] [ '<STR_LIT>' ] : <EOL> component = component [ '<STR_LIT>' ] <EOL> if component [ '<STR_LIT:status>' ] in [ '<STR_LIT:OK>' , '<STR_LIT>' ] : <EOL> component_ok = True <EOL> else : <EOL> component_ok = False <EOL> messages = [ ] <EOL> if component [ '<STR_LIT>' ] : <EOL> if component [ '<STR_LIT>' ] : <EOL> messages = component [ '<STR_LIT>' ] <EOL> tap_component = TapTest ( component [ '<STR_LIT:name>' ] , component_ok , <EOL> messages ) <EOL> tap_plugin . add_subtest ( tap_component ) <EOL> return tap . dump ( ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> try : <EOL> main ( ) <EOL> except KeyboardInterrupt : <EOL> sys . exit ( <NUM_LIT:1> ) </s>
<s> import copy <EOL> import datetime <EOL> import lockfile <EOL> import multiprocessing <EOL> import os <EOL> import psutil <EOL> import pytest <EOL> import re <EOL> from smoker . server import exceptions as smoker_exceptions <EOL> import smoker . server . plugins as server_plugins <EOL> import time <EOL> class TestPluginManager ( object ) : <EOL> """<STR_LIT>""" <EOL> conf_plugins_to_load = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : <NUM_LIT:5> , <EOL> '<STR_LIT>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } <EOL> } <EOL> conf_plugins_with_enabled_is_false = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : <NUM_LIT:15> , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : <NUM_LIT:5> } <EOL> } <EOL> conf_plugins_with_template_is_false = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : <NUM_LIT:5> , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : <NUM_LIT:5> , <EOL> '<STR_LIT>' : '<STR_LIT>' } <EOL> } <EOL> conf_plugins = dict ( <EOL> conf_plugins_to_load . items ( ) + <EOL> conf_plugins_with_enabled_is_false . items ( ) + <EOL> conf_plugins_with_template_is_false . items ( ) ) <EOL> conf_templates = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : <NUM_LIT:2> , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : <NUM_LIT:30> , <EOL> '<STR_LIT>' : <NUM_LIT:10> } , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : <NUM_LIT:3> , <EOL> '<STR_LIT>' : <NUM_LIT:5> } <EOL> } <EOL> conf_actions = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : '<STR_LIT>' } <EOL> } <EOL> config = { <EOL> '<STR_LIT>' : conf_plugins , <EOL> '<STR_LIT>' : conf_templates , <EOL> '<STR_LIT>' : conf_actions } <EOL> pluginmgr = server_plugins . PluginManager ( ** copy . deepcopy ( config ) ) <EOL> loaded_plugins = pluginmgr . get_plugins ( ) <EOL> def test_disabled_plugins_should_not_be_loaded ( self ) : <EOL> plugins = self . conf_plugins_with_template_is_false . iteritems ( ) <EOL> for plugin , options in plugins : <EOL> if '<STR_LIT>' in options and not options [ '<STR_LIT>' ] : <EOL> assert plugin not in self . loaded_plugins . keys ( ) <EOL> def test_enabled_plugins_should_be_loaded ( self ) : <EOL> for plugin , options in self . conf_plugins_to_load . iteritems ( ) : <EOL> if '<STR_LIT>' in options and options [ '<STR_LIT>' ] : <EOL> assert plugin in self . loaded_plugins . keys ( ) <EOL> def test_plugins_without_enabled_option_should_be_loaded ( self ) : <EOL> for plugin , options in self . conf_plugins_to_load . iteritems ( ) : <EOL> if '<STR_LIT>' not in options : <EOL> assert plugin in self . loaded_plugins . keys ( ) <EOL> def test_plugins_are_rightly_loaded ( self ) : <EOL> assert len ( self . loaded_plugins ) == len ( self . conf_plugins_to_load ) <EOL> def test_plugins_not_in_config_should_not_be_loaded ( self ) : <EOL> for plugin in self . loaded_plugins : <EOL> assert plugin in self . conf_plugins <EOL> def test_load_plugins_without_baseplugin_template_will_get_error ( self ) : <EOL> templates = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : <NUM_LIT:5> , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : <NUM_LIT:30> , <EOL> '<STR_LIT>' : <NUM_LIT:10> } <EOL> } <EOL> actions = copy . deepcopy ( self . conf_actions ) <EOL> with pytest . raises ( smoker_exceptions . BasePluginTemplateNotFound ) : <EOL> server_plugins . PluginManager ( plugins = self . conf_plugins , <EOL> templates = templates , <EOL> actions = actions ) <EOL> def test_no_plugin_to_load ( self ) : <EOL> actions = copy . deepcopy ( self . conf_actions ) <EOL> with pytest . raises ( smoker_exceptions . NoRunningPlugins ) as exc_info : <EOL> server_plugins . PluginManager ( plugins = dict ( ) , <EOL> templates = self . conf_templates , <EOL> actions = actions ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> def test_load_plugins_without_any_template ( self ) : <EOL> actions = copy . deepcopy ( self . conf_actions ) <EOL> with pytest . raises ( smoker_exceptions . BasePluginTemplateNotFound ) : <EOL> server_plugins . PluginManager ( plugins = self . conf_plugins , <EOL> templates = dict ( ) , <EOL> actions = actions ) <EOL> def test_load_plugins_with_template_is_true ( self ) : <EOL> pluginmgr = server_plugins . PluginManager ( ** copy . deepcopy ( self . config ) ) <EOL> for plugin in self . conf_plugins_to_load : <EOL> if '<STR_LIT>' in self . conf_plugins_to_load [ plugin ] : <EOL> assert plugin in pluginmgr . get_plugins ( ) <EOL> assert '<STR_LIT>' in pluginmgr . get_plugin ( plugin ) . params <EOL> templates = pluginmgr . get_plugin ( plugin ) . params [ '<STR_LIT>' ] <EOL> assert '<STR_LIT>' in templates <EOL> def test_load_plugins_with_template_is_false ( self ) : <EOL> templates = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : <NUM_LIT:5> , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : <NUM_LIT:30> , <EOL> '<STR_LIT>' : <NUM_LIT:10> } <EOL> } <EOL> conf = dict ( copy . deepcopy ( self . config ) , ** { '<STR_LIT>' : templates } ) <EOL> pluginmgr = server_plugins . PluginManager ( ** conf ) <EOL> for plugin in self . conf_plugins_to_load : <EOL> if '<STR_LIT>' in self . conf_plugins_to_load [ plugin ] : <EOL> assert plugin not in pluginmgr . get_plugins ( ) <EOL> def test_load_plugins_with_actions ( self ) : <EOL> expected = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : <NUM_LIT> <EOL> } <EOL> pluginmgr = server_plugins . PluginManager ( ** copy . deepcopy ( self . config ) ) <EOL> action = pluginmgr . plugins [ '<STR_LIT>' ] . params [ '<STR_LIT>' ] <EOL> assert action == expected <EOL> def test_load_plugins_with_blank_actions ( self ) : <EOL> actions = { <EOL> '<STR_LIT>' : dict ( ) <EOL> } <EOL> conf = dict ( copy . deepcopy ( self . config ) , ** { '<STR_LIT>' : actions } ) <EOL> pluginmgr = server_plugins . PluginManager ( ** conf ) <EOL> assert not pluginmgr . plugins [ '<STR_LIT>' ] . params [ '<STR_LIT>' ] <EOL> def test_plugins_without_params_will_use_params_from_base_plugin ( self ) : <EOL> expected_interval = self . conf_templates [ '<STR_LIT>' ] [ '<STR_LIT>' ] <EOL> for plugin_name , plugin in self . conf_plugins_to_load . iteritems ( ) : <EOL> if not plugin . get ( '<STR_LIT>' ) and not plugin . get ( '<STR_LIT>' ) : <EOL> assert ( self . loaded_plugins [ plugin_name ] . params [ '<STR_LIT>' ] == <EOL> expected_interval ) <EOL> def test_get_plugins_with_filter ( self ) : <EOL> filter_ = { '<STR_LIT>' : '<STR_LIT>' } <EOL> expected_plugins = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> load_plugins_with_filter = self . pluginmgr . get_plugins ( filter = filter_ ) <EOL> assert len ( expected_plugins ) == len ( load_plugins_with_filter ) <EOL> for plugin in load_plugins_with_filter : <EOL> assert plugin . name in expected_plugins <EOL> def test_get_plugins_with_invalid_name ( self ) : <EOL> with pytest . raises ( smoker_exceptions . NoSuchPlugin ) as exc_info : <EOL> self . pluginmgr . get_plugin ( '<STR_LIT>' ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> def test_get_non_exist_template ( self ) : <EOL> with pytest . raises ( smoker_exceptions . TemplateNotFound ) as exc_info : <EOL> self . pluginmgr . get_template ( '<STR_LIT>' ) <EOL> expected = '<STR_LIT>' <EOL> assert expected in exc_info . value <EOL> def test_get_template ( self ) : <EOL> assert ( self . pluginmgr . get_template ( '<STR_LIT>' ) == <EOL> self . conf_templates [ '<STR_LIT>' ] ) <EOL> def test_add_process_using_plugin_list ( self ) : <EOL> pluginmgr = server_plugins . PluginManager ( ** copy . deepcopy ( self . config ) ) <EOL> plugin_list = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> expected_plugins = list ( ) <EOL> for plugin in plugin_list : <EOL> expected_plugins . append ( pluginmgr . get_plugin ( plugin ) ) <EOL> process_id = pluginmgr . add_process ( plugins = plugin_list ) <EOL> added_process = pluginmgr . get_process_list ( ) [ process_id ] [ '<STR_LIT>' ] <EOL> assert expected_plugins == added_process <EOL> def test_add_process_using_filter ( self ) : <EOL> pluginmgr = server_plugins . PluginManager ( ** copy . deepcopy ( self . config ) ) <EOL> filter_ = { '<STR_LIT>' : '<STR_LIT>' } <EOL> expected_plugins = pluginmgr . get_plugins ( filter = filter_ ) <EOL> process_id = pluginmgr . add_process ( filter = filter_ ) <EOL> added_process = pluginmgr . get_process_list ( ) [ process_id ] [ '<STR_LIT>' ] <EOL> assert expected_plugins == added_process <EOL> def test_add_process_using_plugin_list_and_filter ( self ) : <EOL> pluginmgr = server_plugins . PluginManager ( ** copy . deepcopy ( self . config ) ) <EOL> plugin_list = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> filter_ = { '<STR_LIT>' : '<STR_LIT>' } <EOL> expected_plugins = list ( ) <EOL> for plugin in plugin_list : <EOL> expected_plugins . append ( pluginmgr . get_plugin ( plugin ) ) <EOL> expected_plugins += pluginmgr . get_plugins ( filter = filter_ ) <EOL> process_id = pluginmgr . add_process ( plugins = plugin_list , filter = filter_ ) <EOL> added_process = pluginmgr . get_process_list ( ) [ process_id ] [ '<STR_LIT>' ] <EOL> assert expected_plugins == added_process <EOL> def test_add_process_without_any_plugin ( self ) : <EOL> conf = copy . deepcopy ( self . config ) <EOL> with pytest . raises ( smoker_exceptions . NoPluginsFound ) : <EOL> server_plugins . PluginManager ( ** conf ) . add_process ( ) <EOL> def test_add_process_with_invalid_plugin_name ( self ) : <EOL> conf = copy . deepcopy ( self . config ) <EOL> with pytest . raises ( smoker_exceptions . NoSuchPlugin ) as exc_info : <EOL> pluginmgr = server_plugins . PluginManager ( ** conf ) <EOL> pluginmgr . add_process ( plugins = [ '<STR_LIT>' ] ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> def test_get_process_with_invalid_process_id ( self ) : <EOL> with pytest . raises ( IndexError ) : <EOL> self . pluginmgr . get_process ( <NUM_LIT> ) <EOL> assert not self . pluginmgr . get_process ( <NUM_LIT:0> ) <EOL> def test_run_plugins_with_interval ( self ) : <EOL> pluginmgr = server_plugins . PluginManager ( ** copy . deepcopy ( self . config ) ) <EOL> time . sleep ( <NUM_LIT> ) <EOL> pluginmgr . run_plugins_with_interval ( ) <EOL> for plugin in pluginmgr . plugins . values ( ) : <EOL> assert plugin . current_run <EOL> def test_get_action ( self ) : <EOL> assert ( self . pluginmgr . get_action ( '<STR_LIT>' ) == <EOL> self . conf_actions [ '<STR_LIT>' ] ) <EOL> def test_get_non_exist_action ( self ) : <EOL> with pytest . raises ( smoker_exceptions . ActionNotFound ) as exc_info : <EOL> self . pluginmgr . get_action ( '<STR_LIT>' ) <EOL> expected = '<STR_LIT>' <EOL> assert expected in exc_info . value <EOL> def test_join_timed_plugin_workers ( self ) : <EOL> pluginmgr = server_plugins . PluginManager ( ** copy . deepcopy ( self . config ) ) <EOL> plugin = pluginmgr . get_plugin ( '<STR_LIT>' ) <EOL> time . sleep ( plugin . params [ '<STR_LIT>' ] + <NUM_LIT:0.5> ) <EOL> plugin . run ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> assert plugin . current_run <EOL> pluginmgr . join_timed_plugin_workers ( ) <EOL> assert not plugin . current_run <EOL> def test_join_non_timed_plugin_workers ( self ) : <EOL> pluginmgr = server_plugins . PluginManager ( ** copy . deepcopy ( self . config ) ) <EOL> plugin = pluginmgr . get_plugin ( '<STR_LIT>' ) <EOL> time . sleep ( plugin . params [ '<STR_LIT>' ] + <NUM_LIT:0.5> ) <EOL> plugin . run ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> assert plugin . current_run <EOL> plugin . params [ '<STR_LIT>' ] = <NUM_LIT:0> <EOL> pluginmgr . join_timed_plugin_workers ( ) <EOL> assert plugin . current_run <EOL> class TestPlugin ( object ) : <EOL> """<STR_LIT>""" <EOL> test_params_default = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> test_plugin_name = '<STR_LIT>' <EOL> plugin = server_plugins . Plugin ( name = test_plugin_name , <EOL> params = test_params_default ) <EOL> def test_create_plugin_test_params_default ( self ) : <EOL> expected_params = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : <NUM_LIT:0> , <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : <NUM_LIT:10> , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : None <EOL> } <EOL> assert self . plugin . params == expected_params <EOL> def test_validate_created_plugin ( self ) : <EOL> with pytest . raises ( smoker_exceptions . InvalidConfiguration ) as exc_info : <EOL> params = dict ( self . test_params_default , ** { '<STR_LIT>' : <NUM_LIT:0> } ) <EOL> server_plugins . Plugin ( name = self . test_plugin_name , params = params ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> with pytest . raises ( smoker_exceptions . InvalidConfiguration ) as exc_info : <EOL> params = dict ( self . test_params_default , ** { '<STR_LIT>' : None } ) <EOL> server_plugins . Plugin ( name = self . test_plugin_name , params = params ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> with pytest . raises ( smoker_exceptions . InvalidConfiguration ) as exc_info : <EOL> test_params = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> params = dict ( self . test_params_default , ** test_params ) <EOL> server_plugins . Plugin ( name = self . test_plugin_name , params = params ) <EOL> expected = '<STR_LIT>' <EOL> assert expected in exc_info . value <EOL> with pytest . raises ( smoker_exceptions . InvalidConfiguration ) as exc_info : <EOL> test_params = { <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> params = dict ( self . test_params_default , ** test_params ) <EOL> server_plugins . Plugin ( name = self . test_plugin_name , params = params ) <EOL> expected = '<STR_LIT>' <EOL> assert expected in exc_info . value <EOL> def test_schedule_run_with_time ( self ) : <EOL> next_run = ( datetime . datetime . now ( ) + datetime . timedelta ( seconds = <NUM_LIT:3> ) ) <EOL> self . plugin . schedule_run ( time = next_run ) <EOL> assert self . plugin . next_run == next_run <EOL> def test_schedule_run_with_invalid_time_format ( self ) : <EOL> with pytest . raises ( smoker_exceptions . InvalidArgument ) as exc_info : <EOL> self . plugin . schedule_run ( time = <NUM_LIT:15> ) <EOL> expected = '<STR_LIT>' <EOL> assert expected in exc_info . value <EOL> with pytest . raises ( smoker_exceptions . InvalidArgument ) as exc_info : <EOL> self . plugin . schedule_run ( time = time . ctime ( ) ) <EOL> expected = '<STR_LIT>' <EOL> assert expected in exc_info . value <EOL> def test_schedule_run_now ( self ) : <EOL> self . plugin . schedule_run ( now = True ) <EOL> delta = ( datetime . datetime . now ( ) - self . plugin . next_run ) <EOL> assert round ( delta . total_seconds ( ) , <NUM_LIT:0> ) == <NUM_LIT:0> <EOL> def test_schedule_run_with_interval ( self ) : <EOL> params = dict ( self . test_params_default , ** { '<STR_LIT>' : <NUM_LIT:15> } ) <EOL> plugin = server_plugins . Plugin ( name = self . test_plugin_name , <EOL> params = params ) <EOL> delta = ( plugin . next_run - datetime . datetime . now ( ) ) <EOL> assert round ( delta . total_seconds ( ) , <NUM_LIT:0> ) == plugin . params [ '<STR_LIT>' ] <EOL> def test_force_to_run_plugin_without_interval_parameter ( self ) : <EOL> plugin = server_plugins . Plugin ( name = self . test_plugin_name , <EOL> params = self . test_params_default ) <EOL> plugin . forced = True <EOL> plugin . run ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> assert plugin . current_run <EOL> assert type ( plugin . current_run ) . __name__ == '<STR_LIT>' <EOL> assert not plugin . next_run <EOL> assert plugin . forced <EOL> def test_force_to_run_plugin_with_interval_parameter ( self ) : <EOL> params = dict ( self . test_params_default , ** { '<STR_LIT>' : <NUM_LIT:2> } ) <EOL> plugin = server_plugins . Plugin ( name = self . test_plugin_name , <EOL> params = params ) <EOL> n = plugin . next_run <EOL> plugin . forced = True <EOL> plugin . run ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> assert plugin . current_run <EOL> assert type ( plugin . current_run ) . __name__ == '<STR_LIT>' <EOL> assert n == plugin . next_run <EOL> assert plugin . forced <EOL> def test_run_plugin_with_interval ( self ) : <EOL> params = dict ( self . test_params_default , ** { '<STR_LIT>' : <NUM_LIT:2> } ) <EOL> plugin = server_plugins . Plugin ( name = self . test_plugin_name , <EOL> params = params ) <EOL> time . sleep ( <NUM_LIT> ) <EOL> assert not plugin . current_run <EOL> plugin . run ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> assert plugin . current_run <EOL> assert type ( plugin . current_run ) . __name__ == '<STR_LIT>' <EOL> def test_run_plugin_with_interval_should_schedule_next_run ( self ) : <EOL> params = dict ( self . test_params_default , ** { '<STR_LIT>' : <NUM_LIT:2> } ) <EOL> plugin = server_plugins . Plugin ( name = self . test_plugin_name , <EOL> params = params ) <EOL> time . sleep ( <NUM_LIT> ) <EOL> plugin . run ( ) <EOL> delta = ( plugin . next_run - datetime . datetime . now ( ) ) <EOL> assert round ( delta . total_seconds ( ) , <NUM_LIT:0> ) == plugin . params [ '<STR_LIT>' ] <EOL> def test_plugin_should_not_be_run_without_interval_parameter ( self ) : <EOL> plugin = server_plugins . Plugin ( name = self . test_plugin_name , <EOL> params = self . test_params_default ) <EOL> assert not plugin . next_run <EOL> plugin . forced = False <EOL> plugin . run ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> assert not plugin . current_run <EOL> def test_interval_run_plugin_and_collect_new_result ( self ) : <EOL> params = dict ( self . test_params_default , ** { '<STR_LIT>' : <NUM_LIT:2> } ) <EOL> plugin = server_plugins . Plugin ( name = self . test_plugin_name , <EOL> params = params ) <EOL> time . sleep ( <NUM_LIT> ) <EOL> plugin . run ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> assert not plugin . get_last_result ( ) <EOL> plugin . collect_new_result ( ) <EOL> result = plugin . get_last_result ( ) <EOL> assert '<STR_LIT:status>' in result and result [ '<STR_LIT:status>' ] == '<STR_LIT:OK>' <EOL> assert '<STR_LIT>' in result and not result [ '<STR_LIT>' ] <EOL> def test_force_plugin_to_run_and_collect_new_result ( self ) : <EOL> plugin = server_plugins . Plugin ( name = self . test_plugin_name , <EOL> params = self . test_params_default ) <EOL> plugin . forced = True <EOL> plugin . run ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> assert not plugin . get_last_result ( ) <EOL> plugin . collect_new_result ( ) <EOL> assert not plugin . forced <EOL> result = plugin . forced_result <EOL> assert '<STR_LIT:status>' in result and result [ '<STR_LIT:status>' ] == '<STR_LIT:OK>' <EOL> assert '<STR_LIT>' in result and result [ '<STR_LIT>' ] <EOL> def test_history_of_collect_new_result ( self ) : <EOL> params = dict ( self . test_params_default , ** { '<STR_LIT>' : <NUM_LIT:5> } ) <EOL> plugin = server_plugins . Plugin ( name = self . test_plugin_name , <EOL> params = params ) <EOL> for n in range ( <NUM_LIT:7> ) : <EOL> plugin . forced = True <EOL> plugin . run ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> plugin . collect_new_result ( ) <EOL> assert len ( plugin . result ) == params [ '<STR_LIT>' ] <EOL> assert plugin . forced_result == plugin . result [ - <NUM_LIT:1> ] <EOL> class TestPluginWorker ( object ) : <EOL> """<STR_LIT>""" <EOL> action = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : <NUM_LIT> <EOL> } <EOL> params_default = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : '<STR_LIT:default>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : <NUM_LIT:30> , <EOL> '<STR_LIT>' : None <EOL> } <EOL> queue = multiprocessing . Queue ( ) <EOL> conf_worker = { <EOL> '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : queue , <EOL> '<STR_LIT>' : params_default , <EOL> '<STR_LIT>' : False <EOL> } <EOL> def test_running_worker_process ( self ) : <EOL> worker = server_plugins . PluginWorker ( ** self . conf_worker ) <EOL> worker . run ( ) <EOL> assert '<STR_LIT:status>' in worker . result and worker . result [ '<STR_LIT:status>' ] == '<STR_LIT:OK>' <EOL> assert '<STR_LIT:info>' in worker . result [ '<STR_LIT>' ] <EOL> assert worker . result [ '<STR_LIT>' ] [ '<STR_LIT:info>' ] == [ os . uname ( ) [ <NUM_LIT:1> ] ] <EOL> def test_running_worker_process_title_should_be_changed ( self ) : <EOL> expected = '<STR_LIT>' <EOL> worker = server_plugins . PluginWorker ( ** self . conf_worker ) <EOL> worker . run ( ) <EOL> procs = get_process_list ( ) <EOL> assert expected in procs . values ( ) <EOL> def test_drop_privileged_with_invalid_params ( self ) : <EOL> test_params = { <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : <NUM_LIT> <EOL> } <EOL> params = dict ( self . params_default , ** test_params ) <EOL> worker = server_plugins . PluginWorker ( name = '<STR_LIT>' , <EOL> queue = self . queue , params = params ) <EOL> with pytest . raises ( OSError ) as exc_info : <EOL> worker . run ( ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> def test_drop_privileged_with_invalid_params_type ( self ) : <EOL> test_params = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } <EOL> params = dict ( self . params_default , ** test_params ) <EOL> worker = server_plugins . PluginWorker ( name = '<STR_LIT>' , <EOL> queue = self . queue , params = params ) <EOL> with pytest . raises ( TypeError ) as exc_info : <EOL> worker . run ( ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> def test_run_worker_with_maintenance_lock ( self ) : <EOL> expected_message = [ '<STR_LIT>' ] <EOL> maintenance_lock = os . getcwd ( ) + random_string ( ) <EOL> test_params = { '<STR_LIT>' : maintenance_lock + '<STR_LIT>' } <EOL> params = dict ( self . params_default , ** test_params ) <EOL> lock = lockfile . FileLock ( maintenance_lock ) <EOL> with lock : <EOL> worker = server_plugins . PluginWorker ( name = '<STR_LIT>' , <EOL> queue = self . queue , <EOL> params = params ) <EOL> worker . run ( ) <EOL> assert '<STR_LIT:status>' in worker . result <EOL> assert worker . result [ '<STR_LIT:status>' ] == '<STR_LIT>' <EOL> assert '<STR_LIT>' in worker . result [ '<STR_LIT>' ] <EOL> assert worker . result [ '<STR_LIT>' ] [ '<STR_LIT>' ] == expected_message <EOL> def test_run_invalid_command ( self ) : <EOL> expected = '<STR_LIT>' <EOL> test_params = { <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> params = dict ( self . params_default , ** test_params ) <EOL> worker = server_plugins . PluginWorker ( name = '<STR_LIT>' , <EOL> queue = self . queue , params = params ) <EOL> worker . run ( ) <EOL> assert '<STR_LIT:status>' in worker . result and worker . result [ '<STR_LIT:status>' ] == '<STR_LIT>' <EOL> assert '<STR_LIT>' in worker . result [ '<STR_LIT>' ] <EOL> assert re . search ( expected , worker . result [ '<STR_LIT>' ] [ '<STR_LIT:error>' ] [ <NUM_LIT:0> ] ) <EOL> def test_run_command_with_parser ( self ) : <EOL> expected = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:status>' : '<STR_LIT:OK>' , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:info>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT:error>' : [ ] <EOL> } <EOL> } <EOL> } <EOL> test_params = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> params = dict ( self . params_default , ** test_params ) <EOL> worker = server_plugins . PluginWorker ( name = '<STR_LIT>' , <EOL> queue = self . queue , params = params ) <EOL> worker . run ( ) <EOL> assert '<STR_LIT:status>' in worker . result and worker . result [ '<STR_LIT:status>' ] == '<STR_LIT:OK>' <EOL> assert '<STR_LIT>' in worker . result <EOL> assert worker . result [ '<STR_LIT>' ] == expected <EOL> assert '<STR_LIT>' in worker . result and not worker . result [ '<STR_LIT>' ] <EOL> def test_run_command_with_invalid_parser_path ( self ) : <EOL> expected_info = [ '<STR_LIT>' ] <EOL> expected_error = [ '<STR_LIT>' ] <EOL> test_params = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> params = dict ( self . params_default , ** test_params ) <EOL> worker = server_plugins . PluginWorker ( name = '<STR_LIT>' , <EOL> queue = self . queue , params = params ) <EOL> worker . run ( ) <EOL> assert '<STR_LIT:status>' in worker . result and worker . result [ '<STR_LIT:status>' ] == '<STR_LIT>' <EOL> assert '<STR_LIT:info>' and '<STR_LIT:error>' in worker . result [ '<STR_LIT>' ] <EOL> assert worker . result [ '<STR_LIT>' ] [ '<STR_LIT:info>' ] == expected_info <EOL> assert worker . result [ '<STR_LIT>' ] [ '<STR_LIT:error>' ] == expected_error <EOL> def test_run_parser ( self ) : <EOL> expected = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:status>' : '<STR_LIT:OK>' , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:info>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT:error>' : [ ] <EOL> } <EOL> } <EOL> } <EOL> test_params = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> params = dict ( self . params_default , ** test_params ) <EOL> worker = server_plugins . PluginWorker ( name = '<STR_LIT>' , <EOL> queue = self . queue , params = params ) <EOL> result = worker . run_parser ( stdout = '<STR_LIT>' , stderr = '<STR_LIT>' ) . result <EOL> assert '<STR_LIT:status>' in result and result [ '<STR_LIT:status>' ] == '<STR_LIT:OK>' <EOL> assert result [ '<STR_LIT>' ] == expected <EOL> assert '<STR_LIT>' in result and not result [ '<STR_LIT>' ] <EOL> assert ( result [ '<STR_LIT>' ] [ '<STR_LIT>' ] [ '<STR_LIT:status>' ] == <EOL> result [ '<STR_LIT:status>' ] ) <EOL> def test_run_invalid_parser ( self ) : <EOL> test_params = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> params = dict ( self . params_default , ** test_params ) <EOL> worker = server_plugins . PluginWorker ( name = '<STR_LIT>' , <EOL> queue = self . queue , params = params ) <EOL> with pytest . raises ( ImportError ) as exc_info : <EOL> worker . run_parser ( stdout = '<STR_LIT>' , stderr = '<STR_LIT>' ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> def test_run_module ( self ) : <EOL> worker = server_plugins . PluginWorker ( ** self . conf_worker ) <EOL> module = '<STR_LIT>' <EOL> result = worker . run_module ( module ) . result <EOL> assert '<STR_LIT:status>' in result and result [ '<STR_LIT:status>' ] == '<STR_LIT:OK>' <EOL> assert '<STR_LIT:info>' in result [ '<STR_LIT>' ] <EOL> assert result [ '<STR_LIT>' ] [ '<STR_LIT:info>' ] == [ '<STR_LIT:U+0020>' . join ( os . uname ( ) ) ] <EOL> def test_run_invalid_module ( self ) : <EOL> worker = server_plugins . PluginWorker ( ** self . conf_worker ) <EOL> module = '<STR_LIT>' <EOL> with pytest . raises ( ImportError ) as exc_info : <EOL> worker . run_module ( module ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> def test_escape ( self ) : <EOL> worker = server_plugins . PluginWorker ( ** self . conf_worker ) <EOL> tbe_str = '<STR_LIT>' <EOL> assert worker . escape ( tbe = tbe_str ) == re . escape ( tbe_str ) <EOL> tbe_dict = { '<STR_LIT>' : '<STR_LIT>' } <EOL> expected_dict = { '<STR_LIT>' : '<STR_LIT>' } <EOL> assert worker . escape ( tbe = tbe_dict ) == expected_dict <EOL> tbe_list = [ <NUM_LIT:1> , '<STR_LIT>' , '<STR_LIT>' ] <EOL> expected_list = [ <NUM_LIT:1> , '<STR_LIT>' , '<STR_LIT>' ] <EOL> assert worker . escape ( tbe = tbe_list ) == expected_list <EOL> tbe_tuple = { <NUM_LIT:1> , '<STR_LIT>' , '<STR_LIT>' } <EOL> with pytest . raises ( Exception ) as exc_info : <EOL> worker . escape ( tbe = tbe_tuple ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> def test_get_params ( self ) : <EOL> worker = server_plugins . PluginWorker ( ** self . conf_worker ) <EOL> assert worker . get_param ( '<STR_LIT>' ) == '<STR_LIT>' <EOL> assert worker . get_param ( '<STR_LIT>' ) == <NUM_LIT:30> <EOL> assert not worker . get_param ( '<STR_LIT>' ) <EOL> assert not worker . get_param ( '<STR_LIT>' ) <EOL> class TestResult ( object ) : <EOL> """<STR_LIT>""" <EOL> result_to_validate = { <EOL> '<STR_LIT:status>' : '<STR_LIT:OK>' , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:info>' : [ ] , <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT:error>' : [ ] <EOL> } , <EOL> '<STR_LIT>' : datetime . datetime . now ( ) . isoformat ( ) , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT:action>' : None , <EOL> '<STR_LIT>' : False <EOL> } <EOL> def test_set_status ( self ) : <EOL> result = server_plugins . Result ( ) <EOL> result . set_status ( '<STR_LIT:OK>' ) <EOL> assert result . result [ '<STR_LIT:status>' ] == '<STR_LIT:OK>' <EOL> result . set_status ( '<STR_LIT>' ) <EOL> assert result . result [ '<STR_LIT:status>' ] == '<STR_LIT>' <EOL> result . set_status ( '<STR_LIT>' ) <EOL> assert result . result [ '<STR_LIT:status>' ] == '<STR_LIT>' <EOL> for status in [ '<STR_LIT:OK>' , '<STR_LIT>' , '<STR_LIT>' ] : <EOL> component_results = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:status>' : status , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:info>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT:error>' : [ ] <EOL> } <EOL> } <EOL> } <EOL> result = server_plugins . Result ( ) <EOL> result . result [ '<STR_LIT>' ] = component_results <EOL> result . set_status ( ) <EOL> assert status == result . result [ '<STR_LIT:status>' ] <EOL> def test_set_invalid_status ( self ) : <EOL> result = server_plugins . Result ( ) <EOL> expected = '<STR_LIT>' <EOL> with pytest . raises ( Exception ) as exc_info : <EOL> result . set_status ( ) <EOL> assert expected in exc_info . value <EOL> expected = '<STR_LIT>' <EOL> with pytest . raises ( smoker_exceptions . InvalidArgument ) as exc_info : <EOL> result . set_status ( '<STR_LIT>' ) <EOL> assert expected in exc_info . value <EOL> def test_add_msg ( self ) : <EOL> for level in [ '<STR_LIT:info>' , '<STR_LIT>' , '<STR_LIT:error>' ] : <EOL> result = server_plugins . Result ( ) <EOL> result . add_msg ( level , '<STR_LIT>' ) <EOL> result . add_msg ( level , '<STR_LIT>' ) <EOL> result . add_msg ( level , level ) <EOL> expected_info = [ '<STR_LIT>' , '<STR_LIT>' , level ] <EOL> assert '<STR_LIT:status>' in result . result and not result . result [ '<STR_LIT:status>' ] <EOL> assert level in result . result [ '<STR_LIT>' ] <EOL> assert expected_info == result . result [ '<STR_LIT>' ] [ level ] <EOL> def test_add_msg_with_invalid_level ( self ) : <EOL> result = server_plugins . Result ( ) <EOL> with pytest . raises ( smoker_exceptions . InvalidArgument ) as exc_info : <EOL> result . add_msg ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> assert '<STR_LIT>' in exc_info . value <EOL> def test_add_msg_with_multiline_is_true ( self ) : <EOL> for level in [ '<STR_LIT:info>' , '<STR_LIT>' , '<STR_LIT:error>' ] : <EOL> result = server_plugins . Result ( ) <EOL> result . add_msg ( level , '<STR_LIT>' , multiline = True ) <EOL> result . add_msg ( level , level ) <EOL> expected_info = [ '<STR_LIT>' , level ] <EOL> assert '<STR_LIT:status>' in result . result and not result . result [ '<STR_LIT:status>' ] <EOL> assert level in result . result [ '<STR_LIT>' ] <EOL> assert expected_info == result . result [ '<STR_LIT>' ] [ level ] <EOL> def test_add_msg_with_multiline_is_false ( self ) : <EOL> for level in [ '<STR_LIT:info>' , '<STR_LIT>' , '<STR_LIT:error>' ] : <EOL> result = server_plugins . Result ( ) <EOL> result . add_msg ( level , '<STR_LIT>' ) <EOL> result . add_msg ( level , level ) <EOL> expected_info = [ '<STR_LIT>' , '<STR_LIT>' , level ] <EOL> assert '<STR_LIT:status>' in result . result and not result . result [ '<STR_LIT:status>' ] <EOL> assert level in result . result [ '<STR_LIT>' ] <EOL> assert expected_info == result . result [ '<STR_LIT>' ] [ level ] <EOL> def test_validate_status ( self ) : <EOL> for status in [ '<STR_LIT:OK>' , '<STR_LIT>' , '<STR_LIT>' ] : <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT:status>' ] = status <EOL> result . validate ( ) <EOL> assert result . validated <EOL> def test_validate_invalid_status ( self ) : <EOL> expected = '<STR_LIT>' '<STR_LIT>' <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT:status>' ] = '<STR_LIT>' <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> assert expected in exc_info . value <EOL> def test_validate_message_should_be_dict ( self ) : <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT>' ] = str ( ) <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> expected = '<STR_LIT>' <EOL> assert expected in exc_info . value <EOL> def test_validate_level_message_should_be_list ( self ) : <EOL> for level in [ '<STR_LIT:info>' , '<STR_LIT:error>' , '<STR_LIT>' ] : <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT>' ] [ level ] = str ( ) <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> expected = '<STR_LIT>' '<STR_LIT>' % level <EOL> assert expected in exc_info . value <EOL> def test_validate_level_message_output_should_be_string ( self ) : <EOL> for level in [ '<STR_LIT:info>' , '<STR_LIT:error>' , '<STR_LIT>' ] : <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT>' ] [ level ] = [ '<STR_LIT>' , [ '<STR_LIT>' ] ] <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> expected = '<STR_LIT>' '<STR_LIT>' % level <EOL> assert expected in exc_info . value <EOL> def test_validate_component_result_should_be_dict ( self ) : <EOL> expected = '<STR_LIT>' <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT>' ] = list ( ) <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> assert expected in exc_info . value <EOL> def test_validate_component_result_should_have_message ( self ) : <EOL> component_results = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:status>' : '<STR_LIT:OK>' , <EOL> } <EOL> } <EOL> expected = '<STR_LIT>' <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT>' ] = component_results <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> assert expected in exc_info . value <EOL> def test_validate_component_result_should_have_status ( self ) : <EOL> component_results = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:info>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT:error>' : [ ] <EOL> } <EOL> } <EOL> } <EOL> expected = '<STR_LIT>' <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT>' ] = component_results <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> assert expected in exc_info . value <EOL> def test_validate_action_result_should_be_dict ( self ) : <EOL> expected = '<STR_LIT>' <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT:action>' ] = str ( ) <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> assert expected in exc_info . value <EOL> def test_validate_action_result_should_have_message ( self ) : <EOL> action_result = { <EOL> '<STR_LIT:status>' : '<STR_LIT:OK>' , <EOL> } <EOL> expected = '<STR_LIT>' <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT:action>' ] = action_result <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> assert expected in exc_info . value <EOL> def test_validate_action_result_should_have_status ( self ) : <EOL> action_result = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:info>' : [ ] , <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT:error>' : [ ] <EOL> } <EOL> } <EOL> expected = '<STR_LIT>' <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> result . result [ '<STR_LIT:action>' ] = action_result <EOL> with pytest . raises ( smoker_exceptions . ValidationError ) as exc_info : <EOL> result . validate ( ) <EOL> assert expected in exc_info . value <EOL> def test_set_result ( self ) : <EOL> result_to_validate = copy . deepcopy ( self . result_to_validate ) <EOL> result = server_plugins . Result ( ) <EOL> result . set_result ( result_to_validate , validate = True ) <EOL> assert result . validated <EOL> def test_get_result ( self ) : <EOL> result = server_plugins . Result ( ) <EOL> result . result = copy . deepcopy ( self . result_to_validate ) <EOL> assert not result . validated <EOL> result . get_result ( ) <EOL> assert result . validated <EOL> def get_process_list ( ) : <EOL> procs = dict ( ) <EOL> for proc in psutil . process_iter ( ) : <EOL> try : <EOL> pinfo = proc . as_dict ( attrs = [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> procs [ pinfo [ '<STR_LIT>' ] ] = pinfo [ '<STR_LIT>' ] [ <NUM_LIT:0> ] <EOL> except ( psutil . NoSuchProcess , IndexError , TypeError ) : <EOL> pass <EOL> return procs <EOL> def random_string ( ) : <EOL> return str ( datetime . datetime . now ( ) . strftime ( "<STR_LIT>" ) ) </s>
<s> from googkit . commands . command import Command <EOL> class SequenceCommand ( Command ) : <EOL> """<STR_LIT>""" <EOL> @ classmethod <EOL> def _internal_commands ( cls ) : <EOL> return [ ] <EOL> def run ( self ) : <EOL> for CommandClass in self . __class__ . _internal_commands ( ) : <EOL> command = CommandClass ( self . env ) <EOL> command . run ( ) </s>
<s> import unittest <EOL> from test . stub_environment import StubEnvironment <EOL> from googkit . commands . command import Command <EOL> from googkit . commands . sequence import SequenceCommand <EOL> from googkit . compat . unittest import mock <EOL> class DummyFooCommand ( Command ) : <EOL> pass <EOL> class DummyBarCommand ( Command ) : <EOL> pass <EOL> class TestSequenceCommand ( unittest . TestCase ) : <EOL> def test_run ( self ) : <EOL> class DummySequenceCommand ( SequenceCommand ) : <EOL> @ classmethod <EOL> def _internal_commands ( cls ) : <EOL> return [ <EOL> DummyFooCommand , <EOL> DummyBarCommand <EOL> ] <EOL> env = StubEnvironment ( ) <EOL> command = DummySequenceCommand ( env ) <EOL> with mock . patch ( '<STR_LIT>' ) as MockFoo , mock . patch ( '<STR_LIT>' ) as MockBar : <EOL> command . run ( ) <EOL> self . assertTrue ( MockFoo . return_value . run . called ) <EOL> self . assertTrue ( MockBar . return_value . run . called ) </s>
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> import os <EOL> import shutil <EOL> import sys <EOL> import anvil . commands . util as commandutil <EOL> from anvil . manage import ManageCommand <EOL> class CleanCommand ( ManageCommand ) : <EOL> def __init__ ( self ) : <EOL> super ( CleanCommand , self ) . __init__ ( <EOL> name = '<STR_LIT>' , <EOL> help_short = '<STR_LIT>' , <EOL> help_long = __doc__ ) <EOL> def create_argument_parser ( self ) : <EOL> parser = super ( CleanCommand , self ) . create_argument_parser ( ) <EOL> return parser <EOL> def execute ( self , args , cwd ) : <EOL> result = commandutil . clean_output ( cwd ) <EOL> return <NUM_LIT:0> if result else <NUM_LIT:1> </s>
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> import io <EOL> import os <EOL> import re <EOL> from anvil . context import RuleContext <EOL> from anvil . rule import Rule , build_rule <EOL> from anvil . task import ( Task , ExecutableTask , JavaExecutableTask , <EOL> WriteFileTask ) <EOL> import anvil . util <EOL> @ build_rule ( '<STR_LIT>' ) <EOL> class ClosureJsLintRule ( Rule ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , name , namespaces , linter_path = None , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> super ( ClosureJsLintRule , self ) . __init__ ( name , * args , ** kwargs ) <EOL> self . src_filter = '<STR_LIT>' <EOL> self . _command = '<STR_LIT>' <EOL> self . _extra_args = [ '<STR_LIT>' , ] <EOL> self . namespaces = [ ] <EOL> self . namespaces . extend ( namespaces ) <EOL> self . linter_path = linter_path <EOL> class _Context ( RuleContext ) : <EOL> def begin ( self ) : <EOL> super ( ClosureJsLintRule . _Context , self ) . begin ( ) <EOL> self . _append_output_paths ( self . src_paths ) <EOL> if self . _check_if_cached ( ) : <EOL> self . _succeed ( ) <EOL> return <EOL> namespaces = '<STR_LIT:U+002C>' . join ( self . rule . namespaces ) <EOL> args = [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' % ( namespaces ) , <EOL> ] <EOL> command = self . rule . _command <EOL> env = None <EOL> if self . rule . linter_path : <EOL> command = '<STR_LIT>' <EOL> env = { <EOL> '<STR_LIT>' : self . rule . linter_path , <EOL> } <EOL> args = [ <EOL> os . path . join ( <EOL> self . rule . linter_path , <EOL> '<STR_LIT>' % ( self . rule . _command ) ) , <EOL> ] + args <EOL> for src_path in self . file_delta . changed_files : <EOL> if ( src_path . find ( '<STR_LIT>' % os . sep ) == - <NUM_LIT:1> and <EOL> src_path . find ( '<STR_LIT>' % os . sep ) == - <NUM_LIT:1> ) : <EOL> args . append ( src_path ) <EOL> d = self . _run_task_async ( ExecutableTask ( <EOL> self . build_env , command , args , env = env , <EOL> pretty_name = str ( self . rule ) ) ) <EOL> self . _chain ( d ) <EOL> @ build_rule ( '<STR_LIT>' ) <EOL> class ClosureJsFixStyleRule ( ClosureJsLintRule ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , name , namespaces , linter_path = None , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> super ( ClosureJsFixStyleRule , self ) . __init__ ( name , namespaces , <EOL> linter_path = linter_path , * args , ** kwargs ) <EOL> self . _command = '<STR_LIT>' <EOL> self . _extra_args = [ ] <EOL> @ build_rule ( '<STR_LIT>' ) <EOL> class ClosureJsLibraryRule ( Rule ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , name , mode , compiler_jar , entry_points , <EOL> pretty_print = False , debug = False , <EOL> compiler_flags = None , externs = None , wrap_with_global = None , <EOL> out = None , deps_out = None , file_list_out = None , <EOL> * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> super ( ClosureJsLibraryRule , self ) . __init__ ( name , * args , ** kwargs ) <EOL> self . src_filter = '<STR_LIT>' <EOL> self . mode = mode <EOL> self . compiler_jar = compiler_jar <EOL> self . _append_dependent_paths ( [ self . compiler_jar ] ) <EOL> self . pretty_print = pretty_print <EOL> self . debug = debug <EOL> self . entry_points = [ ] <EOL> if isinstance ( entry_points , str ) : <EOL> self . entry_points . append ( entry_points ) <EOL> elif entry_points : <EOL> self . entry_points . extend ( entry_points ) <EOL> self . compiler_flags = [ ] <EOL> if compiler_flags : <EOL> self . compiler_flags . extend ( compiler_flags ) <EOL> self . externs = [ ] <EOL> if externs : <EOL> self . externs . extend ( externs ) <EOL> self . _append_dependent_paths ( self . externs ) <EOL> self . wrap_with_global = wrap_with_global <EOL> self . out = out <EOL> self . deps_out = deps_out <EOL> self . file_list_out = file_list_out <EOL> class _Context ( RuleContext ) : <EOL> def begin ( self ) : <EOL> super ( ClosureJsLibraryRule . _Context , self ) . begin ( ) <EOL> jar_path = self . _resolve_input_files ( [ self . rule . compiler_jar ] ) [ <NUM_LIT:0> ] <EOL> args = [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] <EOL> args . extend ( self . rule . compiler_flags ) <EOL> deps_only = False <EOL> compiling = False <EOL> if self . rule . mode == '<STR_LIT>' : <EOL> deps_only = True <EOL> elif self . rule . mode == '<STR_LIT>' : <EOL> compiling = True <EOL> args . append ( '<STR_LIT>' ) <EOL> args . append ( '<STR_LIT>' ) <EOL> args . append ( '<STR_LIT>' ) <EOL> elif self . rule . mode == '<STR_LIT>' : <EOL> compiling = True <EOL> args . append ( '<STR_LIT>' ) <EOL> elif self . rule . mode == '<STR_LIT>' : <EOL> compiling = True <EOL> args . append ( '<STR_LIT>' ) <EOL> if self . rule . pretty_print : <EOL> args . append ( '<STR_LIT>' ) <EOL> args . append ( '<STR_LIT>' ) <EOL> if not self . rule . debug : <EOL> args . append ( '<STR_LIT>' ) <EOL> args . append ( '<STR_LIT>' ) <EOL> if self . rule . wrap_with_global : <EOL> args . append ( '<STR_LIT>' % ( <EOL> self . rule . wrap_with_global ) ) <EOL> extern_paths = self . _resolve_input_files ( self . rule . externs ) <EOL> for extern_path in extern_paths : <EOL> args . append ( '<STR_LIT>' % ( extern_path ) ) <EOL> for entry_point in self . rule . entry_points : <EOL> args . append ( '<STR_LIT>' % ( entry_point ) ) <EOL> if compiling : <EOL> output_path = self . _get_out_path ( name = self . rule . out , suffix = '<STR_LIT>' ) <EOL> self . _ensure_output_exists ( os . path . dirname ( output_path ) ) <EOL> self . _append_output_paths ( [ output_path ] ) <EOL> args . append ( '<STR_LIT>' % ( output_path ) ) <EOL> deps_name = self . rule . deps_out or self . rule . out <EOL> deps_js_path = self . _get_out_path ( name = deps_name , suffix = '<STR_LIT>' ) <EOL> self . _ensure_output_exists ( os . path . dirname ( deps_js_path ) ) <EOL> self . _append_output_paths ( [ deps_js_path ] ) <EOL> file_list_path = None <EOL> if self . rule . file_list_out : <EOL> file_list_path = self . _get_out_path ( name = self . rule . file_list_out ) <EOL> self . _ensure_output_exists ( os . path . dirname ( file_list_path ) ) <EOL> self . _append_output_paths ( [ file_list_path ] ) <EOL> if self . _check_if_cached ( ) : <EOL> self . _succeed ( ) <EOL> return <EOL> d = self . _run_task_async ( _ScanJsDependenciesTask ( <EOL> self . build_env , self . src_paths ) ) <EOL> def _deps_scanned ( dep_graph ) : <EOL> ds = [ ] <EOL> used_paths = dep_graph . get_transitive_closure ( self . rule . entry_points ) <EOL> ds . append ( self . _run_task_async ( WriteFileTask ( <EOL> self . build_env , dep_graph . get_deps_js ( ) , deps_js_path ) ) ) <EOL> if file_list_path : <EOL> rel_used_paths = [ <EOL> os . path . relpath ( path , self . _get_rule_path ( ) ) <EOL> for path in used_paths ] <EOL> ds . append ( self . _run_task_async ( WriteFileTask ( <EOL> self . build_env , u'<STR_LIT:\n>' . join ( rel_used_paths ) , file_list_path ) ) ) <EOL> if compiling : <EOL> for src_path in used_paths : <EOL> args . append ( '<STR_LIT>' % ( src_path ) ) <EOL> ds . append ( self . _run_task_async ( JavaExecutableTask ( <EOL> self . build_env , jar_path , args , <EOL> pretty_name = str ( self . rule ) ) ) ) <EOL> else : <EOL> self . _append_output_paths ( used_paths ) <EOL> self . _chain ( ds ) <EOL> d . add_callback_fn ( _deps_scanned ) <EOL> self . _chain_errback ( d ) <EOL> class _ScanJsDependenciesTask ( Task ) : <EOL> def __init__ ( self , build_env , src_paths , * args , ** kwargs ) : <EOL> super ( _ScanJsDependenciesTask , self ) . __init__ ( build_env , * args , ** kwargs ) <EOL> self . src_paths = src_paths <EOL> def execute ( self ) : <EOL> deps_graph = JsDependencyGraph ( self . build_env , self . src_paths ) <EOL> return deps_graph <EOL> class JsDependencyFile ( object ) : <EOL> """<STR_LIT>""" <EOL> _PROVIDEREQURE_REGEX = re . compile ( <EOL> '<STR_LIT>' ) <EOL> _GOOG_BASE_LINE = ( <EOL> '<STR_LIT>' ) <EOL> def __init__ ( self , src_path ) : <EOL> """<STR_LIT>""" <EOL> self . src_path = src_path <EOL> self . provides = [ ] <EOL> self . requires = [ ] <EOL> self . is_base_js = False <EOL> self . is_css_rename_map = False <EOL> with io . open ( self . src_path , '<STR_LIT:rb>' ) as f : <EOL> self . _scan ( f ) <EOL> def _scan ( self , f ) : <EOL> """<STR_LIT>""" <EOL> provides = set ( ) <EOL> requires = set ( ) <EOL> for line in f . readlines ( ) : <EOL> match = self . _PROVIDEREQURE_REGEX . match ( line ) <EOL> if match : <EOL> if match . group ( <NUM_LIT:1> ) == '<STR_LIT>' : <EOL> provides . add ( str ( match . group ( <NUM_LIT:2> ) ) ) <EOL> else : <EOL> requires . add ( str ( match . group ( <NUM_LIT:2> ) ) ) <EOL> elif line . startswith ( self . _GOOG_BASE_LINE ) : <EOL> provides . add ( '<STR_LIT>' ) <EOL> self . is_base_js = True <EOL> elif line . startswith ( '<STR_LIT>' ) : <EOL> self . is_css_rename_map = True <EOL> self . provides = list ( provides ) <EOL> self . provides . sort ( ) <EOL> self . requires = list ( requires ) <EOL> self . requires . sort ( ) <EOL> class JsDependencyGraph ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , build_env , src_paths , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> self . build_env = build_env <EOL> self . src_paths = list ( src_paths ) <EOL> self . dep_files = { } <EOL> self . _provide_map = { } <EOL> self . base_dep_file = None <EOL> self . base_js_path = None <EOL> for src_path in self . src_paths : <EOL> dep_file = JsDependencyFile ( src_path ) <EOL> self . dep_files [ src_path ] = dep_file <EOL> if dep_file . is_base_js : <EOL> self . base_dep_file = dep_file <EOL> self . base_js_path = os . path . dirname ( dep_file . src_path ) <EOL> for provide in dep_file . provides : <EOL> assert not provide in self . _provide_map <EOL> self . _provide_map [ provide ] = dep_file <EOL> def get_deps_js ( self ) : <EOL> """<STR_LIT>""" <EOL> base_path = self . build_env . root_path <EOL> if self . base_js_path : <EOL> base_path = self . base_js_path <EOL> lines = [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] <EOL> src_paths = self . dep_files . keys ( ) <EOL> src_paths . sort ( ) <EOL> for src_path in src_paths : <EOL> dep_file = self . dep_files [ src_path ] <EOL> rel_path = os . path . relpath ( dep_file . src_path , base_path ) <EOL> rel_path = anvil . util . strip_build_paths ( rel_path ) <EOL> lines . append ( '<STR_LIT>' % ( <EOL> anvil . util . ensure_forwardslashes ( rel_path ) , <EOL> dep_file . provides , dep_file . requires ) ) <EOL> return u'<STR_LIT:\n>' . join ( lines ) <EOL> def get_transitive_closure ( self , entry_points ) : <EOL> """<STR_LIT>""" <EOL> deps_list = [ ] <EOL> if self . base_dep_file : <EOL> deps_list . append ( self . base_dep_file . src_path ) <EOL> for entry_point in entry_points : <EOL> self . _add_dependencies ( deps_list , entry_point ) <EOL> for dep_file in self . dep_files . values ( ) : <EOL> if dep_file . is_css_rename_map : <EOL> deps_list . append ( dep_file . src_path ) <EOL> return deps_list <EOL> def _add_dependencies ( self , deps_list , namespace ) : <EOL> if not namespace in self . _provide_map : <EOL> print '<STR_LIT>' % ( namespace ) <EOL> assert namespace in self . _provide_map <EOL> dep_file = self . _provide_map [ namespace ] <EOL> if dep_file . src_path in deps_list : <EOL> return <EOL> for require in dep_file . requires : <EOL> if require in dep_file . provides : <EOL> print '<STR_LIT>' % ( <EOL> require ) <EOL> assert not require in dep_file . provides <EOL> self . _add_dependencies ( deps_list , require ) <EOL> deps_list . append ( dep_file . src_path ) </s>
<s> """<STR_LIT>""" <EOL> class ApiException ( Exception ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , reason , def_dict = None ) : <EOL> """<STR_LIT>""" <EOL> super ( ApiException , self ) . __init__ ( ) <EOL> self . _reason = reason <EOL> self . _def_dict = def_dict <EOL> def __str__ ( self ) : <EOL> if self . _def_dict : <EOL> return '<STR_LIT>' % ( self . _reason , self . _def_dict ) <EOL> return self . _reason </s>
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> import os <EOL> import StringIO <EOL> import zipfile <EOL> from googleapis . codegen . filesys . library_package import LibraryPackage <EOL> class ZipLibraryPackage ( LibraryPackage ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , stream ) : <EOL> """<STR_LIT>""" <EOL> super ( ZipLibraryPackage , self ) . __init__ ( ) <EOL> self . _zip = zipfile . ZipFile ( stream , '<STR_LIT:w>' , zipfile . ZIP_STORED ) <EOL> self . _current_file_data = None <EOL> self . _created_dirs = [ ] <EOL> def StartFile ( self , name ) : <EOL> """<STR_LIT>""" <EOL> self . EndFile ( ) <EOL> self . _current_file_data = StringIO . StringIO ( ) <EOL> name = '<STR_LIT>' % ( self . _file_path_prefix , name ) <EOL> self . _current_file_name = name . encode ( '<STR_LIT:ascii>' ) <EOL> self . CreateDirectory ( os . path . dirname ( self . _current_file_name ) ) <EOL> return self . _current_file_data <EOL> def CreateDirectory ( self , directory ) : <EOL> """<STR_LIT>""" <EOL> to_create = [ ] <EOL> while directory : <EOL> if directory in self . _created_dirs : <EOL> break <EOL> to_create . append ( directory ) <EOL> self . _created_dirs . append ( directory ) <EOL> directory = os . path . dirname ( directory ) <EOL> to_create . reverse ( ) <EOL> for directory in to_create : <EOL> info = zipfile . ZipInfo ( ( directory + '<STR_LIT:/>' ) . encode ( '<STR_LIT:ascii>' ) , <EOL> date_time = self . ZipTimestamp ( ) ) <EOL> info . external_attr = ( <NUM_LIT:0> <NUM_LIT> << <NUM_LIT:16> ) | <NUM_LIT> <EOL> self . _zip . writestr ( info , '<STR_LIT>' ) <EOL> def EndFile ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _current_file_data : <EOL> info = zipfile . ZipInfo ( self . _current_file_name , <EOL> date_time = self . ZipTimestamp ( ) ) <EOL> info . external_attr = <NUM_LIT:0> <NUM_LIT> << <NUM_LIT:16> <EOL> data = self . _current_file_data . getvalue ( ) <EOL> if isinstance ( data , unicode ) : <EOL> data = data . encode ( '<STR_LIT:utf-8>' ) <EOL> self . _zip . writestr ( info , data ) <EOL> self . _current_file_data . close ( ) <EOL> self . _current_file_data = None <EOL> def ZipTimestamp ( self ) : <EOL> return ( <NUM_LIT> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:1> ) <EOL> def DoneWritingArchive ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _zip : <EOL> self . EndFile ( ) <EOL> self . _zip . close ( ) <EOL> self . _zip = None <EOL> def FileExtension ( self ) : <EOL> """<STR_LIT>""" <EOL> return '<STR_LIT>' <EOL> def MimeType ( self ) : <EOL> """<STR_LIT>""" <EOL> return '<STR_LIT>' </s>
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> import logging <EOL> import os <EOL> from googleapis . codegen . filesys import files <EOL> from googleapis . codegen . utilities import json_expander <EOL> from googleapis . codegen . utilities import json_with_comments <EOL> class Targets ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , targets_path = None , template_root = None , targets_dict = None ) : <EOL> """<STR_LIT>""" <EOL> self . template_root = template_root or Targets . _default_template_root <EOL> self . targets_path = targets_path or os . path . join ( self . template_root , <EOL> '<STR_LIT>' ) <EOL> if targets_dict : <EOL> self . _targets_dict = targets_dict <EOL> else : <EOL> self . _targets_dict = json_with_comments . Loads ( <EOL> files . GetFileContents ( self . targets_path ) ) <EOL> if '<STR_LIT>' not in self . _targets_dict : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> def Dict ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . _targets_dict <EOL> def VariationsForLanguage ( self , language ) : <EOL> language_def = self . _targets_dict [ '<STR_LIT>' ] . get ( language ) <EOL> if not language_def : <EOL> return None <EOL> return Variations ( self , language , language_def [ '<STR_LIT>' ] ) <EOL> def GetLanguage ( self , language ) : <EOL> return self . _targets_dict [ '<STR_LIT>' ] [ language ] <EOL> def Languages ( self ) : <EOL> return self . _targets_dict [ '<STR_LIT>' ] <EOL> def Platforms ( self ) : <EOL> return self . _targets_dict . get ( '<STR_LIT>' , { } ) <EOL> @ staticmethod <EOL> def SetDefaultTemplateRoot ( path ) : <EOL> """<STR_LIT>""" <EOL> logging . info ( '<STR_LIT>' , path ) <EOL> Targets . _default_template_root = path <EOL> @ staticmethod <EOL> def GetDefaultTemplateRoot ( ) : <EOL> return Targets . _default_template_root <EOL> _default_template_root = os . path . join ( os . path . dirname ( __file__ ) , <EOL> '<STR_LIT>' ) <EOL> use_versioned_paths = False <EOL> @ staticmethod <EOL> def SetUseVersionedPaths ( use_versioned_paths ) : <EOL> """<STR_LIT>""" <EOL> Targets . use_versioned_paths = use_versioned_paths <EOL> class Variations ( dict ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , targets , language , variations_dict ) : <EOL> super ( Variations , self ) . __init__ ( variations_dict ) <EOL> self . _targets = targets <EOL> self . _language = language <EOL> def IsValid ( self , variation ) : <EOL> """<STR_LIT>""" <EOL> return variation in self <EOL> def _RelativeTemplateDir ( self , variation ) : <EOL> """<STR_LIT>""" <EOL> if self . _targets . use_versioned_paths : <EOL> path = self [ variation ] . get ( '<STR_LIT>' ) or variation <EOL> else : <EOL> path = None <EOL> if not path : <EOL> path = self . get ( variation , { } ) . get ( '<STR_LIT:path>' ) or variation <EOL> return os . path . join ( self . _language , path ) <EOL> def AbsoluteTemplateDir ( self , variation ) : <EOL> """<STR_LIT>""" <EOL> return os . path . join ( self . _targets . template_root , <EOL> self . _RelativeTemplateDir ( variation ) ) <EOL> def GetFeaturesForReleaseVersion ( self , release_version ) : <EOL> for name in self : <EOL> features = self . GetFeatures ( name ) <EOL> if release_version == features . get ( '<STR_LIT>' ) : <EOL> return features <EOL> return None <EOL> def GetFeatures ( self , variation ) : <EOL> """<STR_LIT>""" <EOL> if not variation : <EOL> return None <EOL> template_dir = self . AbsoluteTemplateDir ( variation ) <EOL> features = Features ( template_dir , self . get ( variation ) , variation ) <EOL> json_path = os . path . join ( template_dir , '<STR_LIT>' ) <EOL> try : <EOL> features_json = files . GetFileContents ( json_path ) <EOL> except files . FileDoesNotExist : <EOL> return features <EOL> features . update ( json_expander . ExpandJsonTemplate ( <EOL> json_with_comments . Loads ( features_json ) ) ) <EOL> if not features . get ( '<STR_LIT>' ) : <EOL> features [ '<STR_LIT>' ] = variation <EOL> return features <EOL> class Features ( dict ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , template_dir , initial_content = None , name = None ) : <EOL> super ( Features , self ) . __init__ ( initial_content or { } ) <EOL> self . name = name <EOL> self . template_dir = template_dir <EOL> if '<STR_LIT:path>' not in self : <EOL> self [ '<STR_LIT:path>' ] = os . path . basename ( template_dir ) <EOL> def DependenciesForEnvironment ( self , environment = None ) : <EOL> """<STR_LIT>""" <EOL> required = [ ] <EOL> optional = [ ] <EOL> excluded = [ ] <EOL> for r in self . get ( '<STR_LIT>' , [ ] ) : <EOL> environments = r [ '<STR_LIT>' ] <EOL> if '<STR_LIT:*>' in environments or environment in environments : <EOL> required . append ( r ) <EOL> elif '<STR_LIT>' in environments or not environment : <EOL> optional . append ( r ) <EOL> else : <EOL> excluded . append ( r ) <EOL> return required , optional , excluded <EOL> def ExtractPathsFromDependencies ( self , dependencies , file_type = None ) : <EOL> """<STR_LIT>""" <EOL> ret = set ( ) <EOL> for d in dependencies or [ ] : <EOL> for f in d . get ( '<STR_LIT>' ) or [ ] : <EOL> p = f . get ( '<STR_LIT:path>' ) <EOL> if p and ( file_type is None or file_type == f . get ( '<STR_LIT:type>' ) ) : <EOL> ret . add ( p ) <EOL> return ret <EOL> def AllDependencyPaths ( self ) : <EOL> """<STR_LIT>""" <EOL> ret = set ( ) <EOL> for dependency in self . get ( '<STR_LIT>' , [ ] ) : <EOL> for f in dependency . get ( '<STR_LIT>' ) or [ ] : <EOL> p = f . get ( '<STR_LIT:path>' ) <EOL> if p : <EOL> ret . add ( p ) <EOL> return ret <EOL> def FilePathsWeDoNotDependOn ( self , environment = None , file_type = None ) : <EOL> """<STR_LIT>""" <EOL> if not environment and not file_type : <EOL> return [ ] <EOL> req , _ , _ = self . DependenciesForEnvironment ( environment = environment ) <EOL> req_paths = self . ExtractPathsFromDependencies ( req , file_type = file_type ) <EOL> all_paths = self . AllDependencyPaths ( ) <EOL> return all_paths - req_paths </s>
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> import logging <EOL> class Error ( Exception ) : <EOL> """<STR_LIT>""" <EOL> class FileError ( Error ) : <EOL> """<STR_LIT>""" <EOL> class Container ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , lines = None , relative_path = '<STR_LIT>' , absolute_path = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> self . lines = lines if lines else [ ] <EOL> self . absolute_path = absolute_path <EOL> self . relative_path = relative_path <EOL> class FileFilter ( object ) : <EOL> """<STR_LIT>""" <EOL> def Filter ( self , container , args ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( <EOL> '<STR_LIT>' ) <EOL> class PrintFilter ( FileFilter ) : <EOL> """<STR_LIT>""" <EOL> def Filter ( self , container , unused_args ) : <EOL> """<STR_LIT>""" <EOL> print '<STR_LIT>' % container . absolute_path <EOL> print '<STR_LIT:\n>' . join ( container . lines ) <EOL> return container <EOL> class WriteFileFilter ( FileFilter ) : <EOL> """<STR_LIT>""" <EOL> def Filter ( self , container , unused_args ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> f = file ( container . absolute_path , '<STR_LIT:w>' ) <EOL> except IOError as e : <EOL> raise FileError ( '<STR_LIT>' % ( <EOL> container . absolute_path , e ) ) <EOL> try : <EOL> f . write ( '<STR_LIT:\n>' . join ( container . lines ) ) <EOL> except IOError as e : <EOL> raise FileError ( '<STR_LIT>' % ( <EOL> container . absolute_path , e ) ) <EOL> else : <EOL> f . close ( ) <EOL> logging . info ( '<STR_LIT>' , container . absolute_path ) <EOL> return container </s>
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class Error ( Exception ) : <EOL> """<STR_LIT>""" <EOL> class BadPortValue ( Error ) : <EOL> """<STR_LIT>""" <EOL> class BadPortRange ( Error ) : <EOL> """<STR_LIT>""" <EOL> def Port ( port ) : <EOL> """<STR_LIT>""" <EOL> pval = - <NUM_LIT:1> <EOL> try : <EOL> pval = int ( port ) <EOL> except ValueError : <EOL> raise BadPortValue ( '<STR_LIT>' % port ) <EOL> if pval < <NUM_LIT:0> or pval > <NUM_LIT> : <EOL> raise BadPortRange ( '<STR_LIT>' % port ) <EOL> return pval </s>
<s> try : <EOL> from setuptools import setup , find_packages <EOL> except ImportError : <EOL> print '<STR_LIT>' <EOL> print '<STR_LIT>' <EOL> raise SystemExit ( <NUM_LIT:1> ) <EOL> REQUIRE = [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] <EOL> REQUIRE_SETUP = [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] <EOL> REQUIRE_TESTS = REQUIRE + [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] <EOL> CV_STUBS = [ <EOL> ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ] <EOL> CV_ENTRY_POINTS = [ '<STR_LIT>' % s for s in CV_STUBS ] <EOL> setup ( <EOL> name = '<STR_LIT>' , <EOL> version = '<STR_LIT>' , <EOL> url = '<STR_LIT>' , <EOL> license = '<STR_LIT>' , <EOL> description = '<STR_LIT>' , <EOL> author = '<STR_LIT>' , <EOL> author_email = '<STR_LIT>' , <EOL> packages = find_packages ( '<STR_LIT:src>' , exclude = [ '<STR_LIT>' ] ) , <EOL> package_dir = { '<STR_LIT>' : '<STR_LIT:src>' } , <EOL> package_data = { <EOL> '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> } , <EOL> include_package_data = True , <EOL> entry_points = { <EOL> '<STR_LIT>' : CV_ENTRY_POINTS , <EOL> } , <EOL> setup_requires = REQUIRE_SETUP , <EOL> install_requires = REQUIRE , <EOL> tests_require = REQUIRE_TESTS , <EOL> google_test_dir = '<STR_LIT>' , <EOL> ) </s>
<s> import collections <EOL> import httplib <EOL> import mock <EOL> from django . conf import settings <EOL> settings . configure ( ) <EOL> from google . appengine . api import users <EOL> from google . apputils import app <EOL> from google . apputils import basetest <EOL> from cauliflowervest . server import handlers <EOL> from cauliflowervest . server import main as gae_main <EOL> from cauliflowervest . server import models <EOL> from cauliflowervest . server import permissions <EOL> from cauliflowervest . server import util <EOL> from tests . cauliflowervest . server . handlers import test_util <EOL> class VolumeTypesModuleTest ( basetest . TestCase ) : <EOL> def setUp ( self ) : <EOL> super ( VolumeTypesModuleTest , self ) . setUp ( ) <EOL> test_util . SetUpTestbedTestCase ( self ) <EOL> def tearDown ( self ) : <EOL> super ( VolumeTypesModuleTest , self ) . tearDown ( ) <EOL> test_util . TearDownTestbedTestCase ( self ) <EOL> def testOk ( self ) : <EOL> models . User ( <EOL> key_name = '<STR_LIT>' , user = users . get_current_user ( ) , <EOL> filevault_perms = [ permissions . SEARCH ] , luks_perms = [ permissions . SEARCH ] , <EOL> ) . put ( ) <EOL> resp = gae_main . app . get_response ( <EOL> '<STR_LIT>' , { '<STR_LIT>' : '<STR_LIT:GET>' } ) <EOL> self . assertEqual ( httplib . OK , resp . status_int ) <EOL> data = util . FromSafeJson ( resp . body ) <EOL> volume_fields = { x : y for x , y in data . items ( ) if '<STR_LIT>' in y } <EOL> self . assertEqual ( <NUM_LIT:2> , len ( volume_fields ) ) <EOL> @ mock . patch . object ( <EOL> handlers , '<STR_LIT>' , <EOL> return_value = collections . defaultdict ( lambda : False ) ) <EOL> def testOkStatusWithoutPermissions ( self , * _ ) : <EOL> resp = gae_main . app . get_response ( <EOL> '<STR_LIT>' , { '<STR_LIT>' : '<STR_LIT:GET>' } ) <EOL> self . assertEqual ( httplib . OK , resp . status_int ) <EOL> self . assertEqual ( <NUM_LIT:0> , len ( util . FromSafeJson ( resp . body ) ) ) <EOL> @ mock . patch . dict ( <EOL> handlers . settings . __dict__ , { <EOL> '<STR_LIT>' : { <EOL> permissions . TYPE_LUKS : ( permissions . RETRIEVE_OWN ) <EOL> } <EOL> } ) <EOL> def testNoSearchPermissionsCanRetrieveOwn ( self ) : <EOL> resp = gae_main . app . get_response ( <EOL> '<STR_LIT>' , { '<STR_LIT>' : '<STR_LIT:GET>' } ) <EOL> self . assertEqual ( httplib . OK , resp . status_int ) <EOL> data = util . FromSafeJson ( resp . body ) <EOL> self . assertEqual ( '<STR_LIT>' , data [ '<STR_LIT:user>' ] ) <EOL> self . assertEqual ( <NUM_LIT:2> , len ( data ) ) <EOL> self . assertEqual ( <EOL> [ permissions . RETRIEVE_OWN ] , data [ permissions . TYPE_LUKS ] . keys ( ) ) <EOL> self . assertTrue ( data [ permissions . TYPE_LUKS ] [ permissions . RETRIEVE_OWN ] ) <EOL> def main ( _ ) : <EOL> basetest . main ( ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> app . run ( ) </s>
<s> """<STR_LIT>""" <EOL> import unittest as googletest <EOL> from closure_linter import error_fixer <EOL> from closure_linter import testutil <EOL> from closure_linter import tokenutil <EOL> class ErrorFixerTest ( googletest . TestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . error_fixer = error_fixer . ErrorFixer ( ) <EOL> def testDeleteToken ( self ) : <EOL> start_token = testutil . TokenizeSourceAndRunEcmaPass ( _TEST_SCRIPT ) <EOL> second_token = start_token . next <EOL> self . error_fixer . HandleFile ( '<STR_LIT>' , start_token ) <EOL> self . error_fixer . _DeleteToken ( start_token ) <EOL> self . assertEqual ( second_token , self . error_fixer . _file_token ) <EOL> def testDeleteTokens ( self ) : <EOL> start_token = testutil . TokenizeSourceAndRunEcmaPass ( _TEST_SCRIPT ) <EOL> fourth_token = start_token . next . next . next <EOL> self . error_fixer . HandleFile ( '<STR_LIT>' , start_token ) <EOL> self . error_fixer . _DeleteTokens ( start_token , <NUM_LIT:3> ) <EOL> self . assertEqual ( fourth_token , self . error_fixer . _file_token ) <EOL> def DoTestFixJsDocPipeNull ( self , expected , original ) : <EOL> _ , comments = testutil . ParseFunctionsAndComments ( <EOL> '<STR_LIT>' % original ) <EOL> jstype = comments [ <NUM_LIT:0> ] . GetDocFlags ( ) [ <NUM_LIT:0> ] . jstype <EOL> self . error_fixer . HandleFile ( '<STR_LIT>' , None ) <EOL> self . error_fixer . _FixJsDocPipeNull ( jstype ) <EOL> self . assertEquals ( expected , repr ( jstype ) ) <EOL> result = tokenutil . TokensToString ( jstype . FirstToken ( ) ) . strip ( '<STR_LIT>' ) <EOL> self . assertEquals ( expected , result ) <EOL> def testFixJsDocPipeNull ( self ) : <EOL> self . DoTestFixJsDocPipeNull ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . DoTestFixJsDocPipeNull ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . DoTestFixJsDocPipeNull ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> self . DoTestFixJsDocPipeNull ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> _TEST_SCRIPT = """<STR_LIT>""" <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> googletest . main ( ) </s>
<s> """<STR_LIT>""" <EOL> import gflags as flags <EOL> import unittest as googletest <EOL> from closure_linter import errors <EOL> from closure_linter import runner <EOL> from closure_linter . common import erroraccumulator <EOL> flags . FLAGS . check_trailing_comma = True <EOL> class TrailingCommaTest ( googletest . TestCase ) : <EOL> """<STR_LIT>""" <EOL> def testGetTrailingCommaArray ( self ) : <EOL> """<STR_LIT>""" <EOL> original = [ '<STR_LIT>' , ] <EOL> expected = errors . COMMA_AT_END_OF_LITERAL <EOL> self . _AssertInError ( original , expected ) <EOL> def testGetTrailingCommaDict ( self ) : <EOL> """<STR_LIT>""" <EOL> original = [ '<STR_LIT>' , ] <EOL> expected = errors . COMMA_AT_END_OF_LITERAL <EOL> self . _AssertInError ( original , expected ) <EOL> def _AssertInError ( self , original , expected ) : <EOL> """<STR_LIT>""" <EOL> error_accumulator = erroraccumulator . ErrorAccumulator ( ) <EOL> runner . Run ( '<STR_LIT>' , error_accumulator , source = original ) <EOL> error_nums = [ e . code for e in error_accumulator . GetErrors ( ) ] <EOL> self . assertIn ( expected , error_nums ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> googletest . main ( ) </s>
<s> def PickScorer ( name ) : <EOL> scorer_map = { <EOL> '<STR_LIT>' : ScorePsnrBitrate , <EOL> '<STR_LIT>' : ScoreCpuPsnr , <EOL> } <EOL> return scorer_map [ name ] <EOL> def ScorePsnrBitrate ( target_bitrate , result ) : <EOL> """<STR_LIT>""" <EOL> if not result : <EOL> return None <EOL> score = result [ '<STR_LIT>' ] <EOL> if result [ '<STR_LIT>' ] > int ( target_bitrate ) : <EOL> score -= ( result [ '<STR_LIT>' ] - int ( target_bitrate ) ) * <NUM_LIT:0.1> <EOL> return score <EOL> def ScoreCpuPsnr ( target_bitrate , result ) : <EOL> """<STR_LIT>""" <EOL> if target_bitrate == <NUM_LIT:0.0> : <EOL> return - <NUM_LIT:1.0> <EOL> score = result [ '<STR_LIT>' ] <EOL> if result [ '<STR_LIT>' ] > int ( target_bitrate ) : <EOL> percent_overshoot = <NUM_LIT> * ( ( result [ '<STR_LIT>' ] - float ( target_bitrate ) ) <EOL> / float ( target_bitrate ) ) <EOL> score -= <NUM_LIT:0.1> * percent_overshoot <EOL> used_time = result [ '<STR_LIT>' ] <EOL> available_time = result [ '<STR_LIT>' ] <EOL> if used_time > available_time : <EOL> badness = ( used_time - available_time ) / available_time <EOL> score -= badness * <NUM_LIT:100> <EOL> return score <EOL> def DelayCalculation ( frame_info_list , framerate , bitrate , buffer_size , <EOL> print_trace = False ) : <EOL> """<STR_LIT>""" <EOL> for frame in frame_info_list : <EOL> frame [ '<STR_LIT>' ] = float ( frame [ '<STR_LIT:size>' ] ) / bitrate <EOL> playback_clock = buffer_size <EOL> buffer_clock = <NUM_LIT:0> <EOL> delay = <NUM_LIT:0> <EOL> frame_count = <NUM_LIT:0> <EOL> for frame in frame_info_list : <EOL> buffer_clock += frame [ '<STR_LIT>' ] <EOL> playback_clock += <NUM_LIT:1.0> / framerate <EOL> if buffer_clock > playback_clock : <EOL> delay += ( buffer_clock - playback_clock ) <EOL> if print_trace : <EOL> print '<STR_LIT>' % ( frame_count , <EOL> buffer_clock - playback_clock ) <EOL> playback_clock = buffer_clock <EOL> frame_count += <NUM_LIT:1> <EOL> return delay / ( float ( frame_count ) / framerate ) </s>
<s> """<STR_LIT>""" <EOL> from google . apputils import app <EOL> import logging <EOL> from google . apputils import basetest as googletest <EOL> import ebq_crypto as ecrypto <EOL> _KEY1 = '<STR_LIT>' <EOL> _PLAINTEXT1 = '<STR_LIT>' <EOL> class ProbabilisticCiphertTest ( googletest . TestCase ) : <EOL> def setUp ( self ) : <EOL> """<STR_LIT>""" <EOL> self . cipher = ecrypto . ProbabilisticCipher ( _KEY1 ) <EOL> def testProbabilisticEncryptDecryptUnicodeString ( self ) : <EOL> logging . debug ( '<STR_LIT>' ) <EOL> for plaintext in ( u'<STR_LIT>' , u'<STR_LIT>' , u'<STR_LIT>' , u'<STR_LIT>' , <EOL> u"""<STR_LIT>""" ) : <EOL> ciphertext = self . cipher . Encrypt ( plaintext ) <EOL> self . assertEqual ( plaintext , self . cipher . Decrypt ( ciphertext ) ) <EOL> try : <EOL> self . cipher . Encrypt ( <NUM_LIT> ) <EOL> self . fail ( ) <EOL> except ValueError : <EOL> pass <EOL> class PseudonymCiphertTest ( googletest . TestCase ) : <EOL> def setUp ( self ) : <EOL> """<STR_LIT>""" <EOL> self . cipher = ecrypto . PseudonymCipher ( _KEY1 ) <EOL> def testPseudonymEncryptDecryptUnicodeString ( self ) : <EOL> logging . debug ( '<STR_LIT>' ) <EOL> for plaintext in ( u'<STR_LIT>' , u'<STR_LIT>' , u'<STR_LIT>' , u'<STR_LIT>' , <EOL> u"""<STR_LIT>""" ) : <EOL> ciphertext = self . cipher . Encrypt ( plaintext ) <EOL> self . assertEqual ( plaintext , self . cipher . Decrypt ( ciphertext ) ) <EOL> try : <EOL> self . cipher . Encrypt ( <NUM_LIT> ) <EOL> self . fail ( ) <EOL> except ValueError : <EOL> pass <EOL> def _GetRandForTesting ( size ) : <EOL> return size * '<STR_LIT:1>' <EOL> class HomomorphicIntCiphertTest ( googletest . TestCase ) : <EOL> def setUp ( self ) : <EOL> """<STR_LIT>""" <EOL> self . cipher = ecrypto . HomomorphicIntCipher ( _KEY1 ) <EOL> def testHomomorphicEncryptIntDecryptInt ( self ) : <EOL> logging . debug ( '<STR_LIT>' ) <EOL> for plaintext in ( <NUM_LIT:2> , <NUM_LIT:5> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) : <EOL> ciphertext = self . cipher . Encrypt ( plaintext ) <EOL> self . assertEqual ( plaintext , self . cipher . Decrypt ( ciphertext ) ) <EOL> try : <EOL> self . cipher . Encrypt ( '<STR_LIT>' ) <EOL> self . fail ( ) <EOL> except ValueError : <EOL> pass <EOL> try : <EOL> self . cipher . Encrypt ( <NUM_LIT> ) <EOL> self . fail ( ) <EOL> except ValueError : <EOL> pass <EOL> class HomomorphicFloatCipherTest ( googletest . TestCase ) : <EOL> def setUp ( self ) : <EOL> """<STR_LIT>""" <EOL> self . cipher = ecrypto . HomomorphicFloatCipher ( _KEY1 ) <EOL> def testHomomorphicEncryptFloatDecryptFloat ( self ) : <EOL> logging . debug ( '<STR_LIT>' ) <EOL> for plaintext in ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) : <EOL> ciphertext = self . cipher . Encrypt ( plaintext ) <EOL> self . assertEqual ( plaintext , self . cipher . Decrypt ( ciphertext ) ) <EOL> try : <EOL> self . cipher . Encrypt ( <NUM_LIT:1.0> * <NUM_LIT:2> ** <NUM_LIT> ) <EOL> self . fail ( ) <EOL> except ValueError : <EOL> pass <EOL> try : <EOL> self . cipher . Encrypt ( '<STR_LIT>' ) <EOL> self . fail ( ) <EOL> except ValueError : <EOL> pass <EOL> class StringHashTest ( googletest . TestCase ) : <EOL> def setUp ( self ) : <EOL> """<STR_LIT>""" <EOL> self . hasher = ecrypto . StringHash ( _KEY1 , <NUM_LIT:8> , '<STR_LIT>' ) <EOL> self . fieldname = u'<STR_LIT>' <EOL> def testGetStringKeyHash ( self ) : <EOL> logging . debug ( '<STR_LIT>' ) <EOL> hash1 = self . hasher . GetStringKeyHash ( self . fieldname , u'<STR_LIT>' ) <EOL> self . assertEqual ( <NUM_LIT:12> , len ( hash1 ) ) <EOL> hash2 = self . hasher . GetStringKeyHash ( self . fieldname , u'<STR_LIT>' ) <EOL> self . assertEqual ( hash1 , hash2 ) <EOL> hash3 = self . hasher . GetStringKeyHash ( self . fieldname , u'<STR_LIT>' ) <EOL> self . assertNotEqual ( hash1 , hash3 ) <EOL> hash4 = self . hasher . GetStringKeyHash ( self . fieldname , u'<STR_LIT>' , <EOL> output_len = <NUM_LIT> ) <EOL> self . assertEqual ( <NUM_LIT> , len ( hash4 ) ) <EOL> hash5 = self . hasher . GetStringKeyHash ( self . fieldname , u'<STR_LIT>' , <EOL> output_len = <NUM_LIT> , hashfunc = '<STR_LIT>' ) <EOL> self . assertNotEqual ( hash4 , hash5 ) <EOL> hasher6 = ecrypto . StringHash ( _KEY1 , <NUM_LIT> , '<STR_LIT>' ) <EOL> self . assertEqual ( hash5 , hasher6 . GetStringKeyHash ( self . fieldname , u'<STR_LIT>' ) ) <EOL> def testGetHashessForWordSubsequencesWithIv ( self ) : <EOL> logging . debug ( '<STR_LIT>' ) <EOL> text = u'<STR_LIT>' <EOL> hashes1 = self . hasher . GetHashesForWordSubsequencesWithIv ( <EOL> self . fieldname , text , random_permute = False , rand_gen = _GetRandForTesting ) <EOL> self . assertEqual ( <NUM_LIT> , len ( hashes1 . split ( ) ) ) <EOL> self . assertEqual ( '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' , hashes1 ) <EOL> hashes2 = self . hasher . GetHashesForWordSubsequencesWithIv ( <EOL> self . fieldname , text , random_permute = False , rand_gen = _GetRandForTesting ) <EOL> self . assertEqual ( hashes1 , hashes2 ) <EOL> hashes3 = self . hasher . GetHashesForWordSubsequencesWithIv ( <EOL> self . fieldname , text [ <NUM_LIT:3> : ] , random_permute = False , <EOL> rand_gen = _GetRandForTesting ) <EOL> self . assertNotEqual ( hashes1 , hashes3 ) <EOL> self . assertEqual ( <NUM_LIT> , len ( hashes3 . split ( ) ) ) <EOL> hashes4 = self . hasher . GetHashesForWordSubsequencesWithIv ( <EOL> self . fieldname , text [ <NUM_LIT:3> : ] , output_len = <NUM_LIT:16> , random_permute = False , <EOL> rand_gen = _GetRandForTesting ) <EOL> self . assertEqual ( <NUM_LIT> , len ( hashes4 . split ( ) [ <NUM_LIT:1> ] ) ) <EOL> hashes5 = self . hasher . GetHashesForWordSubsequencesWithIv ( <EOL> self . fieldname , text [ <NUM_LIT:3> : ] , hashfunc = '<STR_LIT>' , random_permute = False , <EOL> rand_gen = _GetRandForTesting ) <EOL> self . assertNotEqual ( hashes1 , hashes5 ) <EOL> hashes6 = self . hasher . GetHashesForWordSubsequencesWithIv ( <EOL> self . fieldname , text , max_sequence_len = <NUM_LIT:3> , random_permute = False ) <EOL> self . assertEqual ( <NUM_LIT> , len ( hashes6 . split ( ) ) ) <EOL> unclean_text = ( u'<STR_LIT>' '<STR_LIT>' + <EOL> u'<STR_LIT>' ) <EOL> hashes_unclean = self . hasher . GetHashesForWordSubsequencesWithIv ( <EOL> self . fieldname , unclean_text [ <NUM_LIT:3> : ] , random_permute = False , <EOL> rand_gen = _GetRandForTesting ) <EOL> self . assertEqual ( hashes3 , hashes_unclean ) <EOL> text_slash = u'<STR_LIT>' <EOL> hashes_slash = self . hasher . GetHashesForWordSubsequencesWithIv ( <EOL> self . fieldname , text_slash , random_permute = False , <EOL> rand_gen = _GetRandForTesting , separator = '<STR_LIT:/>' ) <EOL> self . assertEqual ( <NUM_LIT:7> , len ( hashes_slash . split ( ) ) ) <EOL> self . assertEqual ( '<STR_LIT>' <EOL> '<STR_LIT>' , <EOL> hashes_slash ) <EOL> empty_text = u'<STR_LIT>' <EOL> hashes_empty = self . hasher . GetHashesForWordSubsequencesWithIv ( <EOL> self . fieldname , empty_text , random_permute = False , <EOL> rand_gen = _GetRandForTesting ) <EOL> self . assertEqual ( '<STR_LIT>' , hashes_empty ) <EOL> def main ( _ ) : <EOL> googletest . main ( ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> app . run ( ) </s>
<s> from ... util import s16 , s32 , s64 <EOL> from . . import scalartypes as scalars <EOL> from . . jvmops import * <EOL> from . import lookup <EOL> from . genlookup import FLOAT_SIGN , FLOAT_INF , FLOAT_NINF , FLOAT_NAN , DOUBLE_SIGN , DOUBLE_INF , DOUBLE_NINF , DOUBLE_NAN <EOL> def normalizeFloat ( x ) : <EOL> x %= <NUM_LIT:1> << <NUM_LIT:32> <EOL> if x | FLOAT_SIGN > FLOAT_NINF : <EOL> return FLOAT_NAN <EOL> return x <EOL> def normalizeDouble ( x ) : <EOL> x %= <NUM_LIT:1> << <NUM_LIT:64> <EOL> if x | DOUBLE_SIGN > DOUBLE_NINF : <EOL> return DOUBLE_NAN <EOL> return x <EOL> def _calcInt ( x ) : <EOL> assert ( x == s32 ( x ) ) <EOL> if x in lookup . INTS : <EOL> return lookup . INTS [ x ] <EOL> low = s16 ( x ) <EOL> high = ( x ^ low ) >> <NUM_LIT:16> <EOL> assert ( high ) <EOL> if not low : <EOL> return _calcInt ( high ) + _calcInt ( <NUM_LIT:16> ) + bytes ( [ ISHL ] ) <EOL> return _calcInt ( high ) + _calcInt ( <NUM_LIT:16> ) + bytes ( [ ISHL ] ) + _calcInt ( low ) + bytes ( [ IXOR ] ) <EOL> def _calcLong ( x ) : <EOL> assert ( x == s64 ( x ) ) <EOL> if x in lookup . LONGS : <EOL> return lookup . LONGS [ x ] <EOL> low = s32 ( x ) <EOL> high = ( x ^ low ) >> <NUM_LIT:32> <EOL> if not high : <EOL> return _calcInt ( low ) + bytes ( [ I2L ] ) <EOL> result = _calcInt ( high ) + bytes ( [ I2L ] ) + _calcInt ( <NUM_LIT:32> ) + bytes ( [ LSHL ] ) <EOL> if low : <EOL> result += _calcInt ( low ) + bytes ( [ I2L , LXOR ] ) <EOL> return result <EOL> def _calcFloat ( x ) : <EOL> assert ( x == normalizeFloat ( x ) ) <EOL> if x in lookup . FLOATS : <EOL> return lookup . FLOATS [ x ] <EOL> exponent = ( ( x >> <NUM_LIT> ) & <NUM_LIT> ) - <NUM_LIT> <EOL> mantissa = x % ( <NUM_LIT:1> << <NUM_LIT> ) <EOL> if exponent == - <NUM_LIT> : <EOL> exponent += <NUM_LIT:1> <EOL> else : <EOL> mantissa += <NUM_LIT:1> << <NUM_LIT> <EOL> exponent -= <NUM_LIT> <EOL> if x & FLOAT_SIGN : <EOL> mantissa = - mantissa <EOL> ex_combine_op = FDIV if exponent < <NUM_LIT:0> else FMUL <EOL> exponent = abs ( exponent ) <EOL> exponent_parts = bytearray ( ) <EOL> while exponent >= <NUM_LIT> : <EOL> exponent_parts . extend ( [ LCONST_1 , ICONST_M1 , LSHL , L2F , ex_combine_op ] ) <EOL> mantissa = - mantissa <EOL> exponent -= <NUM_LIT> <EOL> if exponent > <NUM_LIT:0> : <EOL> exponent_parts . append ( LCONST_1 ) <EOL> exponent_parts . extend ( _calcInt ( exponent ) ) <EOL> exponent_parts . extend ( [ LSHL , L2F , ex_combine_op ] ) <EOL> return _calcInt ( mantissa ) + bytes ( [ I2F ] ) + exponent_parts <EOL> def _calcDouble ( x ) : <EOL> assert ( x == normalizeDouble ( x ) ) <EOL> if x in lookup . DOUBLES : <EOL> return lookup . DOUBLES [ x ] <EOL> exponent = ( ( x >> <NUM_LIT> ) & <NUM_LIT> ) - <NUM_LIT> <EOL> mantissa = x % ( <NUM_LIT:1> << <NUM_LIT> ) <EOL> if exponent == - <NUM_LIT> : <EOL> exponent += <NUM_LIT:1> <EOL> else : <EOL> mantissa += <NUM_LIT:1> << <NUM_LIT> <EOL> exponent -= <NUM_LIT> <EOL> if x & DOUBLE_SIGN : <EOL> mantissa = - mantissa <EOL> abs_exponent = abs ( exponent ) <EOL> exponent_parts = bytearray ( ) <EOL> part63 = abs_exponent // <NUM_LIT> <EOL> if part63 : <EOL> if exponent < <NUM_LIT:0> : <EOL> exponent_parts . extend ( [ DCONST_1 , LCONST_1 , ICONST_M1 , LSHL , L2D , DDIV ] ) <EOL> else : <EOL> exponent_parts . extend ( [ LCONST_1 , ICONST_M1 , LSHL , L2D ] ) <EOL> if part63 & <NUM_LIT:1> : <EOL> mantissa = - mantissa <EOL> last_needed = part63 & <NUM_LIT:1> <EOL> stack = [ <NUM_LIT:1> ] <EOL> for bi in range ( <NUM_LIT:1> , part63 . bit_length ( ) ) : <EOL> exponent_parts . append ( DUP2 ) <EOL> stack . append ( stack [ - <NUM_LIT:1> ] ) <EOL> if last_needed : <EOL> exponent_parts . append ( DUP2 ) <EOL> stack . append ( stack [ - <NUM_LIT:1> ] ) <EOL> exponent_parts . append ( DMUL ) <EOL> stack . append ( stack . pop ( ) + stack . pop ( ) ) <EOL> last_needed = part63 & ( <NUM_LIT:1> << bi ) <EOL> assert ( sum ( stack ) == part63 and len ( stack ) == bin ( part63 ) . count ( '<STR_LIT:1>' ) ) <EOL> exponent_parts . extend ( [ DMUL ] * bin ( part63 ) . count ( '<STR_LIT:1>' ) ) <EOL> rest = abs_exponent % <NUM_LIT> <EOL> if rest : <EOL> exponent_parts . append ( LCONST_1 ) <EOL> exponent_parts . extend ( _calcInt ( rest ) ) <EOL> exponent_parts . extend ( [ LSHL , L2D ] ) <EOL> exponent_parts . append ( DDIV if exponent < <NUM_LIT:0> else DMUL ) <EOL> return _calcLong ( mantissa ) + bytes ( [ L2D ] ) + exponent_parts <EOL> def calcInt ( x ) : return _calcInt ( s32 ( x ) ) <EOL> def calcLong ( x ) : return _calcLong ( s64 ( x ) ) <EOL> def calcFloat ( x ) : return _calcFloat ( normalizeFloat ( x ) ) <EOL> def calcDouble ( x ) : return _calcDouble ( normalizeDouble ( x ) ) <EOL> def normalize ( st , val ) : <EOL> if st == scalars . FLOAT : <EOL> return normalizeFloat ( val ) <EOL> elif st == scalars . DOUBLE : <EOL> return normalizeDouble ( val ) <EOL> return val <EOL> def calc ( st , val ) : <EOL> if st == scalars . INT : <EOL> return calcInt ( val ) <EOL> elif st == scalars . FLOAT : <EOL> return calcFloat ( val ) <EOL> elif st == scalars . LONG : <EOL> return calcLong ( val ) <EOL> elif st == scalars . DOUBLE : <EOL> return calcDouble ( val ) <EOL> assert ( <NUM_LIT:0> ) <EOL> def lookupOnly ( st , val ) : <EOL> if st == scalars . INT : <EOL> return lookup . INTS . get ( s32 ( val ) ) <EOL> elif st == scalars . FLOAT : <EOL> return lookup . FLOATS . get ( val ) <EOL> elif st == scalars . LONG : <EOL> return lookup . LONGS . get ( s64 ( val ) ) <EOL> elif st == scalars . DOUBLE : <EOL> return lookup . DOUBLES . get ( val ) </s>
<s> import logging <EOL> from optparse import OptionParser <EOL> import os <EOL> import sys <EOL> try : <EOL> sys . path . append ( os . path . join ( os . path . dirname ( __file__ ) , os . pardir ) ) <EOL> except NameError : <EOL> sys . path . append ( os . path . join ( os . path . dirname ( <EOL> locals ( ) . get ( "<STR_LIT>" , "<STR_LIT>" ) ) , os . pardir ) ) <EOL> import setuputil . android <EOL> import setuputil . linux <EOL> import setuputil . mac <EOL> import setuputil . windows <EOL> """<STR_LIT>""" <EOL> def say_hello ( ) : <EOL> """<STR_LIT>""" <EOL> print ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> answer = raw_input ( "<STR_LIT>" ) <EOL> if answer . lower ( ) . startswith ( "<STR_LIT:q>" ) : <EOL> return False <EOL> else : <EOL> return True <EOL> def create_option_parser ( ) : <EOL> """<STR_LIT>""" <EOL> parser = OptionParser ( ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store>" , type = "<STR_LIT:string>" , <EOL> dest = "<STR_LIT>" , default = setuputil . common . BASE_DIR , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store>" , type = "<STR_LIT:string>" , <EOL> dest = "<STR_LIT>" , default = setuputil . common . BASE_DIR , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store>" , type = "<STR_LIT:string>" , <EOL> dest = "<STR_LIT>" , default = setuputil . common . BASE_DIR , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store>" , type = "<STR_LIT:string>" , <EOL> dest = "<STR_LIT>" , default = setuputil . common . BASE_DIR , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store>" , type = "<STR_LIT:string>" , <EOL> dest = "<STR_LIT>" , default = setuputil . common . BASE_DIR , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store>" , type = "<STR_LIT:string>" , <EOL> dest = "<STR_LIT>" , default = setuputil . common . BASE_DIR , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store>" , type = "<STR_LIT:string>" , <EOL> dest = "<STR_LIT>" , default = setuputil . common . BASE_DIR , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store_true>" , <EOL> dest = "<STR_LIT>" , default = False , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store_true>" , <EOL> dest = "<STR_LIT>" , default = False , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store_true>" , <EOL> dest = "<STR_LIT>" , default = False , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store_true>" , <EOL> dest = "<STR_LIT>" , default = False , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , action = "<STR_LIT:store_true>" , <EOL> dest = "<STR_LIT>" , default = False , <EOL> help = "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> options , _ = parser . parse_args ( ) <EOL> return options <EOL> def create_logger ( ) : <EOL> """<STR_LIT>""" <EOL> logging . basicConfig ( ) <EOL> logging . getLogger ( ) . setLevel ( logging . INFO ) <EOL> def linux_setup ( ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> setup = setuputil . linux . LinuxSetup ( ) <EOL> setup . setup_all ( ) <EOL> return <EOL> except setuputil . common . VersionUnsupportedError as e : <EOL> logging . error ( "<STR_LIT>" ) <EOL> raise e <EOL> except setuputil . common . PermissionDeniedError as e : <EOL> logging . error ( "<STR_LIT>" + e . program + "<STR_LIT>" + e . instructions ) <EOL> raise e <EOL> except setuputil . common . BadDirectoryError as e : <EOL> logging . error ( "<STR_LIT>" + e . flag + "<STR_LIT>" <EOL> "<STR_LIT>" + e . directory + "<STR_LIT>" ) <EOL> raise e <EOL> def windows_init ( options ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> setup = setuputil . windows . WindowsSetup ( options ) <EOL> return setup <EOL> except setuputil . common . VersionUnsupportedError as e : <EOL> logging . error ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> raise e <EOL> except setuputil . common . VersionUnsupportedError as e : <EOL> logging . error ( "<STR_LIT>" + e . version + "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> raise e <EOL> except setuputil . common . BadDirectoryError as e : <EOL> logging . error ( "<STR_LIT>" + e . flag + "<STR_LIT>" <EOL> "<STR_LIT>" + e . directory + "<STR_LIT>" ) <EOL> raise e <EOL> return None <EOL> def windows_setup ( setup ) : <EOL> try : <EOL> setup . setup_all ( ) <EOL> except setuputil . common . PermissionDeniedError as e : <EOL> logging . error ( "<STR_LIT>" + e . program + "<STR_LIT>" <EOL> + e . instructions ) <EOL> raise e <EOL> except setuputil . common . FileDownloadError as e : <EOL> logging . error ( "<STR_LIT>" + e . link + "<STR_LIT>" <EOL> "<STR_LIT>" + e . instructions ) <EOL> raise e <EOL> except setuputil . common . InstallFailedError as e : <EOL> logging . error ( e . program + "<STR_LIT>" + e . link + <EOL> "<STR_LIT>" + <EOL> e . instructions ) <EOL> raise e <EOL> except setuputil . common . WebbrowserFailedError as e : <EOL> logging . error ( "<STR_LIT>" + e . pagename + "<STR_LIT>" + <EOL> e . link + "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> raise e <EOL> except setuputil . common . InstallInterruptError as e : <EOL> logging . error ( "<STR_LIT>" + e . program + "<STR_LIT>" + e . instructions ) <EOL> raise e <EOL> def mac_init ( options , skip_version_check = False ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> setup = setuputil . mac . MacSetup ( options , skip_version_check ) <EOL> return setup <EOL> except setuputil . common . VersionUnsupportedError as e : <EOL> logging . error ( "<STR_LIT>" + e . version + "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> raise e <EOL> except setuputil . common . VersionTooHighError as e : <EOL> logging . error ( "<STR_LIT>" + e . version + "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> if raw_input ( "<STR_LIT>" ) . lower ( ) . startswith ( "<STR_LIT:y>" ) : <EOL> return mac_init ( options , skip_version_check = True ) <EOL> else : <EOL> raise e <EOL> except setuputil . mac . VersionTooLowError as e : <EOL> logging . error ( "<STR_LIT>" + e . version + "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> if raw_input ( "<STR_LIT>" <EOL> "<STR_LIT>" ) . lower ( ) . startswith ( "<STR_LIT:y>" ) : <EOL> return mac_init ( options , skip_version_check = True ) <EOL> else : <EOL> raise e <EOL> except setuputil . common . BadDirectoryError as e : <EOL> logging . error ( "<STR_LIT>" + e . flag + "<STR_LIT>" <EOL> "<STR_LIT>" + e . directory + "<STR_LIT>" ) <EOL> raise e <EOL> return None <EOL> def mac_setup ( setup ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> setup . setup_all ( ) <EOL> return <EOL> except setuputil . common . InstallInterruptError as e : <EOL> logging . error ( "<STR_LIT>" + e . program + "<STR_LIT:.>" ) <EOL> raise e <EOL> except setuputil . common . InstallFailedError as e : <EOL> logging . error ( e . program + "<STR_LIT>" + e . link + <EOL> "<STR_LIT>" + <EOL> e . instructions ) <EOL> raise e <EOL> except setuputil . common . FileDownloadError as e : <EOL> logging . error ( "<STR_LIT>" + e . link + "<STR_LIT>" <EOL> "<STR_LIT>" + e . instructions ) <EOL> raise e <EOL> except setuputil . common . ExtractionError as e : <EOL> logging . error ( "<STR_LIT>" + e . filepath + "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> raise e <EOL> except setuputil . common . PermissionDeniedError as e : <EOL> logging . error ( e . program + "<STR_LIT>" + <EOL> e . instructions ) <EOL> raise e <EOL> except setuputil . common . CommandFailedError as e : <EOL> logging . error ( "<STR_LIT>" + e . command + "<STR_LIT:\n>" <EOL> "<STR_LIT>" + e . link + "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> raise e <EOL> except setuputil . common . UnknownFileTypeError as e : <EOL> logging . error ( "<STR_LIT>" + e . filetype + "<STR_LIT>" + <EOL> e . instructions ) <EOL> raise e <EOL> except setuputil . common . BadDirectoryError as e : <EOL> logging . error ( "<STR_LIT>" + e . flag + "<STR_LIT>" <EOL> "<STR_LIT>" + e . directory + "<STR_LIT>" ) <EOL> raise e <EOL> def android_init ( system , options ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> setup = setuputil . android . AndroidSetup ( system , options ) <EOL> return setup <EOL> except setuputil . common . SystemUnsupportedError as e : <EOL> logging . error ( "<STR_LIT>" + e . system + "<STR_LIT:.>" ) <EOL> raise e <EOL> except setuputil . common . BadDirectoryError as e : <EOL> logging . error ( "<STR_LIT>" + e . flag + "<STR_LIT>" <EOL> "<STR_LIT>" + e . directory + "<STR_LIT>" ) <EOL> raise e <EOL> return None <EOL> def android_setup ( setup ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> setup . setup_all ( ) <EOL> except setuputil . common . FileDownloadError as e : <EOL> logging . error ( "<STR_LIT>" + e . link + "<STR_LIT>" <EOL> "<STR_LIT>" + e . instructions ) <EOL> raise e <EOL> except setuputil . common . UnknownFileTypeError as e : <EOL> logging . error ( "<STR_LIT>" + e . filetype + "<STR_LIT>" + <EOL> e . instructions ) <EOL> raise e <EOL> except setuputil . common . CommandFailedError as e : <EOL> logging . error ( "<STR_LIT>" + e . command + "<STR_LIT:\n>" <EOL> "<STR_LIT>" + e . link + "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> raise e <EOL> def main ( ) : <EOL> if not say_hello ( ) : <EOL> return <NUM_LIT:0> <EOL> create_logger ( ) <EOL> options = create_option_parser ( ) <EOL> system = sys . platform <EOL> path_update = False <EOL> path = "<STR_LIT>" <EOL> if system . startswith ( "<STR_LIT>" ) : <EOL> linux_setup ( ) <EOL> system = setuputil . common . LINUX <EOL> elif system == "<STR_LIT:win32>" or system == "<STR_LIT>" : <EOL> w = windows_init ( options ) <EOL> windows_setup ( w ) <EOL> system = setuputil . common . WINDOWS <EOL> path_update = w . has_bash_changed ( ) <EOL> path = w . get_windows_path_update ( ) <EOL> elif sys . platform == "<STR_LIT>" : <EOL> m = mac_init ( options ) <EOL> mac_setup ( m ) <EOL> system = setuputil . common . MAC <EOL> path_update = m . has_bash_changed ( ) <EOL> else : <EOL> logging . error ( system + "<STR_LIT>" ) <EOL> return <NUM_LIT:1> <EOL> if not options . no_android : <EOL> a = android_init ( system , options ) <EOL> android_setup ( a ) <EOL> path_update = path_update or a . has_bash_changed ( ) <EOL> if system == setuputil . common . WINDOWS : <EOL> path = a . get_windows_path_update ( ) + os . pathsep + path <EOL> if path_update : <EOL> if system == setuputil . common . LINUX : <EOL> print ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> elif system == setuputil . common . MAC : <EOL> print ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> else : <EOL> setuputil . windows . update_windows_path ( path ) <EOL> print ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> return <NUM_LIT:0> <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> sys . exit ( main ( ) ) </s>
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> __all__ = [ "<STR_LIT>" ] <EOL> import BaseHTTPServer <EOL> from google3 . pyglib import flags as gflags <EOL> import logging <EOL> import socket <EOL> import sys <EOL> from optparse import OptionParser <EOL> from apiclient . oauth import RequestError <EOL> try : <EOL> from urlparse import parse_qsl <EOL> except ImportError : <EOL> from cgi import parse_qsl <EOL> FLAGS = gflags . FLAGS <EOL> gflags . DEFINE_boolean ( '<STR_LIT>' , True , <EOL> ( '<STR_LIT>' <EOL> '<STR_LIT>' ) ) <EOL> gflags . DEFINE_string ( '<STR_LIT>' , '<STR_LIT:localhost>' , <EOL> ( '<STR_LIT>' <EOL> '<STR_LIT>' ) ) <EOL> gflags . DEFINE_multi_int ( '<STR_LIT>' , [ <NUM_LIT> , <NUM_LIT> ] , <EOL> ( '<STR_LIT>' <EOL> '<STR_LIT>' ) ) <EOL> class ClientRedirectServer ( BaseHTTPServer . HTTPServer ) : <EOL> """<STR_LIT>""" <EOL> query_params = { } <EOL> class ClientRedirectHandler ( BaseHTTPServer . BaseHTTPRequestHandler ) : <EOL> """<STR_LIT>""" <EOL> def do_GET ( s ) : <EOL> """<STR_LIT>""" <EOL> s . send_response ( <NUM_LIT:200> ) <EOL> s . send_header ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> s . end_headers ( ) <EOL> query = s . path . split ( '<STR_LIT:?>' , <NUM_LIT:1> ) [ - <NUM_LIT:1> ] <EOL> query = dict ( parse_qsl ( query ) ) <EOL> s . server . query_params = query <EOL> s . wfile . write ( "<STR_LIT>" ) <EOL> s . wfile . write ( "<STR_LIT>" ) <EOL> s . wfile . write ( "<STR_LIT>" ) <EOL> def log_message ( self , format , * args ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def run ( flow , storage ) : <EOL> """<STR_LIT>""" <EOL> if FLAGS . auth_local_webserver : <EOL> success = False <EOL> port_number = <NUM_LIT:0> <EOL> for port in FLAGS . auth_host_port : <EOL> port_number = port <EOL> try : <EOL> httpd = BaseHTTPServer . HTTPServer ( ( FLAGS . auth_host_name , port ) , <EOL> ClientRedirectHandler ) <EOL> except socket . error , e : <EOL> pass <EOL> else : <EOL> success = True <EOL> break <EOL> FLAGS . auth_local_webserver = success <EOL> if FLAGS . auth_local_webserver : <EOL> oauth_callback = '<STR_LIT>' % ( FLAGS . auth_host_name , port_number ) <EOL> else : <EOL> oauth_callback = '<STR_LIT>' <EOL> authorize_url = flow . step1_get_authorize_url ( oauth_callback ) <EOL> print '<STR_LIT>' <EOL> print authorize_url <EOL> print <EOL> if FLAGS . auth_local_webserver : <EOL> print '<STR_LIT>' <EOL> print '<STR_LIT>' <EOL> print <EOL> if FLAGS . auth_local_webserver : <EOL> httpd . handle_request ( ) <EOL> if '<STR_LIT:error>' in httpd . query_params : <EOL> sys . exit ( '<STR_LIT>' ) <EOL> if '<STR_LIT>' in httpd . query_params : <EOL> code = httpd . query_params [ '<STR_LIT>' ] <EOL> else : <EOL> accepted = '<STR_LIT:n>' <EOL> while accepted . lower ( ) == '<STR_LIT:n>' : <EOL> accepted = raw_input ( '<STR_LIT>' ) <EOL> code = raw_input ( '<STR_LIT>' ) . strip ( ) <EOL> try : <EOL> credentials = flow . step2_exchange ( code ) <EOL> except RequestError : <EOL> sys . exit ( '<STR_LIT>' ) <EOL> storage . put ( credentials ) <EOL> credentials . set_store ( storage . put ) <EOL> print "<STR_LIT>" <EOL> return credentials </s>
<s> """<STR_LIT>""" <EOL> import argparse <EOL> import os <EOL> import sys <EOL> import unittest2 <EOL> def _ParseArgs ( argv ) : <EOL> """<STR_LIT>""" <EOL> argparser = argparse . ArgumentParser ( description = ( '<STR_LIT>' ) ) <EOL> argparser . add_argument ( '<STR_LIT>' , '<STR_LIT>' , <EOL> help = '<STR_LIT>' ) <EOL> argparser . add_argument ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' , default = False , <EOL> help = '<STR_LIT>' ) <EOL> return argparser . parse_args ( argv ) <EOL> def main ( argv ) : <EOL> args = _ParseArgs ( argv ) <EOL> file_pattern = '<STR_LIT>' if not args . test_file else args . test_file <EOL> suite = unittest2 . loader . TestLoader ( ) . discover ( <EOL> start_dir = os . path . join ( os . path . dirname ( __file__ ) , '<STR_LIT>' ) , <EOL> pattern = file_pattern ) <EOL> show_test_names = <NUM_LIT:2> if args . verbose else <NUM_LIT:1> <EOL> unittest2 . TextTestRunner ( verbosity = show_test_names ) . run ( suite ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> main ( sys . argv [ <NUM_LIT:1> : ] ) </s>
<s> """<STR_LIT>""" <EOL> import logging <EOL> import os <EOL> import tempfile <EOL> import time <EOL> APPINFO = <NUM_LIT> <EOL> APPWARNING = <NUM_LIT> <EOL> def GetLogFileName ( ) : <EOL> """<STR_LIT>""" <EOL> return os . path . join ( tempfile . gettempdir ( ) , '<STR_LIT>' ) <EOL> def SetupLogging ( verbose_flag ) : <EOL> """<STR_LIT>""" <EOL> logging . addLevelName ( APPINFO , '<STR_LIT>' ) <EOL> logging . addLevelName ( APPWARNING , '<STR_LIT>' ) <EOL> if verbose_flag : <EOL> logging_level = logging . DEBUG <EOL> print '<STR_LIT>' <EOL> else : <EOL> logging_level = APPINFO <EOL> logging . basicConfig ( level = logging_level , <EOL> format = '<STR_LIT>' , <EOL> datefmt = '<STR_LIT>' , <EOL> filename = GetLogFileName ( ) , <EOL> filemode = '<STR_LIT:a>' ) <EOL> console_handler = logging . StreamHandler ( ) <EOL> console_handler . setLevel ( logging_level ) <EOL> console_formatter = logging . Formatter ( '<STR_LIT>' ) <EOL> console_handler . setFormatter ( console_formatter ) <EOL> logger = logging . getLogger ( '<STR_LIT>' ) <EOL> logger . addHandler ( console_handler ) <EOL> def LogDebug ( msg ) : <EOL> """<STR_LIT>""" <EOL> logging . getLogger ( '<STR_LIT>' ) . debug ( msg ) <EOL> def LogInfo ( msg ) : <EOL> """<STR_LIT>""" <EOL> logging . getLogger ( '<STR_LIT>' ) . log ( APPINFO , msg ) <EOL> def LogWarning ( msg ) : <EOL> """<STR_LIT>""" <EOL> logging . getLogger ( '<STR_LIT>' ) . log ( APPWARNING , msg ) <EOL> def LogError ( msg , error_exception = None ) : <EOL> """<STR_LIT>""" <EOL> if error_exception : <EOL> logging . getLogger ( '<STR_LIT>' ) . error ( '<STR_LIT>' , msg , error_exception ) <EOL> else : <EOL> logging . getLogger ( '<STR_LIT>' ) . error ( msg ) <EOL> class Timer ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , log_tag = None , hide_timing = False ) : <EOL> """<STR_LIT>""" <EOL> self . _log_tag = log_tag <EOL> self . _hide_timing = hide_timing <EOL> def __enter__ ( self ) : <EOL> self . _start = time . time ( ) <EOL> return self <EOL> def __exit__ ( self , * args ) : <EOL> self . _end = time . time ( ) <EOL> self . secs = self . _end - self . _start <EOL> if not self . _hide_timing and self . _log_tag : <EOL> LogInfo ( '<STR_LIT>' % ( self . _log_tag , self . secs ) ) </s>
<s> """<STR_LIT>""" <EOL> from __future__ import print_function <EOL> __author__ = '<STR_LIT>' <EOL> from optparse import OptionParser <EOL> import os <EOL> import pprint <EOL> import sys <EOL> from googleapiclient . discovery import build <EOL> import httplib2 <EOL> from oauth2client . client import flow_from_clientsecrets <EOL> from oauth2client . file import Storage <EOL> from oauth2client . tools import run <EOL> CLIENT_SECRETS = '<STR_LIT>' <EOL> MISSING_CLIENT_SECRETS_MESSAGE = """<STR_LIT>""" % os . path . join ( os . path . dirname ( __file__ ) , CLIENT_SECRETS ) <EOL> def access_settings ( service , groupId , settings ) : <EOL> """<STR_LIT>""" <EOL> group = service . groups ( ) <EOL> g = group . get ( groupUniqueId = groupId ) . execute ( ) <EOL> print ( '<STR_LIT>' % g [ '<STR_LIT:name>' ] ) <EOL> pprint . pprint ( g ) <EOL> if not settings . keys ( ) : <EOL> print ( '<STR_LIT>' ) <EOL> return <EOL> body = { } <EOL> for key in settings . iterkeys ( ) : <EOL> if settings [ key ] is not None : <EOL> body [ key ] = settings [ key ] <EOL> g1 = group . update ( groupUniqueId = groupId , body = body ) . execute ( ) <EOL> print ( '<STR_LIT>' ) <EOL> pprint . pprint ( g1 ) <EOL> def main ( argv ) : <EOL> """<STR_LIT>""" <EOL> usage = '<STR_LIT>' <EOL> parser = OptionParser ( usage = usage ) <EOL> parser . add_option ( '<STR_LIT>' , <EOL> help = '<STR_LIT>' ) <EOL> parser . add_option ( '<STR_LIT>' , <EOL> help = '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> parser . add_option ( '<STR_LIT>' , <EOL> help = '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> parser . add_option ( '<STR_LIT>' , <EOL> help = '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> parser . add_option ( '<STR_LIT>' , <EOL> help = '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> parser . add_option ( '<STR_LIT>' , <EOL> help = '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> ( options , args ) = parser . parse_args ( ) <EOL> if options . groupId is None : <EOL> print ( '<STR_LIT>' ) <EOL> parser . print_help ( ) <EOL> return <EOL> settings = { } <EOL> if ( options . whoCanInvite or options . whoCanJoin or options . whoCanPostMessage <EOL> or options . whoCanPostMessage or options . whoCanViewMembership ) is None : <EOL> print ( '<STR_LIT>' ) <EOL> parser . print_help ( ) <EOL> else : <EOL> settings = { '<STR_LIT>' : options . whoCanInvite , <EOL> '<STR_LIT>' : options . whoCanJoin , <EOL> '<STR_LIT>' : options . whoCanPostMessage , <EOL> '<STR_LIT>' : options . whoCanViewGroup , <EOL> '<STR_LIT>' : options . whoCanViewMembership } <EOL> FLOW = flow_from_clientsecrets ( CLIENT_SECRETS , <EOL> scope = '<STR_LIT>' , <EOL> message = MISSING_CLIENT_SECRETS_MESSAGE ) <EOL> storage = Storage ( '<STR_LIT>' ) <EOL> credentials = storage . get ( ) <EOL> if credentials is None or credentials . invalid : <EOL> print ( '<STR_LIT>' ) <EOL> credentials = run ( FLOW , storage ) <EOL> http = httplib2 . Http ( ) <EOL> http = credentials . authorize ( http ) <EOL> service = build ( '<STR_LIT>' , '<STR_LIT>' , http = http ) <EOL> access_settings ( service = service , groupId = options . groupId , settings = settings ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> main ( sys . argv ) </s>
<s> """<STR_LIT>""" <EOL> import platform <EOL> import re <EOL> def NetshStaticIp ( interface , ip = u'<STR_LIT>' , subnet = u'<STR_LIT>' , <EOL> gw = u'<STR_LIT:127.0.0.1>' ) : <EOL> """<STR_LIT>""" <EOL> args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:address>' , <EOL> interface , '<STR_LIT>' , ip , subnet , gw , '<STR_LIT:1>' ] <EOL> res = client_utils_common . Execute ( '<STR_LIT>' , args , <EOL> time_limit = - <NUM_LIT:1> , bypass_whitelist = True ) <EOL> return res <EOL> def DisableInterfaces ( interface ) : <EOL> """<STR_LIT>""" <EOL> set_tested_versions = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> set_args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , interface , '<STR_LIT>' ] <EOL> host_version = platform . platform ( ) . lower ( ) <EOL> for version in set_tested_versions : <EOL> if host_version . find ( version ) != - <NUM_LIT:1> : <EOL> res = client_utils_common . Execute ( '<STR_LIT>' , set_args , <EOL> time_limit = - <NUM_LIT:1> , bypass_whitelist = True ) <EOL> return res <EOL> return ( '<STR_LIT>' , '<STR_LIT>' , <NUM_LIT> , '<STR_LIT>' ) <EOL> def GetEnabledInterfaces ( ) : <EOL> """<STR_LIT>""" <EOL> interfaces = [ ] <EOL> show_args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> res = client_utils_common . Execute ( '<STR_LIT>' , show_args , <EOL> time_limit = - <NUM_LIT:1> , bypass_whitelist = True ) <EOL> pattern = re . compile ( r'<STR_LIT>' ) <EOL> for line in res [ <NUM_LIT:0> ] . split ( '<STR_LIT:\r\n>' ) : <EOL> interface_info = pattern . split ( line ) <EOL> if '<STR_LIT>' in interface_info : <EOL> interfaces . extend ( interface_info [ - <NUM_LIT:1> : ] ) <EOL> return interfaces <EOL> def MsgUser ( msg ) : <EOL> """<STR_LIT>""" <EOL> msg_tested_versions = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> msg_args = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:*>' , '<STR_LIT>' ] <EOL> host_version = platform . platform ( ) . lower ( ) <EOL> if not msg : <EOL> return ( '<STR_LIT>' , '<STR_LIT>' , - <NUM_LIT:1> ) <EOL> else : <EOL> msg_args . extend ( [ msg ] ) <EOL> for version in msg_tested_versions : <EOL> if host_version . find ( version ) != - <NUM_LIT:1> : <EOL> res = client_utils_common . Execute ( '<STR_LIT>' , msg_args , <EOL> time_limit = - <NUM_LIT:1> , bypass_whitelist = True ) <EOL> return res <EOL> return ( '<STR_LIT>' , '<STR_LIT>' , - <NUM_LIT:1> ) <EOL> def main ( ) : <EOL> return_str = { } <EOL> MSG_STRING = ( '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> if '<STR_LIT>' in py_args : <EOL> return_str [ '<STR_LIT>' ] = MsgUser ( py_args [ '<STR_LIT>' ] ) <EOL> else : <EOL> return_str [ '<STR_LIT>' ] = MsgUser ( MSG_STRING ) <EOL> for interface in GetEnabledInterfaces ( ) : <EOL> if interface != '<STR_LIT>' or interface != '<STR_LIT>' : <EOL> return_str [ interface ] = DisableInterfaces ( interface ) <EOL> if return_str [ interface ] [ <NUM_LIT:2> ] == <NUM_LIT> : <EOL> if all ( [ key in py_args for key in [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ] ) : <EOL> return_str [ interface ] = NetshStaticIp ( interface , <EOL> py_args [ '<STR_LIT>' ] , <EOL> py_args [ '<STR_LIT>' ] , <EOL> py_args [ '<STR_LIT>' ] ) <EOL> else : <EOL> return_str [ interface ] = NetshStaticIp ( interface ) <EOL> magic_list = [ ] <EOL> for key in return_str : <EOL> stdout , stderr , exit_status , time_taken = return_str [ key ] <EOL> key_str = '<STR_LIT>' % ( key , <EOL> stdout . encode ( '<STR_LIT>' ) , <EOL> stderr . encode ( '<STR_LIT>' ) , <EOL> exit_status , <EOL> time_taken ) <EOL> magic_list . append ( key_str ) <EOL> magic_return_str = '<STR_LIT>' . join ( magic_list ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> main ( ) </s>
<s> """<STR_LIT>""" <EOL> import os <EOL> import StringIO <EOL> import psutil <EOL> from grr . client import comms <EOL> from grr . lib import config_lib <EOL> from grr . lib import flags <EOL> from grr . lib import rdfvalue <EOL> from grr . lib import stats <EOL> from grr . lib import test_lib <EOL> from grr . lib import utils <EOL> from grr . lib . rdfvalues import client as rdf_client <EOL> from grr . lib . rdfvalues import protodict as rdf_protodict <EOL> class ConfigActionTest ( test_lib . EmptyActionTest ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> super ( ConfigActionTest , self ) . setUp ( ) <EOL> self . config_stubber = test_lib . PreserveConfig ( ) <EOL> self . config_stubber . Start ( ) <EOL> def tearDown ( self ) : <EOL> super ( ConfigActionTest , self ) . tearDown ( ) <EOL> self . config_stubber . Stop ( ) <EOL> def testUpdateConfiguration ( self ) : <EOL> """<STR_LIT>""" <EOL> self . config_file = os . path . join ( self . temp_dir , "<STR_LIT>" ) <EOL> config_lib . CONFIG . SetWriteBack ( self . config_file ) <EOL> self . assertRaises ( IOError , open , self . config_file ) <EOL> location = [ "<STR_LIT>" , <EOL> "<STR_LIT>" ] <EOL> request = rdf_protodict . Dict ( ) <EOL> request [ "<STR_LIT>" ] = location <EOL> request [ "<STR_LIT>" ] = <NUM_LIT> <EOL> result = self . RunAction ( "<STR_LIT>" , request ) <EOL> self . assertEqual ( result , [ ] ) <EOL> self . assertEqual ( config_lib . CONFIG [ "<STR_LIT>" ] , <NUM_LIT> ) <EOL> data = open ( self . config_file ) . read ( ) <EOL> self . assertTrue ( "<STR_LIT>" . format ( "<STR_LIT:U+002C>" . join ( location ) ) in data ) <EOL> self . urls = [ ] <EOL> def FakeUrlOpen ( req , timeout = <NUM_LIT:10> ) : <EOL> _ = timeout <EOL> self . urls . append ( req . get_full_url ( ) ) <EOL> return StringIO . StringIO ( ) <EOL> with utils . Stubber ( comms . urllib2 , "<STR_LIT>" , FakeUrlOpen ) : <EOL> client_context = comms . GRRHTTPClient ( worker = MockClientWorker ) <EOL> client_context . MakeRequest ( "<STR_LIT>" ) <EOL> self . assertTrue ( location [ <NUM_LIT:0> ] in self . urls [ <NUM_LIT:0> ] ) <EOL> def testUpdateConfigBlacklist ( self ) : <EOL> """<STR_LIT>""" <EOL> with test_lib . ConfigOverrider ( { <EOL> "<STR_LIT>" : [ "<STR_LIT>" ] , <EOL> "<STR_LIT>" : <NUM_LIT:1> } ) : <EOL> location = [ "<STR_LIT>" ] <EOL> request = rdf_protodict . Dict ( ) <EOL> request [ "<STR_LIT>" ] = location <EOL> request [ "<STR_LIT>" ] = <NUM_LIT:10> <EOL> self . RunAction ( "<STR_LIT>" , request ) <EOL> self . assertEqual ( config_lib . CONFIG [ "<STR_LIT>" ] , location ) <EOL> self . assertEqual ( config_lib . CONFIG [ "<STR_LIT>" ] , <NUM_LIT:1> ) <EOL> def testGetConfig ( self ) : <EOL> """<STR_LIT>""" <EOL> location = [ "<STR_LIT>" ] <EOL> request = rdf_protodict . Dict ( ) <EOL> request [ "<STR_LIT>" ] = location <EOL> request [ "<STR_LIT>" ] = <NUM_LIT> <EOL> self . RunAction ( "<STR_LIT>" , request ) <EOL> self . RunAction ( "<STR_LIT>" ) <EOL> self . assertEqual ( config_lib . CONFIG [ "<STR_LIT>" ] , <NUM_LIT> ) <EOL> self . assertEqual ( config_lib . CONFIG [ "<STR_LIT>" ] , location ) <EOL> class MockStatsCollector ( object ) : <EOL> """<STR_LIT>""" <EOL> cpu_samples = [ ( rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT:100> ) , <EOL> <NUM_LIT:0.1> , <NUM_LIT:0.1> , <NUM_LIT> ) , <EOL> ( rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) , <EOL> <NUM_LIT:0.1> , <NUM_LIT> , <NUM_LIT> ) , <EOL> ( rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) , <EOL> <NUM_LIT:0.1> , <NUM_LIT> , <NUM_LIT> ) ] <EOL> io_samples = [ ( rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT:100> ) , <NUM_LIT:100> , <NUM_LIT:100> ) , <EOL> ( rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) , <NUM_LIT:200> , <NUM_LIT:200> ) , <EOL> ( rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) , <NUM_LIT> , <NUM_LIT> ) ] <EOL> class MockClientWorker ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> self . stats_collector = MockStatsCollector ( ) <EOL> class GetClientStatsActionTest ( test_lib . EmptyActionTest ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> super ( GetClientStatsActionTest , self ) . setUp ( ) <EOL> self . old_boot_time = psutil . boot_time <EOL> psutil . boot_time = lambda : <NUM_LIT:100> <EOL> def tearDown ( self ) : <EOL> super ( GetClientStatsActionTest , self ) . tearDown ( ) <EOL> psutil . boot_time = self . old_boot_time <EOL> def testReturnsAllDataByDefault ( self ) : <EOL> """<STR_LIT>""" <EOL> stats . STATS . RegisterCounterMetric ( "<STR_LIT>" ) <EOL> stats . STATS . IncrementCounter ( "<STR_LIT>" , <NUM_LIT> ) <EOL> stats . STATS . RegisterCounterMetric ( "<STR_LIT>" ) <EOL> stats . STATS . IncrementCounter ( "<STR_LIT>" , <NUM_LIT> ) <EOL> results = self . RunAction ( "<STR_LIT>" , grr_worker = MockClientWorker ( ) , <EOL> arg = rdf_client . GetClientStatsRequest ( ) ) <EOL> response = results [ <NUM_LIT:0> ] <EOL> self . assertEqual ( response . bytes_received , <NUM_LIT> ) <EOL> self . assertEqual ( response . bytes_sent , <NUM_LIT> ) <EOL> self . assertEqual ( len ( response . cpu_samples ) , <NUM_LIT:3> ) <EOL> for i in range ( <NUM_LIT:3> ) : <EOL> self . assertEqual ( response . cpu_samples [ i ] . timestamp , <EOL> rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <EOL> <NUM_LIT:100> + i * <NUM_LIT:10> ) ) <EOL> self . assertAlmostEqual ( response . cpu_samples [ i ] . user_cpu_time , <NUM_LIT:0.1> ) <EOL> self . assertAlmostEqual ( response . cpu_samples [ i ] . system_cpu_time , <EOL> <NUM_LIT:0.1> * ( i + <NUM_LIT:1> ) ) <EOL> self . assertAlmostEqual ( response . cpu_samples [ i ] . cpu_percent , <NUM_LIT> + <NUM_LIT:5> * i ) <EOL> self . assertEqual ( len ( response . io_samples ) , <NUM_LIT:3> ) <EOL> for i in range ( <NUM_LIT:3> ) : <EOL> self . assertEqual ( response . io_samples [ i ] . timestamp , <EOL> rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <EOL> <NUM_LIT:100> + i * <NUM_LIT:10> ) ) <EOL> self . assertEqual ( response . io_samples [ i ] . read_bytes , <NUM_LIT:100> * ( i + <NUM_LIT:1> ) ) <EOL> self . assertEqual ( response . io_samples [ i ] . write_bytes , <NUM_LIT:100> * ( i + <NUM_LIT:1> ) ) <EOL> self . assertEqual ( response . boot_time , long ( <NUM_LIT:100> * <NUM_LIT> ) ) <EOL> def testFiltersDataPointsByStartTime ( self ) : <EOL> start_time = rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) <EOL> results = self . RunAction ( <EOL> "<STR_LIT>" , grr_worker = MockClientWorker ( ) , <EOL> arg = rdf_client . GetClientStatsRequest ( start_time = start_time ) ) <EOL> response = results [ <NUM_LIT:0> ] <EOL> self . assertEqual ( len ( response . cpu_samples ) , <NUM_LIT:1> ) <EOL> self . assertEqual ( response . cpu_samples [ <NUM_LIT:0> ] . timestamp , <EOL> rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) ) <EOL> self . assertEqual ( len ( response . io_samples ) , <NUM_LIT:1> ) <EOL> self . assertEqual ( response . io_samples [ <NUM_LIT:0> ] . timestamp , <EOL> rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) ) <EOL> def testFiltersDataPointsByEndTime ( self ) : <EOL> end_time = rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) <EOL> results = self . RunAction ( <EOL> "<STR_LIT>" , grr_worker = MockClientWorker ( ) , <EOL> arg = rdf_client . GetClientStatsRequest ( end_time = end_time ) ) <EOL> response = results [ <NUM_LIT:0> ] <EOL> self . assertEqual ( len ( response . cpu_samples ) , <NUM_LIT:1> ) <EOL> self . assertEqual ( response . cpu_samples [ <NUM_LIT:0> ] . timestamp , <EOL> rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT:100> ) ) <EOL> self . assertEqual ( len ( response . io_samples ) , <NUM_LIT:1> ) <EOL> self . assertEqual ( response . io_samples [ <NUM_LIT:0> ] . timestamp , <EOL> rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT:100> ) ) <EOL> def testFiltersDataPointsByStartAndEndTimes ( self ) : <EOL> start_time = rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) <EOL> end_time = rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) <EOL> results = self . RunAction ( <EOL> "<STR_LIT>" , grr_worker = MockClientWorker ( ) , <EOL> arg = rdf_client . GetClientStatsRequest ( start_time = start_time , <EOL> end_time = end_time ) ) <EOL> response = results [ <NUM_LIT:0> ] <EOL> self . assertEqual ( len ( response . cpu_samples ) , <NUM_LIT:1> ) <EOL> self . assertEqual ( response . cpu_samples [ <NUM_LIT:0> ] . timestamp , <EOL> rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) ) <EOL> self . assertEqual ( len ( response . io_samples ) , <NUM_LIT:1> ) <EOL> self . assertEqual ( response . io_samples [ <NUM_LIT:0> ] . timestamp , <EOL> rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) ) <EOL> def main ( argv ) : <EOL> test_lib . main ( argv ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> flags . StartMain ( main ) </s>
<s> """<STR_LIT>""" <EOL> import sys <EOL> if sys . platform == "<STR_LIT:win32>" : <EOL> from grr . client import client_utils_windows <EOL> FindProxies = client_utils_windows . WinFindProxies <EOL> GetRawDevice = client_utils_windows . WinGetRawDevice <EOL> CanonicalPathToLocalPath = client_utils_windows . CanonicalPathToLocalPath <EOL> LocalPathToCanonicalPath = client_utils_windows . LocalPathToCanonicalPath <EOL> NannyController = client_utils_windows . NannyController <EOL> KeepAlive = client_utils_windows . KeepAlive <EOL> WinChmod = client_utils_windows . WinChmod <EOL> elif sys . platform == "<STR_LIT>" : <EOL> from grr . client import client_utils_osx <EOL> from grr . client import client_utils_linux <EOL> FindProxies = client_utils_osx . OSXFindProxies <EOL> GetRawDevice = client_utils_osx . OSXGetRawDevice <EOL> CanonicalPathToLocalPath = client_utils_linux . CanonicalPathToLocalPath <EOL> LocalPathToCanonicalPath = client_utils_linux . LocalPathToCanonicalPath <EOL> NannyController = client_utils_linux . NannyController <EOL> KeepAlive = client_utils_osx . KeepAlive <EOL> else : <EOL> from grr . client import client_utils_linux <EOL> FindProxies = client_utils_linux . LinFindProxies <EOL> GetRawDevice = client_utils_linux . LinGetRawDevice <EOL> CanonicalPathToLocalPath = client_utils_linux . CanonicalPathToLocalPath <EOL> LocalPathToCanonicalPath = client_utils_linux . LocalPathToCanonicalPath <EOL> NannyController = client_utils_linux . NannyController <EOL> KeepAlive = client_utils_linux . KeepAlive </s>
<s> """<STR_LIT>""" <EOL> import ctypes <EOL> import mox <EOL> from grr . client . osx import objc <EOL> from grr . lib import flags <EOL> from grr . lib import test_lib <EOL> class ObjcTest ( test_lib . GRRBaseTest ) : <EOL> def setUp ( self ) : <EOL> super ( ObjcTest , self ) . setUp ( ) <EOL> self . mox = mox . Mox ( ) <EOL> self . mox . StubOutWithMock ( objc . ctypes . util , '<STR_LIT>' ) <EOL> self . mox . StubOutWithMock ( objc . ctypes . cdll , '<STR_LIT>' ) <EOL> self . dll = self . mox . CreateMockAnything ( ) <EOL> self . function = self . mox . CreateMockAnything ( ) <EOL> self . dll . CFMockFunc = self . function <EOL> self . argtypes = [ ctypes . c_void_p , ctypes . c_void_p ] <EOL> self . restype = ctypes . c_void_p <EOL> self . cftable = [ <EOL> ( '<STR_LIT>' , <EOL> self . argtypes , <EOL> self . restype ) <EOL> ] <EOL> def tearDown ( self ) : <EOL> self . mox . UnsetStubs ( ) <EOL> def testSetCTypesForLibraryLibNotFound ( self ) : <EOL> objc . ctypes . util . find_library ( '<STR_LIT>' ) . AndReturn ( None ) <EOL> self . mox . ReplayAll ( ) <EOL> self . assertRaises ( objc . ErrorLibNotFound , objc . SetCTypesForLibrary , <EOL> '<STR_LIT>' , self . cftable ) <EOL> self . mox . VerifyAll ( ) <EOL> def testSetCTypesForLibrary ( self ) : <EOL> objc . ctypes . util . find_library ( '<STR_LIT>' ) . AndReturn ( '<STR_LIT>' ) <EOL> objc . ctypes . cdll . LoadLibrary ( '<STR_LIT>' ) . AndReturn ( self . dll ) <EOL> self . mox . ReplayAll ( ) <EOL> dll = objc . SetCTypesForLibrary ( '<STR_LIT>' , self . cftable ) <EOL> self . assertEqual ( dll . CFMockFunc . argtypes , self . argtypes ) <EOL> self . assertEqual ( dll . CFMockFunc . restype , self . restype ) <EOL> self . mox . VerifyAll ( ) <EOL> def main ( argv ) : <EOL> test_lib . main ( argv ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> flags . StartMain ( main ) </s>
<s> """<STR_LIT>""" <EOL> from setuptools import setup <EOL> setup ( <EOL> name = "<STR_LIT>" , <EOL> version = "<STR_LIT>" , <EOL> description = "<STR_LIT>" , <EOL> license = "<STR_LIT>" , <EOL> url = "<STR_LIT>" , <EOL> entry_points = { <EOL> "<STR_LIT>" : [ <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> ] <EOL> } , <EOL> install_requires = [ <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> ] , <EOL> extras_require = { <EOL> "<STR_LIT>" : [ <EOL> "<STR_LIT>" <EOL> ] , <EOL> } <EOL> ) </s>
<s> """<STR_LIT>""" <EOL> import itertools <EOL> import re <EOL> import sys <EOL> from grr . gui import api_value_renderers <EOL> from grr . lib import aff4 <EOL> from grr . lib import registry <EOL> from grr . lib import utils <EOL> from grr . lib . rdfvalues import client as rdf_client <EOL> from grr . lib . rdfvalues import structs as rdf_structs <EOL> from grr . proto import api_pb2 <EOL> class ApiAFF4ObjectRendererBase ( object ) : <EOL> """<STR_LIT>""" <EOL> __metaclass__ = registry . MetaclassRegistry <EOL> aff4_type = None <EOL> args_type = None <EOL> class ApiAFF4ObjectRendererArgs ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = api_pb2 . ApiAFF4ObjectRendererArgs <EOL> class ApiAFF4ObjectRenderer ( ApiAFF4ObjectRendererBase ) : <EOL> aff4_type = "<STR_LIT>" <EOL> args_type = ApiAFF4ObjectRendererArgs <EOL> def __init__ ( self ) : <EOL> if self . aff4_type is None : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> def RenderObject ( self , aff4_object , args ) : <EOL> """<STR_LIT>""" <EOL> object_attributes = aff4_object . synced_attributes . copy ( ) <EOL> for key , value in aff4_object . new_attributes . items ( ) : <EOL> object_attributes [ key ] = value <EOL> attributes = { } <EOL> for attribute , values in object_attributes . items ( ) : <EOL> attributes [ attribute . predicate ] = [ ] <EOL> for value in values : <EOL> if hasattr ( value , "<STR_LIT>" ) : <EOL> value = value . ToRDFValue ( ) <EOL> if aff4_object . age_policy != aff4 . NEWEST_TIME : <EOL> attributes [ attribute . predicate ] . append ( <EOL> api_value_renderers . RenderValue ( value , <EOL> limit_lists = args . limit_lists ) ) <EOL> else : <EOL> attributes [ attribute . predicate ] = api_value_renderers . RenderValue ( <EOL> value , limit_lists = args . limit_lists ) <EOL> return dict ( aff4_class = aff4_object . __class__ . __name__ , <EOL> urn = utils . SmartUnicode ( aff4_object . urn ) , <EOL> attributes = attributes , <EOL> age_policy = aff4_object . age_policy ) <EOL> class ApiRDFValueCollectionRendererArgs ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = api_pb2 . ApiRDFValueCollectionRendererArgs <EOL> class ApiRDFValueCollectionRenderer ( ApiAFF4ObjectRendererBase ) : <EOL> """<STR_LIT>""" <EOL> aff4_type = "<STR_LIT>" <EOL> args_type = ApiRDFValueCollectionRendererArgs <EOL> def RenderObject ( self , aff4_object , args ) : <EOL> """<STR_LIT>""" <EOL> if args . filter : <EOL> index = <NUM_LIT:0> <EOL> items = [ ] <EOL> for item in aff4_object . GenerateItems ( ) : <EOL> serialized_item = item . SerializeToString ( ) <EOL> if re . search ( re . escape ( args . filter ) , serialized_item , re . I ) : <EOL> if index >= args . offset : <EOL> items . append ( item ) <EOL> index += <NUM_LIT:1> <EOL> if args . count and len ( items ) >= args . count : <EOL> break <EOL> else : <EOL> items = list ( itertools . islice ( <EOL> aff4_object . GenerateItems ( offset = args . offset ) , <EOL> args . count or sys . maxint ) ) <EOL> result = { } <EOL> result [ "<STR_LIT>" ] = args . offset <EOL> result [ "<STR_LIT:count>" ] = len ( items ) <EOL> result [ "<STR_LIT>" ] = [ api_value_renderers . RenderValue ( <EOL> i , limit_lists = args . items_limit_lists ) for i in items ] <EOL> if args . with_total_count : <EOL> if hasattr ( aff4_object , "<STR_LIT>" ) : <EOL> total_count = aff4_object . CalculateLength ( ) <EOL> else : <EOL> total_count = len ( aff4_object ) <EOL> result [ "<STR_LIT>" ] = total_count <EOL> return result <EOL> class ApiIndexedSequentialCollectionRenderer ( ApiRDFValueCollectionRenderer ) : <EOL> aff4_type = "<STR_LIT>" <EOL> class VFSGRRClientApiObjectRenderer ( ApiAFF4ObjectRendererBase ) : <EOL> """<STR_LIT>""" <EOL> aff4_type = "<STR_LIT>" <EOL> def _GetDiskWarnings ( self , client ) : <EOL> """<STR_LIT>""" <EOL> warnings = [ ] <EOL> volumes = client . Get ( client . Schema . VOLUMES ) <EOL> exclude_windows_types = [ <EOL> rdf_client . WindowsVolume . WindowsDriveTypeEnum . DRIVE_CDROM ] <EOL> if volumes : <EOL> for volume in volumes : <EOL> if volume . windowsvolume . drive_type not in exclude_windows_types : <EOL> freespace = volume . FreeSpacePercent ( ) <EOL> if freespace < <NUM_LIT> : <EOL> warnings . append ( [ volume . Name ( ) , freespace ] ) <EOL> return warnings <EOL> def RenderObject ( self , client , unused_args ) : <EOL> """<STR_LIT>""" <EOL> return dict ( disk_warnings = self . _GetDiskWarnings ( client ) , <EOL> summary = api_value_renderers . RenderValue ( client . GetSummary ( ) ) ) <EOL> RENDERERS_CACHE = { } <EOL> def RenderAFF4Object ( obj , args = None ) : <EOL> """<STR_LIT>""" <EOL> args = args or [ ] <EOL> cache_key = obj . __class__ . __name__ <EOL> try : <EOL> candidates = RENDERERS_CACHE [ cache_key ] <EOL> except KeyError : <EOL> candidates = [ ] <EOL> for candidate in ApiAFF4ObjectRendererBase . classes . values ( ) : <EOL> if candidate . aff4_type : <EOL> candidate_class = aff4 . AFF4Object . classes [ candidate . aff4_type ] <EOL> else : <EOL> continue <EOL> if aff4 . issubclass ( obj . __class__ , candidate_class ) : <EOL> candidates . append ( candidate ) <EOL> if not candidates : <EOL> raise RuntimeError ( "<STR_LIT>" % <EOL> obj . __class__ . __name__ ) <EOL> candidates = sorted ( candidates , key = lambda cls : cls . __name__ ) <EOL> RENDERERS_CACHE [ cache_key ] = candidates <EOL> result = { } <EOL> for candidate in candidates : <EOL> api_renderer_args = None <EOL> for arg in args : <EOL> if candidate . args_type and isinstance ( arg , candidate . args_type ) : <EOL> api_renderer_args = arg <EOL> if api_renderer_args is None and candidate . args_type is not None : <EOL> api_renderer_args = candidate . args_type ( ) <EOL> api_renderer = candidate ( ) <EOL> renderer_output = api_renderer . RenderObject ( obj , api_renderer_args ) <EOL> for k , v in renderer_output . items ( ) : <EOL> result [ k ] = v <EOL> return result </s>
<s> """<STR_LIT>""" <EOL> from grr . gui import api_test_lib <EOL> from grr . gui . api_plugins import aff4 as aff4_plugin <EOL> from grr . lib import aff4 <EOL> from grr . lib import flags <EOL> from grr . lib import test_lib <EOL> class ApiGetAff4ObjectHandlerTest ( test_lib . GRRBaseTest ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> super ( ApiGetAff4ObjectHandlerTest , self ) . setUp ( ) <EOL> self . handler = aff4_plugin . ApiGetAff4ObjectHandler ( ) <EOL> def testRendersAff4ObjectWithGivenPath ( self ) : <EOL> with test_lib . FakeTime ( <NUM_LIT> ) : <EOL> with aff4 . FACTORY . Create ( "<STR_LIT>" , "<STR_LIT>" , <EOL> token = self . token ) as _ : <EOL> pass <EOL> result = self . handler . Render ( <EOL> aff4_plugin . ApiGetAff4ObjectArgs ( aff4_path = "<STR_LIT>" ) , <EOL> token = self . token ) <EOL> self . assertEqual ( result [ "<STR_LIT>" ] , "<STR_LIT>" ) <EOL> self . assertEqual ( result [ "<STR_LIT>" ] , "<STR_LIT>" ) <EOL> self . assertEqual ( result [ "<STR_LIT>" ] , "<STR_LIT>" ) <EOL> self . assertEqual ( result [ "<STR_LIT>" ] [ "<STR_LIT>" ] , { <EOL> "<STR_LIT:value>" : <NUM_LIT> , <EOL> "<STR_LIT:type>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : <NUM_LIT> } ) <EOL> class ApiGetAff4ObjectHandlerRegressionTest ( <EOL> api_test_lib . ApiCallHandlerRegressionTest ) : <EOL> handler = "<STR_LIT>" <EOL> def Run ( self ) : <EOL> with test_lib . FakeTime ( <NUM_LIT> ) : <EOL> with aff4 . FACTORY . Create ( "<STR_LIT>" , "<STR_LIT>" , <EOL> mode = "<STR_LIT>" , token = self . token ) as sample_object : <EOL> sample_object . AddLabels ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> self . Check ( "<STR_LIT:GET>" , "<STR_LIT>" ) <EOL> class ApiGetAff4IndexHandlerTest ( test_lib . GRRBaseTest ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> super ( ApiGetAff4IndexHandlerTest , self ) . setUp ( ) <EOL> self . handler = aff4_plugin . ApiGetAff4IndexHandler ( ) <EOL> def testReturnsChildrenListWithTimestamps ( self ) : <EOL> with test_lib . FakeTime ( <NUM_LIT> ) : <EOL> with aff4 . FACTORY . Create ( "<STR_LIT>" , "<STR_LIT>" , <EOL> token = self . token ) as _ : <EOL> pass <EOL> with test_lib . FakeTime ( <NUM_LIT> ) : <EOL> with aff4 . FACTORY . Create ( "<STR_LIT>" , "<STR_LIT>" , <EOL> token = self . token ) as _ : <EOL> pass <EOL> result = self . handler . Render ( <EOL> aff4_plugin . ApiGetAff4IndexArgs ( aff4_path = "<STR_LIT>" ) , <EOL> token = self . token ) <EOL> result = sorted ( result , key = lambda x : x [ <NUM_LIT:0> ] ) <EOL> self . assertEqual ( result , <EOL> [ [ "<STR_LIT>" , <NUM_LIT> ] , <EOL> [ "<STR_LIT>" , <NUM_LIT> ] ] ) <EOL> class ApiGetAff4IndexHandlerRegressionTest ( <EOL> api_test_lib . ApiCallHandlerRegressionTest ) : <EOL> handler = "<STR_LIT>" <EOL> def Run ( self ) : <EOL> with test_lib . FakeTime ( <NUM_LIT> ) : <EOL> with aff4 . FACTORY . Create ( "<STR_LIT>" , "<STR_LIT>" , token = self . token ) : <EOL> pass <EOL> with test_lib . FakeTime ( <NUM_LIT> ) : <EOL> with aff4 . FACTORY . Create ( "<STR_LIT>" , "<STR_LIT>" , token = self . token ) : <EOL> pass <EOL> with test_lib . FakeTime ( <NUM_LIT> ) : <EOL> with aff4 . FACTORY . Create ( "<STR_LIT>" , "<STR_LIT>" , token = self . token ) : <EOL> pass <EOL> self . Check ( "<STR_LIT:GET>" , "<STR_LIT>" ) <EOL> def main ( argv ) : <EOL> test_lib . main ( argv ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> flags . StartMain ( main ) </s>
<s> """<STR_LIT>""" <EOL> from grr . gui import api_call_robot_router <EOL> from grr . gui import api_call_router_with_approval_checks <EOL> from grr . gui import api_call_router_without_checks <EOL> from grr . gui import api_plugins <EOL> from grr . gui import local <EOL> from grr . gui import plugins <EOL> from grr . gui import renderers <EOL> from grr . gui import urls <EOL> from grr . gui import views </s>
<s> """<STR_LIT>""" <EOL> import os <EOL> from grr . gui import api_call_handler_utils <EOL> from grr . gui import runtests_test <EOL> from grr . lib import action_mocks <EOL> from grr . lib import flags <EOL> from grr . lib import flow <EOL> from grr . lib import output_plugin <EOL> from grr . lib import test_lib <EOL> from grr . lib import utils <EOL> from grr . lib . flows . general import filesystem as flows_filesystem <EOL> from grr . lib . flows . general import processes as flows_processes <EOL> from grr . lib . flows . general import transfer as flows_transfer <EOL> from grr . lib . flows . general import webhistory as flows_webhistory <EOL> from grr . lib . output_plugins import email_plugin <EOL> from grr . lib . rdfvalues import client as rdf_client <EOL> from grr . lib . rdfvalues import crypto as rdf_crypto <EOL> from grr . lib . rdfvalues import paths as rdf_paths <EOL> from grr . lib . rdfvalues import structs as rdf_structs <EOL> from grr . proto import tests_pb2 <EOL> class RecursiveTestFlowArgs ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = tests_pb2 . RecursiveTestFlowArgs <EOL> class RecursiveTestFlow ( flow . GRRFlow ) : <EOL> """<STR_LIT>""" <EOL> args_type = RecursiveTestFlowArgs <EOL> category = "<STR_LIT>" <EOL> @ flow . StateHandler ( next_state = "<STR_LIT>" ) <EOL> def Start ( self ) : <EOL> if self . args . depth < <NUM_LIT:2> : <EOL> for i in range ( <NUM_LIT:2> ) : <EOL> self . Log ( "<STR_LIT>" , i ) <EOL> self . CallFlow ( RecursiveTestFlow . __name__ , depth = self . args . depth + <NUM_LIT:1> , <EOL> next_state = "<STR_LIT>" ) <EOL> class FlowWithOneLogStatement ( flow . GRRFlow ) : <EOL> """<STR_LIT>""" <EOL> @ flow . StateHandler ( next_state = "<STR_LIT>" ) <EOL> def Start ( self ) : <EOL> self . Log ( "<STR_LIT>" ) <EOL> class FlowWithOneStatEntryResult ( flow . GRRFlow ) : <EOL> """<STR_LIT>""" <EOL> @ flow . StateHandler ( ) <EOL> def Start ( self ) : <EOL> self . SendReply ( rdf_client . StatEntry ( aff4path = "<STR_LIT>" ) ) <EOL> class FlowWithOneNetworkConnectionResult ( flow . GRRFlow ) : <EOL> """<STR_LIT>""" <EOL> @ flow . StateHandler ( ) <EOL> def Start ( self ) : <EOL> self . SendReply ( rdf_client . NetworkConnection ( pid = <NUM_LIT> ) ) <EOL> class FlowWithOneHashEntryResult ( flow . GRRFlow ) : <EOL> """<STR_LIT>""" <EOL> @ flow . StateHandler ( ) <EOL> def Start ( self ) : <EOL> hash_result = rdf_crypto . Hash ( <EOL> sha256 = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) . decode ( "<STR_LIT>" ) , <EOL> sha1 = "<STR_LIT>" . decode ( "<STR_LIT>" ) , <EOL> md5 = "<STR_LIT>" . decode ( "<STR_LIT>" ) ) <EOL> self . SendReply ( hash_result ) <EOL> class TestFlowManagement ( test_lib . GRRSeleniumTest ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> super ( TestFlowManagement , self ) . setUp ( ) <EOL> with self . ACLChecksDisabled ( ) : <EOL> self . client_id = rdf_client . ClientURN ( "<STR_LIT>" ) <EOL> self . RequestAndGrantClientApproval ( self . client_id ) <EOL> self . action_mock = action_mocks . ActionMock ( <EOL> "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) <EOL> def testFlowManagement ( self ) : <EOL> """<STR_LIT>""" <EOL> self . Open ( "<STR_LIT:/>" ) <EOL> self . Type ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntilEqual ( u"<STR_LIT>" , <EOL> self . GetText , "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" + flows_processes . ListProcesses . __name__ ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , flows_webhistory . FirefoxHistory . __name__ ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , <EOL> flows_filesystem . UpdateSparseImageChunks . __name__ ) <EOL> self . Click ( "<STR_LIT>" + flows_transfer . GetFile . __name__ ) <EOL> self . Select ( "<STR_LIT>" , <EOL> "<STR_LIT>" ) <EOL> self . Type ( "<STR_LIT>" , <EOL> u"<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> with self . ACLChecksDisabled ( ) : <EOL> flow . GRRFlow . StartFlow ( <EOL> client_id = "<STR_LIT>" , <EOL> flow_name = RecursiveTestFlow . __name__ , <EOL> token = self . token ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntilEqual ( "<STR_LIT>" , self . GetText , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntilEqual ( "<STR_LIT>" , self . GetText , <EOL> "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntilEqual ( "<STR_LIT>" , self . GetText , <EOL> "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsElementPresent , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsElementPresent , <EOL> "<STR_LIT>" ) <EOL> def testLogsCanBeOpenedByClickingOnLogsTab ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> "<STR_LIT>" , self . action_mock , <EOL> client_id = self . client_id , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> def testLogTimestampsArePresentedInUTC ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> with test_lib . FakeTime ( <NUM_LIT> ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> "<STR_LIT>" , self . action_mock , <EOL> client_id = self . client_id , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> def testResultsAreDisplayedInResultsTab ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> "<STR_LIT>" , self . action_mock , <EOL> client_id = self . client_id , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> def testEmptyTableIsDisplayedInResultsWhenNoResults ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> flow . GRRFlow . StartFlow ( flow_name = "<STR_LIT>" , <EOL> client_id = self . client_id , sync = False , <EOL> token = self . token ) <EOL> self . Open ( "<STR_LIT>" + self . client_id . Basename ( ) ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsElementPresent , "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> def testExportTabIsEnabledForStatEntryResults ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> "<STR_LIT>" , self . action_mock , <EOL> client_id = self . client_id , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( <EOL> self . IsTextPresent , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> def testHashesAreDisplayedCorrectly ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> "<STR_LIT>" , self . action_mock , <EOL> client_id = self . client_id , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , <EOL> "<STR_LIT>" ) <EOL> def testExportCommandIsNotDisabledWhenNoResults ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> RecursiveTestFlow . __name__ , self . action_mock , <EOL> client_id = self . client_id , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsElementPresent , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntilNot ( self . IsTextPresent , "<STR_LIT>" ) <EOL> def testExportCommandIsNotShownForNonFileResults ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> "<STR_LIT>" , self . action_mock , <EOL> client_id = self . client_id , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsElementPresent , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntilNot ( self . IsTextPresent , "<STR_LIT>" ) <EOL> def testCancelFlowWorksCorrectly ( self ) : <EOL> """<STR_LIT>""" <EOL> flow . GRRFlow . StartFlow ( client_id = self . client_id , <EOL> flow_name = RecursiveTestFlow . __name__ , <EOL> token = self . token ) <EOL> self . Open ( "<STR_LIT:/>" ) <EOL> self . Type ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntilEqual ( u"<STR_LIT>" , <EOL> self . GetText , "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> def testGlobalFlowManagement ( self ) : <EOL> """<STR_LIT>""" <EOL> with self . ACLChecksDisabled ( ) : <EOL> self . CreateAdminUser ( "<STR_LIT:test>" ) <EOL> self . Open ( "<STR_LIT:/>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . assertEqual ( "<STR_LIT>" , self . GetText ( "<STR_LIT>" ) ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> def testDoesNotShowGenerateArchiveButtonForNonExportableRDFValues ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> "<STR_LIT>" , self . action_mock , <EOL> client_id = self . client_id , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> self . WaitUntilNot ( self . IsTextPresent , <EOL> "<STR_LIT>" ) <EOL> def testDoesNotShowGenerateArchiveButtonWhenResultsCollectionIsEmpty ( self ) : <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> RecursiveTestFlow . __name__ , self . action_mock , <EOL> client_id = self . client_id , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> self . WaitUntilNot ( self . IsTextPresent , <EOL> "<STR_LIT>" ) <EOL> def testShowsGenerateArchiveButtonForGetFileFlow ( self ) : <EOL> pathspec = rdf_paths . PathSpec ( <EOL> path = os . path . join ( self . base_path , "<STR_LIT>" ) , <EOL> pathtype = rdf_paths . PathSpec . PathType . OS ) <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> "<STR_LIT>" , self . action_mock , client_id = self . client_id , <EOL> pathspec = pathspec , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , <EOL> "<STR_LIT>" ) <EOL> def testGenerateArchiveButtonGetsDisabledAfterClick ( self ) : <EOL> pathspec = rdf_paths . PathSpec ( <EOL> path = os . path . join ( self . base_path , "<STR_LIT>" ) , <EOL> pathtype = rdf_paths . PathSpec . PathType . OS ) <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> "<STR_LIT>" , self . action_mock , client_id = self . client_id , <EOL> pathspec = pathspec , token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsElementPresent , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> def testShowsNotificationWhenArchiveGenerationIsDone ( self ) : <EOL> pathspec = rdf_paths . PathSpec ( <EOL> path = os . path . join ( self . base_path , "<STR_LIT>" ) , <EOL> pathtype = rdf_paths . PathSpec . PathType . OS ) <EOL> flow_urn = flow . GRRFlow . StartFlow ( flow_name = "<STR_LIT>" , <EOL> client_id = self . client_id , <EOL> pathspec = pathspec , <EOL> token = self . token ) <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> flow_urn , self . action_mock , client_id = self . client_id , <EOL> token = self . token ) : <EOL> pass <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsUserNotificationPresent , <EOL> "<STR_LIT>" % flow_urn . Basename ( ) ) <EOL> def testShowsErrorMessageIfArchiveStreamingFailsBeforeFirstChunkIsSent ( self ) : <EOL> pathspec = rdf_paths . PathSpec ( <EOL> path = os . path . join ( self . base_path , "<STR_LIT>" ) , <EOL> pathtype = rdf_paths . PathSpec . PathType . OS ) <EOL> flow_urn = flow . GRRFlow . StartFlow ( flow_name = "<STR_LIT>" , <EOL> client_id = self . client_id , <EOL> pathspec = pathspec , <EOL> token = self . token ) <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> flow_urn , self . action_mock , client_id = self . client_id , <EOL> token = self . token ) : <EOL> pass <EOL> def RaisingStub ( * unused_args , ** unused_kwargs ) : <EOL> raise RuntimeError ( "<STR_LIT>" ) <EOL> with utils . Stubber ( api_call_handler_utils . CollectionArchiveGenerator , <EOL> "<STR_LIT>" , RaisingStub ) : <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsUserNotificationPresent , <EOL> "<STR_LIT>" % <EOL> flow_urn . Basename ( ) ) <EOL> def testShowsNotificationIfArchiveStreamingFailsInProgress ( self ) : <EOL> pathspec = rdf_paths . PathSpec ( <EOL> path = os . path . join ( self . base_path , "<STR_LIT>" ) , <EOL> pathtype = rdf_paths . PathSpec . PathType . OS ) <EOL> flow_urn = flow . GRRFlow . StartFlow ( flow_name = "<STR_LIT>" , <EOL> client_id = self . client_id , <EOL> pathspec = pathspec , <EOL> token = self . token ) <EOL> with self . ACLChecksDisabled ( ) : <EOL> for _ in test_lib . TestFlowHelper ( <EOL> flow_urn , self . action_mock , client_id = self . client_id , <EOL> token = self . token ) : <EOL> pass <EOL> def RaisingStub ( * unused_args , ** unused_kwargs ) : <EOL> yield "<STR_LIT:foo>" <EOL> yield "<STR_LIT:bar>" <EOL> raise RuntimeError ( "<STR_LIT>" ) <EOL> with utils . Stubber ( api_call_handler_utils . CollectionArchiveGenerator , <EOL> "<STR_LIT>" , RaisingStub ) : <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsUserNotificationPresent , <EOL> "<STR_LIT>" % <EOL> flow_urn . Basename ( ) ) <EOL> self . WaitUntilNot ( self . IsTextPresent , <EOL> "<STR_LIT>" ) <EOL> def testCreateHuntFromFlow ( self ) : <EOL> email_descriptor = output_plugin . OutputPluginDescriptor ( <EOL> plugin_name = email_plugin . EmailOutputPlugin . __name__ , <EOL> plugin_args = email_plugin . EmailOutputPluginArgs ( <EOL> email_address = "<STR_LIT>" , emails_limit = <NUM_LIT> ) ) <EOL> args = flows_processes . ListProcessesArgs ( <EOL> filename_regex = "<STR_LIT>" , fetch_binaries = True ) <EOL> flow . GRRFlow . StartFlow ( <EOL> flow_name = flows_processes . ListProcesses . __name__ , <EOL> args = args , <EOL> client_id = self . client_id , <EOL> output_plugins = [ email_descriptor ] , <EOL> token = self . token ) <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntilEqual ( "<STR_LIT>" , self . GetValue , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsChecked , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntilNot ( self . IsElementPresent , <EOL> "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntilEqual ( <NUM_LIT:1> , self . GetCssCount , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntilEqual ( <NUM_LIT:1> , self . GetCssCount , <EOL> "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsTextPresent , "<STR_LIT>" ) <EOL> def testCheckCreateHuntButtonIsOnlyEnabledWithFlowSelection ( self ) : <EOL> flow . GRRFlow . StartFlow ( client_id = self . client_id , <EOL> flow_name = RecursiveTestFlow . __name__ , <EOL> token = self . token ) <EOL> self . Open ( "<STR_LIT:/>" ) <EOL> self . Open ( "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsElementPresent , <EOL> "<STR_LIT>" ) <EOL> self . Click ( "<STR_LIT>" ) <EOL> self . WaitUntil ( self . IsElementPresent , <EOL> "<STR_LIT>" ) <EOL> def main ( argv ) : <EOL> runtests_test . SeleniumTestProgram ( argv = argv ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> flags . StartMain ( main ) </s>
<s> """<STR_LIT>""" <EOL> import copy <EOL> import socket <EOL> import threading <EOL> from wsgiref import simple_server <EOL> import logging <EOL> from grr . gui import django_lib <EOL> from grr . lib import access_control <EOL> from grr . lib import config_lib <EOL> from grr . lib import data_store <EOL> from grr . lib import flags <EOL> from grr . lib import ipshell <EOL> from grr . lib import registry <EOL> from grr . lib import startup <EOL> from grr . lib import test_lib <EOL> class DjangoThread ( threading . Thread ) : <EOL> """<STR_LIT>""" <EOL> keep_running = True <EOL> daemon = True <EOL> def __init__ ( self , port , ** kwargs ) : <EOL> super ( DjangoThread , self ) . __init__ ( ** kwargs ) <EOL> self . base_url = "<STR_LIT>" % port <EOL> self . ready_to_serve = threading . Event ( ) <EOL> self . port = port <EOL> def StartAndWaitUntilServing ( self ) : <EOL> self . start ( ) <EOL> if not self . ready_to_serve . wait ( <NUM_LIT> ) : <EOL> raise RuntimeError ( "<STR_LIT>" ) <EOL> def run ( self ) : <EOL> """<STR_LIT>""" <EOL> logging . info ( "<STR_LIT>" , self . base_url ) <EOL> port = self . port <EOL> logging . info ( "<STR_LIT>" , port ) <EOL> try : <EOL> server = simple_server . make_server ( "<STR_LIT>" , port , <EOL> django_lib . GetWSGIHandler ( ) ) <EOL> except socket . error as e : <EOL> raise socket . error ( <EOL> "<STR_LIT>" % ( port , str ( e ) ) ) <EOL> self . ready_to_serve . set ( ) <EOL> while self . keep_running : <EOL> server . handle_request ( ) <EOL> class RunTestsInit ( registry . InitHook ) : <EOL> """<STR_LIT>""" <EOL> pre = [ "<STR_LIT>" ] <EOL> fixture_cache = None <EOL> def Run ( self ) : <EOL> """<STR_LIT>""" <EOL> data_store . DB . security_manager = test_lib . MockSecurityManager ( ) <EOL> self . token = access_control . ACLToken ( username = "<STR_LIT>" , <EOL> reason = "<STR_LIT>" ) <EOL> self . token = self . token . SetUID ( ) <EOL> if data_store . DB . __class__ . __name__ == "<STR_LIT>" : <EOL> self . RestoreFixtureFromCache ( ) <EOL> else : <EOL> self . BuildFixture ( ) <EOL> def BuildFixture ( self ) : <EOL> logging . info ( "<STR_LIT>" ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:10> ) : <EOL> test_lib . ClientFixture ( "<STR_LIT>" % i , token = self . token ) <EOL> def RestoreFixtureFromCache ( self ) : <EOL> """<STR_LIT>""" <EOL> if RunTestsInit . fixture_cache is None : <EOL> db = data_store . DB . subjects <EOL> data_store . DB . subjects = { } <EOL> self . BuildFixture ( ) <EOL> ( RunTestsInit . fixture_cache , <EOL> data_store . DB . subjects ) = ( data_store . DB . subjects , db ) <EOL> data_store . DB . subjects . update ( copy . deepcopy ( RunTestsInit . fixture_cache ) ) <EOL> class TestPluginInit ( registry . InitHook ) : <EOL> """<STR_LIT>""" <EOL> pre = [ "<STR_LIT>" ] <EOL> def RunOnce ( self ) : <EOL> from grr . gui import gui_testonly_plugins <EOL> from grr . gui . plugins import tests <EOL> def main ( _ ) : <EOL> """<STR_LIT>""" <EOL> startup . TestInit ( ) <EOL> trd = DjangoThread ( config_lib . CONFIG [ "<STR_LIT>" ] ) <EOL> trd . StartAndWaitUntilServing ( ) <EOL> user_ns = dict ( ) <EOL> user_ns . update ( globals ( ) ) <EOL> user_ns . update ( locals ( ) ) <EOL> ipshell . IPShell ( argv = [ ] , user_ns = user_ns ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> flags . StartMain ( main ) </s>
<s> """<STR_LIT>""" <EOL> import csv <EOL> import datetime <EOL> import StringIO <EOL> import time <EOL> import logging <EOL> from grr . lib import config_lib <EOL> from grr . lib import email_alerts <EOL> from grr . lib import export_utils <EOL> from grr . lib import rdfvalue <EOL> from grr . lib import registry <EOL> from grr . lib . aff4_objects import aff4_grr <EOL> from grr . lib . aff4_objects import network <EOL> class Report ( object ) : <EOL> """<STR_LIT>""" <EOL> __metaclass__ = registry . MetaclassRegistry <EOL> class ClientReport ( Report ) : <EOL> """<STR_LIT>""" <EOL> EMAIL_TEMPLATE = """<STR_LIT>""" <EOL> EMAIL_FROM = "<STR_LIT>" <EOL> REPORT_ATTRS = [ ] <EOL> EXTENDED_REPORT_ATTRS = [ ] <EOL> __abstract = True <EOL> def __init__ ( self , token = None , thread_num = <NUM_LIT:20> ) : <EOL> self . token = token <EOL> self . results = [ ] <EOL> self . fields = [ f . name for f in self . REPORT_ATTRS ] <EOL> self . fields += [ f [ <NUM_LIT:1> ] . name for f in self . EXTENDED_REPORT_ATTRS ] <EOL> self . thread_num = thread_num <EOL> self . broken_clients = [ ] <EOL> def AsDict ( self ) : <EOL> """<STR_LIT>""" <EOL> if not self . results : <EOL> logging . warn ( "<STR_LIT>" ) <EOL> else : <EOL> return self . results <EOL> def AsCsv ( self ) : <EOL> """<STR_LIT>""" <EOL> output = StringIO . StringIO ( ) <EOL> writer = csv . DictWriter ( output , self . fields ) <EOL> if hasattr ( writer , "<STR_LIT>" ) : <EOL> writer . writeheader ( ) <EOL> for val in self . results : <EOL> writer . writerow ( val ) <EOL> output . seek ( <NUM_LIT:0> ) <EOL> return output <EOL> def SortResults ( self , field ) : <EOL> """<STR_LIT>""" <EOL> logging . debug ( "<STR_LIT>" , len ( self . results ) ) <EOL> self . results . sort ( key = lambda x : str ( x . get ( field , "<STR_LIT>" ) ) ) <EOL> def AsHtmlTable ( self ) : <EOL> """<STR_LIT>""" <EOL> th = [ "<STR_LIT>" % f for f in self . fields ] <EOL> headers = "<STR_LIT>" % "<STR_LIT>" . join ( th ) <EOL> rows = [ ] <EOL> for val in self . results : <EOL> values = [ val [ k ] for k in self . fields ] <EOL> row = [ "<STR_LIT>" % f for f in values ] <EOL> rows . append ( "<STR_LIT>" % "<STR_LIT>" . join ( row ) ) <EOL> html_out = "<STR_LIT>" % ( headers , "<STR_LIT:\n>" . join ( rows ) ) <EOL> return html_out <EOL> def AsText ( self ) : <EOL> """<STR_LIT>""" <EOL> output = StringIO . StringIO ( ) <EOL> fields = self . fields <EOL> writer = csv . DictWriter ( output , fields , dialect = csv . excel_tab ) <EOL> for val in self . results : <EOL> writer . writerow ( val ) <EOL> output . seek ( <NUM_LIT:0> ) <EOL> return output <EOL> def MailReport ( self , recipient , subject = None ) : <EOL> """<STR_LIT>""" <EOL> dt = rdfvalue . RDFDatetime ( ) . Now ( ) . Format ( "<STR_LIT>" ) <EOL> subject = subject or "<STR_LIT>" % ( self . REPORT_NAME , dt ) <EOL> csv_data = self . AsCsv ( ) <EOL> filename = "<STR_LIT>" % ( self . REPORT_NAME , dt ) <EOL> email_alerts . EMAIL_ALERTER . SendEmail ( <EOL> recipient , self . EMAIL_FROM , subject , <EOL> "<STR_LIT>" , <EOL> attachments = { filename : csv_data . getvalue ( ) } , <EOL> is_html = False ) <EOL> logging . info ( "<STR_LIT>" , self . REPORT_NAME , recipient ) <EOL> def MailHTMLReport ( self , recipient , subject = None ) : <EOL> """<STR_LIT>""" <EOL> dt = rdfvalue . RDFDatetime ( ) . Now ( ) . Format ( "<STR_LIT>" ) <EOL> subject = subject or "<STR_LIT>" % ( self . REPORT_NAME , dt ) <EOL> report_text = self . AsHtmlTable ( ) <EOL> email_alerts . EMAIL_ALERTER . SendEmail ( <EOL> recipient , self . EMAIL_FROM , subject , <EOL> self . EMAIL_TEMPLATE % dict ( <EOL> report_text = report_text , <EOL> report_name = self . REPORT_NAME , <EOL> signature = config_lib . CONFIG [ "<STR_LIT>" ] ) , <EOL> is_html = True ) <EOL> logging . info ( "<STR_LIT>" , self . REPORT_NAME , recipient ) <EOL> def Run ( self , max_age = <NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:7> ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def _QueryResults ( self , max_age ) : <EOL> """<STR_LIT>""" <EOL> report_iter = ClientReportIterator ( <EOL> max_age = max_age , token = self . token , report_attrs = self . REPORT_ATTRS , <EOL> extended_report_attrs = self . EXTENDED_REPORT_ATTRS ) <EOL> self . broken_clients = report_iter . broken_subjects <EOL> return report_iter . Run ( ) <EOL> class ClientListReport ( ClientReport ) : <EOL> """<STR_LIT>""" <EOL> REPORT_ATTRS = [ <EOL> aff4_grr . VFSGRRClient . SchemaCls . GetAttribute ( "<STR_LIT>" ) , <EOL> aff4_grr . VFSGRRClient . SchemaCls . GetAttribute ( "<STR_LIT>" ) , <EOL> aff4_grr . VFSGRRClient . SchemaCls . GetAttribute ( "<STR_LIT>" ) , <EOL> aff4_grr . VFSGRRClient . SchemaCls . GetAttribute ( "<STR_LIT>" ) , <EOL> aff4_grr . VFSGRRClient . SchemaCls . GetAttribute ( "<STR_LIT>" ) , <EOL> aff4_grr . VFSGRRClient . SchemaCls . GetAttribute ( "<STR_LIT>" ) , <EOL> aff4_grr . VFSGRRClient . SchemaCls . GetAttribute ( "<STR_LIT>" ) , <EOL> ] <EOL> EXTENDED_REPORT_ATTRS = [ <EOL> ( "<STR_LIT>" , network . Network . SchemaCls . GetAttribute ( "<STR_LIT>" ) ) <EOL> ] <EOL> REPORT_NAME = "<STR_LIT>" <EOL> def Run ( self , max_age = <NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:7> ) : <EOL> """<STR_LIT>""" <EOL> start_time = time . time ( ) <EOL> self . results = [ ] <EOL> self . broken_subjects = [ ] <EOL> for client in self . _QueryResults ( max_age ) : <EOL> self . results . append ( client ) <EOL> self . SortResults ( "<STR_LIT>" ) <EOL> logging . info ( "<STR_LIT>" , self . REPORT_NAME , <EOL> datetime . timedelta ( seconds = time . time ( ) - start_time ) ) <EOL> class VersionBreakdownReport ( ClientReport ) : <EOL> """<STR_LIT>""" <EOL> REPORT_ATTRS = [ <EOL> aff4_grr . VFSGRRClient . SchemaCls . GetAttribute ( "<STR_LIT>" ) <EOL> ] <EOL> REPORT_NAME = "<STR_LIT>" <EOL> def Run ( self , max_age = <NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:7> ) : <EOL> """<STR_LIT>""" <EOL> counts = { } <EOL> self . fields . append ( "<STR_LIT:count>" ) <EOL> self . results = [ ] <EOL> for client in self . _QueryResults ( max_age ) : <EOL> version = client . get ( "<STR_LIT>" ) <EOL> try : <EOL> counts [ version ] += <NUM_LIT:1> <EOL> except KeyError : <EOL> counts [ version ] = <NUM_LIT:1> <EOL> for version , count in counts . iteritems ( ) : <EOL> self . results . append ( { "<STR_LIT>" : version , "<STR_LIT:count>" : count } ) <EOL> self . SortResults ( "<STR_LIT:count>" ) <EOL> class ClientReportIterator ( export_utils . IterateAllClients ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , report_attrs , extended_report_attrs , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> super ( ClientReportIterator , self ) . __init__ ( ** kwargs ) <EOL> self . report_attrs = report_attrs <EOL> self . extended_report_attrs = extended_report_attrs <EOL> def IterFunction ( self , client , out_queue , unused_token ) : <EOL> """<STR_LIT>""" <EOL> result = { } <EOL> for attr in self . report_attrs : <EOL> if attr . name == "<STR_LIT>" : <EOL> result [ attr . name ] = client . Get ( attr ) . Basename ( ) <EOL> elif attr . name == "<STR_LIT>" : <EOL> c_info = client . Get ( attr ) <EOL> if not c_info : <EOL> self . broken_subjects . append ( client . client_id ) <EOL> result [ attr . name ] = None <EOL> continue <EOL> result [ attr . name ] = "<STR_LIT>" % ( c_info . client_name , <EOL> str ( c_info . client_version ) ) <EOL> else : <EOL> result [ attr . name ] = client . Get ( attr ) <EOL> for sub_path , attr in self . extended_report_attrs : <EOL> try : <EOL> client_sub = client . OpenMember ( sub_path ) <EOL> except IOError : <EOL> continue <EOL> if attr . name == "<STR_LIT>" : <EOL> interfaces = client_sub . Get ( attr ) <EOL> if interfaces : <EOL> try : <EOL> result [ attr . name ] = "<STR_LIT:U+002C>" . join ( interfaces . GetIPAddresses ( ) ) <EOL> except AttributeError : <EOL> result [ attr . name ] = "<STR_LIT>" <EOL> else : <EOL> result [ attr . name ] = client_sub . Get ( attr ) <EOL> out_queue . put ( result ) <EOL> class ReportName ( rdfvalue . RDFString ) : <EOL> """<STR_LIT>""" <EOL> type = "<STR_LIT>" <EOL> def ParseFromString ( self , value ) : <EOL> super ( ReportName , self ) . ParseFromString ( value ) <EOL> if value not in Report . classes : <EOL> raise ValueError ( "<STR_LIT>" % value ) </s>
<s> """<STR_LIT>""" <EOL> from grr . lib import access_control <EOL> from grr . lib import config_lib <EOL> from grr . lib import registry <EOL> from grr . lib . authorization import auth_manager <EOL> from grr . lib . rdfvalues import structs as rdf_structs <EOL> from grr . proto import acls_pb2 <EOL> class Error ( Exception ) : <EOL> """<STR_LIT>""" <EOL> class ErrorInvalidClientApprovalAuthorization ( Error ) : <EOL> """<STR_LIT>""" <EOL> class ErrorInvalidApprovers ( Error ) : <EOL> """<STR_LIT>""" <EOL> class ErrorInvalidApprovalSpec ( Error ) : <EOL> """<STR_LIT>""" <EOL> class ClientApprovalAuthorization ( rdf_structs . RDFProtoStruct ) : <EOL> """<STR_LIT>""" <EOL> protobuf = acls_pb2 . ClientApprovalAuthorization <EOL> @ property <EOL> def label ( self ) : <EOL> label = self . Get ( "<STR_LIT:label>" ) <EOL> if not label : <EOL> raise ErrorInvalidClientApprovalAuthorization ( <EOL> "<STR_LIT>" ) <EOL> return label <EOL> @ label . setter <EOL> def label ( self , value ) : <EOL> if not isinstance ( value , basestring ) or not value : <EOL> raise ErrorInvalidClientApprovalAuthorization ( <EOL> "<STR_LIT>" ) <EOL> self . Set ( "<STR_LIT:label>" , value ) <EOL> @ property <EOL> def users ( self ) : <EOL> return self . Get ( "<STR_LIT>" ) <EOL> @ users . setter <EOL> def users ( self , value ) : <EOL> if not isinstance ( value , list ) : <EOL> raise ErrorInvalidClientApprovalAuthorization ( "<STR_LIT>" ) <EOL> self . Set ( "<STR_LIT>" , value ) <EOL> @ property <EOL> def groups ( self ) : <EOL> return self . Get ( "<STR_LIT>" ) <EOL> @ groups . setter <EOL> def groups ( self , value ) : <EOL> if not isinstance ( value , list ) : <EOL> raise ErrorInvalidClientApprovalAuthorization ( "<STR_LIT>" ) <EOL> self . Set ( "<STR_LIT>" , value ) <EOL> @ property <EOL> def key ( self ) : <EOL> return self . Get ( "<STR_LIT:label>" ) <EOL> class ClientApprovalAuthorizationManager ( <EOL> auth_manager . AuthorizationManager ) : <EOL> """<STR_LIT>""" <EOL> def Initialize ( self ) : <EOL> self . LoadApprovals ( ) <EOL> def IsActive ( self ) : <EOL> """<STR_LIT>""" <EOL> return bool ( self . reader . auth_objects ) <EOL> def LoadApprovals ( self , yaml_data = None ) : <EOL> self . reader = auth_manager . AuthorizationReader ( ) <EOL> if yaml_data : <EOL> self . reader . CreateAuthorizations ( yaml_data , ClientApprovalAuthorization ) <EOL> else : <EOL> with open ( <EOL> config_lib . CONFIG [ "<STR_LIT>" ] , mode = "<STR_LIT:rb>" ) as fh : <EOL> self . reader . CreateAuthorizations ( fh . read ( ) , ClientApprovalAuthorization ) <EOL> for approval_spec in self . reader . GetAllAuthorizationObjects ( ) : <EOL> for group in approval_spec . groups : <EOL> self . AuthorizeGroup ( group , approval_spec . label ) <EOL> for user in approval_spec . users : <EOL> self . AuthorizeUser ( user , approval_spec . label ) <EOL> def CheckApproversForLabel ( self , token , client_urn , requester , approvers , <EOL> label ) : <EOL> """<STR_LIT>""" <EOL> auth = self . reader . GetAuthorizationForSubject ( label ) <EOL> if not auth : <EOL> return True <EOL> if auth . requester_must_be_authorized : <EOL> if not self . CheckPermissions ( requester , label ) : <EOL> raise access_control . UnauthorizedAccess ( <EOL> "<STR_LIT>" % ( requester , auth . users , <EOL> auth . groups , label ) , <EOL> subject = client_urn , requested_access = token . requested_access ) <EOL> approved_count = <NUM_LIT:0> <EOL> for approver in approvers : <EOL> if self . CheckPermissions ( approver , label ) and approver != requester : <EOL> approved_count += <NUM_LIT:1> <EOL> if approved_count < auth . num_approvers_required : <EOL> raise access_control . UnauthorizedAccess ( <EOL> "<STR_LIT>" % ( <EOL> approved_count , label , auth . num_approvers_required ) , <EOL> subject = client_urn , requested_access = token . requested_access ) <EOL> return True <EOL> CLIENT_APPROVAL_AUTH_MGR = None <EOL> class ClientApprovalAuthorizationInit ( registry . InitHook ) : <EOL> def RunOnce ( self ) : <EOL> global CLIENT_APPROVAL_AUTH_MGR <EOL> CLIENT_APPROVAL_AUTH_MGR = ClientApprovalAuthorizationManager ( ) </s>
<s> """<STR_LIT>""" <EOL> from grr . lib import flags <EOL> from grr . lib import test_lib <EOL> from grr . lib . checks import hints <EOL> from grr . lib . rdfvalues import client as rdf_client <EOL> from grr . lib . rdfvalues import config_file as rdf_config_file <EOL> from grr . lib . rdfvalues import protodict as rdf_protodict <EOL> class HintsTests ( test_lib . GRRBaseTest ) : <EOL> """<STR_LIT>""" <EOL> def testCheckOverlay ( self ) : <EOL> """<STR_LIT>""" <EOL> full = { "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" } <EOL> partial = { "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" } <EOL> overlay = { "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : "<STR_LIT>" } <EOL> empty = { "<STR_LIT>" : "<STR_LIT>" , "<STR_LIT>" : "<STR_LIT>" , "<STR_LIT>" : "<STR_LIT>" , "<STR_LIT>" : "<STR_LIT>" } <EOL> starts_full = full . copy ( ) <EOL> starts_empty = empty . copy ( ) <EOL> hints . Overlay ( starts_full , starts_empty ) <EOL> self . assertDictEqual ( full , starts_full ) <EOL> self . assertDictEqual ( empty , starts_empty ) <EOL> starts_partial = partial . copy ( ) <EOL> starts_empty = empty . copy ( ) <EOL> hints . Overlay ( starts_empty , starts_partial ) <EOL> self . assertDictEqual ( partial , starts_partial ) <EOL> self . assertDictEqual ( partial , starts_empty ) <EOL> starts_full = full . copy ( ) <EOL> starts_partial = partial . copy ( ) <EOL> hints . Overlay ( starts_partial , starts_full ) <EOL> self . assertDictEqual ( full , starts_full ) <EOL> self . assertDictEqual ( overlay , starts_partial ) <EOL> def testRdfFormatter ( self ) : <EOL> """<STR_LIT>""" <EOL> rdf = rdf_client . ClientSummary ( ) <EOL> rdf . system_info . system = "<STR_LIT>" <EOL> rdf . system_info . node = "<STR_LIT>" <EOL> rdf . users = [ <EOL> rdf_client . User ( username = u ) for u in ( "<STR_LIT:root>" , "<STR_LIT>" ) ] <EOL> addresses = [ rdf_client . NetworkAddress ( human_readable = a ) for a in ( <EOL> "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ] <EOL> eth0 = rdf_client . Interface ( ifname = "<STR_LIT>" , addresses = addresses [ : <NUM_LIT:2> ] ) <EOL> ppp0 = rdf_client . Interface ( ifname = "<STR_LIT>" , addresses = addresses [ <NUM_LIT:2> ] ) <EOL> rdf . interfaces = [ eth0 , ppp0 ] <EOL> template = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> hinter = hints . Hinter ( template = template ) <EOL> expected = "<STR_LIT>" <EOL> result = hinter . Render ( rdf ) <EOL> self . assertEqual ( expected , result ) <EOL> def testRdfFormatterHandlesKeyValuePair ( self ) : <EOL> """<STR_LIT>""" <EOL> key = rdf_protodict . DataBlob ( ) . SetValue ( "<STR_LIT>" ) <EOL> value = rdf_protodict . DataBlob ( ) . SetValue ( [ <NUM_LIT> ] ) <EOL> rdf = rdf_protodict . KeyValue ( k = key , v = value ) <EOL> template = "<STR_LIT>" <EOL> hinter = hints . Hinter ( template = template ) <EOL> expected = "<STR_LIT>" <EOL> result = hinter . Render ( rdf ) <EOL> self . assertEqual ( expected , result ) <EOL> def testRdfFormatterAttributedDict ( self ) : <EOL> sshd = rdf_config_file . SshdConfig ( ) <EOL> sshd . config = rdf_protodict . AttributedDict ( skynet = "<STR_LIT>" ) <EOL> template = "<STR_LIT>" <EOL> hinter = hints . Hinter ( template = template ) <EOL> expected = "<STR_LIT>" <EOL> result = hinter . Render ( sshd ) <EOL> self . assertEqual ( expected , result ) <EOL> def testRdfFormatterFanOut ( self ) : <EOL> rdf = rdf_protodict . Dict ( ) <EOL> user1 = rdf_client . User ( username = "<STR_LIT>" ) <EOL> user2 = rdf_client . User ( username = "<STR_LIT>" ) <EOL> rdf [ "<STR_LIT>" ] = "<STR_LIT>" <EOL> rdf [ "<STR_LIT>" ] = [ user1 , user2 ] <EOL> rdf [ "<STR_LIT>" ] = { "<STR_LIT>" : [ "<STR_LIT>" , [ "<STR_LIT>" , [ "<STR_LIT>" ] ] ] , <EOL> "<STR_LIT>" : { "<STR_LIT>" : [ "<STR_LIT>" , "<STR_LIT>" ] } } <EOL> template = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> hinter = hints . Hinter ( template = template ) <EOL> expected = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> result = hinter . Render ( rdf ) <EOL> self . assertEqual ( expected , result ) <EOL> def testStatModeFormat ( self ) : <EOL> rdf = rdf_client . StatEntry ( st_mode = <NUM_LIT> ) <EOL> expected = "<STR_LIT>" <EOL> template = "<STR_LIT>" <EOL> hinter = hints . Hinter ( template = template ) <EOL> result = hinter . Render ( rdf ) <EOL> self . assertEqual ( expected , result ) <EOL> def main ( argv ) : <EOL> test_lib . main ( argv ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> flags . StartMain ( main ) </s>
<s> """<STR_LIT>""" <EOL> import logging <EOL> import Queue <EOL> import thread <EOL> import threading <EOL> import time <EOL> import MySQLdb <EOL> from MySQLdb import cursors <EOL> from grr . lib import aff4 <EOL> from grr . lib import config_lib <EOL> from grr . lib import data_store <EOL> from grr . lib import rdfvalue <EOL> from grr . lib import utils <EOL> class Error ( data_store . Error ) : <EOL> """<STR_LIT>""" <EOL> class SafeQueue ( Queue . Queue ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , maxsize = <NUM_LIT:0> ) : <EOL> Queue . Queue . __init__ ( self , maxsize = maxsize ) <EOL> self . mutex = threading . RLock ( ) <EOL> self . not_empty = threading . Condition ( self . mutex ) <EOL> self . not_full = threading . Condition ( self . mutex ) <EOL> self . all_tasks_done = threading . Condition ( self . mutex ) <EOL> class MySQLConnection ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , database_name ) : <EOL> try : <EOL> self . dbh = self . _MakeConnection ( database = database_name ) <EOL> self . cursor = self . dbh . cursor ( ) <EOL> self . cursor . connection . autocommit ( True ) <EOL> self . cursor . execute ( "<STR_LIT>" ) <EOL> except MySQLdb . OperationalError as e : <EOL> if "<STR_LIT>" in str ( e ) : <EOL> dbh = self . _MakeConnection ( ) <EOL> cursor = dbh . cursor ( ) <EOL> cursor . connection . autocommit ( True ) <EOL> cursor . execute ( "<STR_LIT>" % database_name ) <EOL> cursor . close ( ) <EOL> dbh . close ( ) <EOL> self . dbh = self . _MakeConnection ( database = database_name ) <EOL> self . cursor = self . dbh . cursor ( ) <EOL> self . cursor . connection . autocommit ( True ) <EOL> self . cursor . execute ( "<STR_LIT>" ) <EOL> else : <EOL> raise <EOL> def _MakeConnection ( self , database = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> first_attempt_time = time . time ( ) <EOL> wait_time = config_lib . CONFIG [ "<STR_LIT>" ] <EOL> while wait_time == <NUM_LIT:0> or time . time ( ) - first_attempt_time < wait_time : <EOL> try : <EOL> connection_args = dict ( <EOL> user = config_lib . CONFIG [ "<STR_LIT>" ] , <EOL> db = database , charset = "<STR_LIT:utf8>" , <EOL> passwd = config_lib . CONFIG [ "<STR_LIT>" ] , <EOL> cursorclass = cursors . DictCursor , <EOL> host = config_lib . CONFIG [ "<STR_LIT>" ] , <EOL> port = config_lib . CONFIG [ "<STR_LIT>" ] ) <EOL> dbh = MySQLdb . connect ( ** connection_args ) <EOL> return dbh <EOL> except MySQLdb . OperationalError as e : <EOL> if "<STR_LIT>" in str ( e ) : <EOL> raise Error ( str ( e ) ) <EOL> if "<STR_LIT>" in str ( e ) : <EOL> logging . warning ( "<STR_LIT>" , <EOL> str ( e ) ) <EOL> time . sleep ( <NUM_LIT> ) <EOL> continue <EOL> raise <EOL> raise IOError ( "<STR_LIT>" ) <EOL> class ConnectionPool ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , database_name ) : <EOL> self . connections = SafeQueue ( ) <EOL> self . database_name = database_name <EOL> self . pool_max_size = int ( config_lib . CONFIG [ "<STR_LIT>" ] ) <EOL> self . pool_min_size = int ( config_lib . CONFIG [ "<STR_LIT>" ] ) <EOL> for _ in range ( self . pool_min_size ) : <EOL> self . connections . put ( MySQLConnection ( self . database_name ) ) <EOL> def GetConnection ( self ) : <EOL> if self . connections . empty ( ) and ( self . connections . unfinished_tasks < <EOL> self . pool_max_size ) : <EOL> self . connections . put ( MySQLConnection ( self . database_name ) ) <EOL> connection = self . connections . get ( block = True ) <EOL> return connection <EOL> def PutConnection ( self , connection ) : <EOL> if self . connections . qsize ( ) < self . pool_min_size : <EOL> self . connections . put ( connection ) <EOL> else : <EOL> self . DropConnection ( connection ) <EOL> def DropConnection ( self , connection ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> connection . cursor . close ( ) <EOL> except MySQLdb . Error : <EOL> pass <EOL> try : <EOL> connection . dbh . close ( ) <EOL> except MySQLdb . Error : <EOL> pass <EOL> class MySQLAdvancedDataStore ( data_store . DataStore ) : <EOL> """<STR_LIT>""" <EOL> POOL = None <EOL> def __init__ ( self ) : <EOL> self . database_name = config_lib . CONFIG [ "<STR_LIT>" ] <EOL> if MySQLAdvancedDataStore . POOL is None : <EOL> MySQLAdvancedDataStore . POOL = ConnectionPool ( self . database_name ) <EOL> self . pool = self . POOL <EOL> self . to_replace = [ ] <EOL> self . to_insert = [ ] <EOL> self . _CalculateAttributeStorageTypes ( ) <EOL> self . database_name = config_lib . CONFIG [ "<STR_LIT>" ] <EOL> self . buffer_lock = threading . RLock ( ) <EOL> self . lock = threading . RLock ( ) <EOL> super ( MySQLAdvancedDataStore , self ) . __init__ ( ) <EOL> def Initialize ( self ) : <EOL> super ( MySQLAdvancedDataStore , self ) . Initialize ( ) <EOL> try : <EOL> self . ExecuteQuery ( "<STR_LIT>" ) <EOL> except MySQLdb . Error : <EOL> logging . debug ( "<STR_LIT>" ) <EOL> self . RecreateTables ( ) <EOL> def DropTables ( self ) : <EOL> """<STR_LIT>""" <EOL> rows = self . ExecuteQuery ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % self . database_name ) <EOL> for row in rows : <EOL> self . ExecuteQuery ( "<STR_LIT>" % row [ "<STR_LIT>" ] ) <EOL> def RecreateTables ( self ) : <EOL> """<STR_LIT>""" <EOL> self . DropTables ( ) <EOL> self . _CreateTables ( ) <EOL> def Transaction ( self , subject , lease_time = None , token = None ) : <EOL> return MySQLTransaction ( self , subject , lease_time = lease_time , token = token ) <EOL> def Size ( self ) : <EOL> query = ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> self . database_name ) <EOL> result = self . ExecuteQuery ( query , [ ] ) <EOL> if len ( result ) != <NUM_LIT:1> : <EOL> return - <NUM_LIT:1> <EOL> return int ( result [ <NUM_LIT:0> ] [ "<STR_LIT:size>" ] ) <EOL> def DeleteAttributes ( self , subject , attributes , start = None , end = None , <EOL> sync = True , token = None ) : <EOL> """<STR_LIT>""" <EOL> _ = sync <EOL> self . security_manager . CheckDataStoreAccess ( token , [ subject ] , "<STR_LIT:w>" ) <EOL> if not attributes : <EOL> return <EOL> if isinstance ( attributes , basestring ) : <EOL> raise ValueError ( <EOL> "<STR_LIT>" ) <EOL> for attribute in attributes : <EOL> timestamp = self . _MakeTimestamp ( start , end ) <EOL> attribute = utils . SmartUnicode ( attribute ) <EOL> queries = self . _BuildDelete ( subject , attribute , timestamp ) <EOL> self . _ExecuteQueries ( queries ) <EOL> def DeleteSubject ( self , subject , sync = False , token = None ) : <EOL> _ = sync <EOL> self . security_manager . CheckDataStoreAccess ( token , [ subject ] , "<STR_LIT:w>" ) <EOL> queries = self . _BuildDelete ( subject ) <EOL> self . _ExecuteQueries ( queries ) <EOL> def ResolveMulti ( self , subject , attributes , timestamp = None , limit = None , <EOL> token = None ) : <EOL> """<STR_LIT>""" <EOL> self . security_manager . CheckDataStoreAccess ( <EOL> token , [ subject ] , self . GetRequiredResolveAccess ( attributes ) ) <EOL> for attribute in attributes : <EOL> query , args = self . _BuildQuery ( subject , attribute , timestamp , limit ) <EOL> result = self . ExecuteQuery ( query , args ) <EOL> for row in result : <EOL> value = self . _Decode ( attribute , row [ "<STR_LIT:value>" ] ) <EOL> yield ( attribute , value , row [ "<STR_LIT>" ] ) <EOL> if limit : <EOL> limit -= len ( result ) <EOL> if limit is not None and limit <= <NUM_LIT:0> : <EOL> break <EOL> def MultiResolvePrefix ( self , subjects , attribute_prefix , timestamp = None , <EOL> limit = None , token = None ) : <EOL> """<STR_LIT>""" <EOL> result = { } <EOL> for subject in subjects : <EOL> values = self . ResolvePrefix ( subject , attribute_prefix , token = token , <EOL> timestamp = timestamp , limit = limit ) <EOL> if values : <EOL> result [ subject ] = values <EOL> if limit : <EOL> limit -= len ( values ) <EOL> if limit is not None and limit <= <NUM_LIT:0> : <EOL> break <EOL> return result . iteritems ( ) <EOL> def ResolvePrefix ( self , subject , attribute_prefix , timestamp = None , limit = None , <EOL> token = None ) : <EOL> """<STR_LIT>""" <EOL> self . security_manager . CheckDataStoreAccess ( <EOL> token , [ subject ] , self . GetRequiredResolveAccess ( attribute_prefix ) ) <EOL> if isinstance ( attribute_prefix , basestring ) : <EOL> attribute_prefix = [ attribute_prefix ] <EOL> results = [ ] <EOL> for prefix in attribute_prefix : <EOL> query , args = self . _BuildQuery ( subject , prefix , timestamp , limit , <EOL> is_prefix = True ) <EOL> rows = self . ExecuteQuery ( query , args ) <EOL> for row in rows : <EOL> attribute = row [ "<STR_LIT>" ] <EOL> value = self . _Decode ( attribute , row [ "<STR_LIT:value>" ] ) <EOL> results . append ( ( attribute , value , row [ "<STR_LIT>" ] ) ) <EOL> return results <EOL> def _ScanAttribute ( self , subject_prefix , attribute , after_urn = None , <EOL> limit = None , token = None ) : <EOL> self . security_manager . CheckDataStoreAccess ( <EOL> token , [ subject_prefix ] , "<STR_LIT>" ) <EOL> subject_prefix = utils . SmartStr ( rdfvalue . RDFURN ( subject_prefix ) ) <EOL> if subject_prefix [ - <NUM_LIT:1> ] != "<STR_LIT:/>" : <EOL> subject_prefix += "<STR_LIT:/>" <EOL> subject_prefix += "<STR_LIT:%>" <EOL> query = """<STR_LIT>""" <EOL> args = [ attribute , subject_prefix , after_urn , attribute ] <EOL> if limit : <EOL> query += "<STR_LIT>" <EOL> args . append ( limit ) <EOL> results = self . ExecuteQuery ( query , args ) <EOL> return results <EOL> def ScanAttributes ( self , subject_prefix , attributes , after_urn = None , <EOL> max_records = None , token = None , relaxed_order = False ) : <EOL> _ = relaxed_order <EOL> if after_urn : <EOL> after_urn = utils . SmartStr ( after_urn ) <EOL> else : <EOL> after_urn = "<STR_LIT>" <EOL> results = { } <EOL> for attribute in attributes : <EOL> attribute_results = self . _ScanAttribute ( <EOL> subject_prefix , attribute , after_urn , max_records , token ) <EOL> for row in attribute_results : <EOL> subject = row [ "<STR_LIT>" ] <EOL> timestamp = row [ "<STR_LIT>" ] <EOL> value = self . _Decode ( attribute , row [ "<STR_LIT:value>" ] ) <EOL> if subject in results : <EOL> results [ subject ] [ attribute ] = ( timestamp , value ) <EOL> else : <EOL> results [ subject ] = { attribute : ( timestamp , value ) } <EOL> result_count = <NUM_LIT:0> <EOL> for subject in sorted ( results ) : <EOL> yield ( subject , results [ subject ] ) <EOL> result_count += <NUM_LIT:1> <EOL> if max_records and result_count >= max_records : <EOL> return <EOL> def MultiSet ( self , subject , values , timestamp = None , replace = True , sync = True , <EOL> to_delete = None , token = None ) : <EOL> """<STR_LIT>""" <EOL> self . security_manager . CheckDataStoreAccess ( token , [ subject ] , "<STR_LIT:w>" ) <EOL> to_delete = set ( to_delete or [ ] ) <EOL> subject = utils . SmartUnicode ( subject ) <EOL> to_insert = [ ] <EOL> to_replace = [ ] <EOL> transaction = [ ] <EOL> for attribute , sequence in values . items ( ) : <EOL> for value in sequence : <EOL> if isinstance ( value , tuple ) : <EOL> value , entry_timestamp = value <EOL> else : <EOL> entry_timestamp = timestamp <EOL> if entry_timestamp is None : <EOL> entry_timestamp = timestamp <EOL> if entry_timestamp is not None : <EOL> entry_timestamp = int ( entry_timestamp ) <EOL> attribute = utils . SmartUnicode ( attribute ) <EOL> data = self . _Encode ( value ) <EOL> if replace or attribute in to_delete : <EOL> existing = self . _CountExistingRows ( subject , attribute ) <EOL> if existing : <EOL> to_replace . append ( [ subject , attribute , data , entry_timestamp ] ) <EOL> else : <EOL> to_insert . append ( [ subject , attribute , data , entry_timestamp ] ) <EOL> if attribute in to_delete : <EOL> to_delete . remove ( attribute ) <EOL> else : <EOL> to_insert . append ( [ subject , attribute , data , entry_timestamp ] ) <EOL> if to_delete : <EOL> self . DeleteAttributes ( subject , to_delete , token = token ) <EOL> if sync : <EOL> if to_replace : <EOL> transaction . extend ( self . _BuildReplaces ( to_replace ) ) <EOL> if to_insert : <EOL> transaction . extend ( self . _BuildInserts ( to_insert ) ) <EOL> if transaction : <EOL> self . _ExecuteTransaction ( transaction ) <EOL> else : <EOL> if to_replace : <EOL> with self . buffer_lock : <EOL> self . to_replace . extend ( to_replace ) <EOL> if to_insert : <EOL> with self . buffer_lock : <EOL> self . to_insert . extend ( to_insert ) <EOL> def _CountExistingRows ( self , subject , attribute ) : <EOL> query = ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> args = [ subject , attribute ] <EOL> result = self . ExecuteQuery ( query , args ) <EOL> return int ( result [ <NUM_LIT:0> ] [ "<STR_LIT>" ] ) <EOL> @ utils . Synchronized <EOL> def Flush ( self ) : <EOL> super ( MySQLAdvancedDataStore , self ) . Flush ( ) <EOL> with self . buffer_lock : <EOL> to_insert = self . to_insert <EOL> to_replace = self . to_replace <EOL> self . to_replace = [ ] <EOL> self . to_insert = [ ] <EOL> transaction = [ ] <EOL> if to_replace : <EOL> transaction . extend ( self . _BuildReplaces ( to_replace ) ) <EOL> if to_insert : <EOL> transaction . extend ( self . _BuildInserts ( to_insert ) ) <EOL> if transaction : <EOL> self . _ExecuteTransaction ( transaction ) <EOL> def _BuildReplaces ( self , values ) : <EOL> transaction = [ ] <EOL> updates = { } <EOL> to_insert = [ ] <EOL> for ( subject , attribute , data , timestamp ) in values : <EOL> updates . setdefault ( subject , { } ) [ attribute ] = [ data , timestamp ] <EOL> for subject in updates : <EOL> for attribute in updates [ subject ] : <EOL> data = updates [ subject ] [ attribute ] [ <NUM_LIT:0> ] <EOL> timestamp = updates [ subject ] [ attribute ] [ <NUM_LIT:1> ] <EOL> to_insert . append ( [ subject , attribute , data , timestamp ] ) <EOL> delete_q = self . _BuildDelete ( subject , attribute ) [ <NUM_LIT:0> ] <EOL> transaction . append ( delete_q ) <EOL> transaction . extend ( self . _BuildInserts ( to_insert ) ) <EOL> return transaction <EOL> def _BuildInserts ( self , values ) : <EOL> subjects_q = { } <EOL> attributes_q = { } <EOL> aff4_q = { } <EOL> subjects_q [ "<STR_LIT>" ] = "<STR_LIT>" <EOL> attributes_q [ "<STR_LIT>" ] = ( <EOL> "<STR_LIT>" ) <EOL> aff4_q [ "<STR_LIT>" ] = ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> subjects_q [ "<STR_LIT:args>" ] = [ ] <EOL> attributes_q [ "<STR_LIT:args>" ] = [ ] <EOL> aff4_q [ "<STR_LIT:args>" ] = [ ] <EOL> seen = { } <EOL> seen [ "<STR_LIT>" ] = [ ] <EOL> seen [ "<STR_LIT>" ] = [ ] <EOL> for ( subject , attribute , value , timestamp ) in values : <EOL> if subject not in seen [ "<STR_LIT>" ] : <EOL> subjects_q [ "<STR_LIT:args>" ] . extend ( [ subject , subject ] ) <EOL> seen [ "<STR_LIT>" ] . append ( subject ) <EOL> if attribute not in seen [ "<STR_LIT>" ] : <EOL> attributes_q [ "<STR_LIT:args>" ] . extend ( [ attribute , attribute ] ) <EOL> seen [ "<STR_LIT>" ] . append ( attribute ) <EOL> aff4_q [ "<STR_LIT:args>" ] . extend ( [ subject , attribute , timestamp , timestamp , value ] ) <EOL> subjects_q [ "<STR_LIT>" ] += "<STR_LIT:U+002CU+0020>" . join ( <EOL> [ "<STR_LIT>" ] * ( len ( subjects_q [ "<STR_LIT:args>" ] ) / <NUM_LIT:2> ) ) <EOL> attributes_q [ "<STR_LIT>" ] += "<STR_LIT:U+002CU+0020>" . join ( <EOL> [ "<STR_LIT>" ] * ( len ( attributes_q [ "<STR_LIT:args>" ] ) / <NUM_LIT:2> ) ) <EOL> aff4_q [ "<STR_LIT>" ] += "<STR_LIT:U+002CU+0020>" . join ( <EOL> [ "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ] * <EOL> ( len ( aff4_q [ "<STR_LIT:args>" ] ) / <NUM_LIT:5> ) ) <EOL> return [ aff4_q , attributes_q , subjects_q ] <EOL> def ExecuteQuery ( self , query , args = None ) : <EOL> """<STR_LIT>""" <EOL> while True : <EOL> connection = self . pool . GetConnection ( ) <EOL> try : <EOL> connection . cursor . execute ( query , args ) <EOL> results = connection . cursor . fetchall ( ) <EOL> self . pool . PutConnection ( connection ) <EOL> return results <EOL> except MySQLdb . Error as e : <EOL> self . pool . DropConnection ( connection ) <EOL> if "<STR_LIT>" in str ( e ) : <EOL> raise e <EOL> else : <EOL> logging . warning ( "<STR_LIT>" , <EOL> str ( e ) ) <EOL> time . sleep ( <NUM_LIT:1> ) <EOL> finally : <EOL> self . pool . connections . task_done ( ) <EOL> def _ExecuteQueries ( self , queries ) : <EOL> """<STR_LIT>""" <EOL> for query in queries : <EOL> self . ExecuteQuery ( query [ "<STR_LIT>" ] , query [ "<STR_LIT:args>" ] ) <EOL> def _ExecuteTransaction ( self , transaction ) : <EOL> """<STR_LIT>""" <EOL> while True : <EOL> connection = self . pool . GetConnection ( ) <EOL> try : <EOL> connection . cursor . execute ( "<STR_LIT>" ) <EOL> for query in transaction : <EOL> connection . cursor . execute ( query [ "<STR_LIT>" ] , query [ "<STR_LIT:args>" ] ) <EOL> connection . cursor . execute ( "<STR_LIT>" ) <EOL> results = connection . cursor . fetchall ( ) <EOL> self . pool . PutConnection ( connection ) <EOL> return results <EOL> except MySQLdb . Error as e : <EOL> self . pool . DropConnection ( connection ) <EOL> if "<STR_LIT>" in str ( e ) : <EOL> raise e <EOL> else : <EOL> logging . warning ( "<STR_LIT>" , <EOL> str ( e ) ) <EOL> time . sleep ( <NUM_LIT:1> ) <EOL> finally : <EOL> self . pool . connections . task_done ( ) <EOL> def _CalculateAttributeStorageTypes ( self ) : <EOL> """<STR_LIT>""" <EOL> self . attribute_types = { } <EOL> for attribute in aff4 . Attribute . PREDICATES . values ( ) : <EOL> self . attribute_types [ attribute . predicate ] = ( <EOL> attribute . attribute_type . data_store_type ) <EOL> def _Encode ( self , value ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> return value . SerializeToString ( ) . encode ( "<STR_LIT>" ) <EOL> except AttributeError : <EOL> if isinstance ( value , ( int , long ) ) : <EOL> return str ( value ) . encode ( "<STR_LIT>" ) <EOL> else : <EOL> return utils . SmartStr ( value ) . encode ( "<STR_LIT>" ) <EOL> def _Decode ( self , attribute , value ) : <EOL> required_type = self . attribute_types . get ( attribute , "<STR_LIT>" ) <EOL> if isinstance ( value , buffer ) : <EOL> value = str ( value ) <EOL> if required_type in ( "<STR_LIT>" , "<STR_LIT>" ) : <EOL> return int ( value ) <EOL> elif required_type == "<STR_LIT:string>" : <EOL> return utils . SmartUnicode ( value ) <EOL> else : <EOL> return value <EOL> def _BuildQuery ( self , subject , attribute = None , timestamp = None , <EOL> limit = None , is_prefix = False ) : <EOL> """<STR_LIT>""" <EOL> args = [ ] <EOL> subject = utils . SmartUnicode ( subject ) <EOL> criteria = "<STR_LIT>" <EOL> args . append ( subject ) <EOL> sorting = "<STR_LIT>" <EOL> tables = "<STR_LIT>" <EOL> if attribute is not None : <EOL> if is_prefix : <EOL> tables += "<STR_LIT>" <EOL> prefix = attribute + "<STR_LIT:%>" <EOL> criteria += "<STR_LIT>" <EOL> args . append ( prefix ) <EOL> else : <EOL> criteria += "<STR_LIT>" <EOL> args . append ( attribute ) <EOL> if isinstance ( timestamp , ( tuple , list ) ) : <EOL> criteria += "<STR_LIT>" <EOL> args . append ( int ( timestamp [ <NUM_LIT:0> ] ) ) <EOL> args . append ( int ( timestamp [ <NUM_LIT:1> ] ) ) <EOL> fields = "<STR_LIT>" <EOL> if is_prefix : <EOL> fields += "<STR_LIT>" <EOL> if timestamp is None or timestamp == self . NEWEST_TIMESTAMP : <EOL> tables += ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) % ( tables , criteria ) <EOL> criteria = "<STR_LIT>" <EOL> args . append ( subject ) <EOL> else : <EOL> sorting = "<STR_LIT>" <EOL> if limit : <EOL> sorting += "<STR_LIT>" % int ( limit ) <EOL> query = "<STR_LIT:U+0020>" . join ( [ "<STR_LIT>" , fields , tables , criteria , sorting ] ) <EOL> return ( query , args ) <EOL> def _BuildDelete ( self , subject , attribute = None , timestamp = None ) : <EOL> """<STR_LIT>""" <EOL> subjects_q = { <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT:args>" : [ subject ] <EOL> } <EOL> aff4_q = { <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT:args>" : [ subject ] <EOL> } <EOL> locks_q = { <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT:args>" : [ subject ] <EOL> } <EOL> if attribute : <EOL> aff4_q [ "<STR_LIT>" ] += "<STR_LIT>" <EOL> aff4_q [ "<STR_LIT:args>" ] . append ( attribute ) <EOL> if isinstance ( timestamp , ( tuple , list ) ) : <EOL> aff4_q [ "<STR_LIT>" ] += "<STR_LIT>" <EOL> aff4_q [ "<STR_LIT:args>" ] . append ( int ( timestamp [ <NUM_LIT:0> ] ) ) <EOL> aff4_q [ "<STR_LIT:args>" ] . append ( int ( timestamp [ <NUM_LIT:1> ] ) ) <EOL> attributes_q = { <EOL> "<STR_LIT>" : "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" , <EOL> "<STR_LIT:args>" : [ attribute ] <EOL> } <EOL> return [ aff4_q , attributes_q ] <EOL> return [ aff4_q , locks_q , subjects_q ] <EOL> def _MakeTimestamp ( self , start = None , end = None ) : <EOL> """<STR_LIT>""" <EOL> mysql_unsigned_bigint_max = <NUM_LIT> <EOL> ts_start = int ( start or <NUM_LIT:0> ) <EOL> if end is None : <EOL> ts_end = mysql_unsigned_bigint_max <EOL> else : <EOL> ts_end = int ( end ) <EOL> if ts_start == <NUM_LIT:0> and ts_end == mysql_unsigned_bigint_max : <EOL> return None <EOL> else : <EOL> return ( ts_start , ts_end ) <EOL> def _CreateTables ( self ) : <EOL> self . ExecuteQuery ( """<STR_LIT>""" ) <EOL> self . ExecuteQuery ( """<STR_LIT>""" ) <EOL> self . ExecuteQuery ( """<STR_LIT>""" ) <EOL> self . ExecuteQuery ( """<STR_LIT>""" ) <EOL> class MySQLTransaction ( data_store . CommonTransaction ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , store , subject , lease_time = None , token = None ) : <EOL> """<STR_LIT>""" <EOL> super ( MySQLTransaction , self ) . __init__ ( store , subject , <EOL> lease_time = lease_time , token = token ) <EOL> if lease_time is None : <EOL> lease_time = config_lib . CONFIG [ "<STR_LIT>" ] <EOL> self . lock_token = thread . get_ident ( ) <EOL> self . lock_time = lease_time <EOL> self . expires_lock = int ( ( time . time ( ) + self . lock_time ) * <NUM_LIT> ) <EOL> query = ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> args = [ self . expires_lock , self . lock_token , subject , time . time ( ) * <NUM_LIT> ] <EOL> self . store . ExecuteQuery ( query , args ) <EOL> self . _CheckForLock ( ) <EOL> def UpdateLease ( self , lease_time ) : <EOL> self . expires_lock = int ( ( time . time ( ) + lease_time ) * <NUM_LIT> ) <EOL> query = ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> args = [ self . expires_lock , self . lock_token , self . subject ] <EOL> self . store . ExecuteQuery ( query , args ) <EOL> def CheckLease ( self ) : <EOL> return max ( <NUM_LIT:0> , self . expires_lock / <NUM_LIT> - time . time ( ) ) <EOL> def Abort ( self ) : <EOL> self . _RemoveLock ( ) <EOL> def Commit ( self ) : <EOL> super ( MySQLTransaction , self ) . Commit ( ) <EOL> self . _RemoveLock ( ) <EOL> def _CheckForLock ( self ) : <EOL> """<STR_LIT>""" <EOL> query = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> args = [ self . subject ] <EOL> rows = self . store . ExecuteQuery ( query , args ) <EOL> for row in rows : <EOL> if ( row [ "<STR_LIT>" ] == self . expires_lock and <EOL> row [ "<STR_LIT>" ] == self . lock_token ) : <EOL> return <EOL> else : <EOL> raise data_store . TransactionError ( "<STR_LIT>" % self . subject ) <EOL> query = ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> args = [ self . expires_lock , self . lock_token , self . subject ] <EOL> self . store . ExecuteQuery ( query , args ) <EOL> self . _CheckForLock ( ) <EOL> def _RemoveLock ( self ) : <EOL> query = ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> args = [ self . expires_lock , self . lock_token , self . subject ] <EOL> self . store . ExecuteQuery ( query , args ) </s>
<s> """<STR_LIT>""" <EOL> from grr . lib import aff4 <EOL> from grr . lib import client_index <EOL> from grr . lib import config_lib <EOL> from grr . lib import flow <EOL> from grr . lib import rdfvalue <EOL> from grr . lib import utils <EOL> from grr . lib . aff4_objects import cronjobs <EOL> class CleanHunts ( cronjobs . SystemCronFlow ) : <EOL> """<STR_LIT>""" <EOL> frequency = rdfvalue . Duration ( "<STR_LIT>" ) <EOL> lifetime = rdfvalue . Duration ( "<STR_LIT>" ) <EOL> @ flow . StateHandler ( ) <EOL> def Start ( self ) : <EOL> hunts_ttl = config_lib . CONFIG [ "<STR_LIT>" ] <EOL> if not hunts_ttl : <EOL> self . Log ( "<STR_LIT>" ) <EOL> return <EOL> exception_label = config_lib . CONFIG [ <EOL> "<STR_LIT>" ] <EOL> hunts_root = aff4 . FACTORY . Open ( "<STR_LIT>" , token = self . token ) <EOL> hunts_urns = list ( hunts_root . ListChildren ( ) ) <EOL> deadline = rdfvalue . RDFDatetime ( ) . Now ( ) - hunts_ttl <EOL> hunts = aff4 . FACTORY . MultiOpen ( hunts_urns , aff4_type = "<STR_LIT>" , <EOL> token = self . token ) <EOL> for hunt in hunts : <EOL> if exception_label in hunt . GetLabelsNames ( ) : <EOL> continue <EOL> runner = hunt . GetRunner ( ) <EOL> if runner . context . expires < deadline : <EOL> aff4 . FACTORY . Delete ( hunt . urn , token = self . token ) <EOL> self . HeartBeat ( ) <EOL> class CleanCronJobs ( cronjobs . SystemCronFlow ) : <EOL> """<STR_LIT>""" <EOL> frequency = rdfvalue . Duration ( "<STR_LIT>" ) <EOL> lifetime = rdfvalue . Duration ( "<STR_LIT>" ) <EOL> @ flow . StateHandler ( ) <EOL> def Start ( self ) : <EOL> cron_jobs_ttl = config_lib . CONFIG [ "<STR_LIT>" ] <EOL> if not cron_jobs_ttl : <EOL> self . Log ( "<STR_LIT>" ) <EOL> return <EOL> jobs = cronjobs . CRON_MANAGER . ListJobs ( token = self . token ) <EOL> jobs_objs = aff4 . FACTORY . MultiOpen ( jobs , aff4_type = "<STR_LIT>" , <EOL> mode = "<STR_LIT:r>" , token = self . token ) <EOL> for obj in jobs_objs : <EOL> age = rdfvalue . RDFDatetime ( ) . Now ( ) - cron_jobs_ttl <EOL> obj . DeleteJobFlows ( age ) <EOL> self . HeartBeat ( ) <EOL> class CleanTemp ( cronjobs . SystemCronFlow ) : <EOL> """<STR_LIT>""" <EOL> frequency = rdfvalue . Duration ( "<STR_LIT>" ) <EOL> lifetime = rdfvalue . Duration ( "<STR_LIT>" ) <EOL> @ flow . StateHandler ( ) <EOL> def Start ( self ) : <EOL> tmp_ttl = config_lib . CONFIG [ "<STR_LIT>" ] <EOL> if not tmp_ttl : <EOL> self . Log ( "<STR_LIT>" ) <EOL> return <EOL> exception_label = config_lib . CONFIG [ <EOL> "<STR_LIT>" ] <EOL> tmp_root = aff4 . FACTORY . Open ( "<STR_LIT>" , mode = "<STR_LIT:r>" , token = self . token ) <EOL> tmp_urns = list ( tmp_root . ListChildren ( ) ) <EOL> deadline = rdfvalue . RDFDatetime ( ) . Now ( ) - tmp_ttl <EOL> for tmp_group in utils . Grouper ( tmp_urns , <NUM_LIT> ) : <EOL> expired_tmp_urns = [ ] <EOL> for tmp_obj in aff4 . FACTORY . MultiOpen ( tmp_group , mode = "<STR_LIT:r>" , <EOL> token = self . token ) : <EOL> if exception_label in tmp_obj . GetLabelsNames ( ) : <EOL> continue <EOL> if tmp_obj . Get ( tmp_obj . Schema . LAST ) < deadline : <EOL> expired_tmp_urns . append ( tmp_obj . urn ) <EOL> aff4 . FACTORY . MultiDelete ( expired_tmp_urns , token = self . token ) <EOL> self . HeartBeat ( ) <EOL> class CleanInactiveClients ( cronjobs . SystemCronFlow ) : <EOL> """<STR_LIT>""" <EOL> frequency = rdfvalue . Duration ( "<STR_LIT>" ) <EOL> lifetime = rdfvalue . Duration ( "<STR_LIT>" ) <EOL> @ flow . StateHandler ( ) <EOL> def Start ( self ) : <EOL> inactive_client_ttl = config_lib . CONFIG [ "<STR_LIT>" ] <EOL> if not inactive_client_ttl : <EOL> self . Log ( "<STR_LIT>" ) <EOL> return <EOL> exception_label = config_lib . CONFIG [ <EOL> "<STR_LIT>" ] <EOL> index = aff4 . FACTORY . Create ( client_index . MAIN_INDEX , <EOL> aff4_type = "<STR_LIT>" , <EOL> mode = "<STR_LIT>" , <EOL> token = self . token ) <EOL> client_urns = index . LookupClients ( [ "<STR_LIT:.>" ] ) <EOL> deadline = rdfvalue . RDFDatetime ( ) . Now ( ) - inactive_client_ttl <EOL> for client_group in utils . Grouper ( client_urns , <NUM_LIT:1000> ) : <EOL> inactive_client_urns = [ ] <EOL> for client in aff4 . FACTORY . MultiOpen ( client_group , mode = "<STR_LIT:r>" , <EOL> aff4_type = "<STR_LIT>" , <EOL> token = self . token ) : <EOL> if exception_label in client . GetLabelsNames ( ) : <EOL> continue <EOL> if client . Get ( client . Schema . LAST ) < deadline : <EOL> inactive_client_urns . append ( client . urn ) <EOL> aff4 . FACTORY . MultiDelete ( inactive_client_urns , token = self . token ) <EOL> self . HeartBeat ( ) </s>
<s> """<STR_LIT>""" <EOL> import stat <EOL> from grr . lib import aff4 <EOL> from grr . lib import flow <EOL> from grr . lib import utils <EOL> from grr . lib . flows . general import filesystem <EOL> from grr . lib . flows . general import fingerprint <EOL> from grr . lib . flows . general import transfer <EOL> from grr . lib . rdfvalues import client as rdf_client <EOL> from grr . lib . rdfvalues import paths as rdf_paths <EOL> from grr . lib . rdfvalues import structs as rdf_structs <EOL> from grr . proto import flows_pb2 <EOL> class FileFinderModificationTimeCondition ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderModificationTimeCondition <EOL> class FileFinderAccessTimeCondition ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderAccessTimeCondition <EOL> class FileFinderInodeChangeTimeCondition ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderInodeChangeTimeCondition <EOL> class FileFinderSizeCondition ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderSizeCondition <EOL> class FileFinderContentsRegexMatchCondition ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderContentsRegexMatchCondition <EOL> class FileFinderContentsLiteralMatchCondition ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderContentsLiteralMatchCondition <EOL> class FileFinderCondition ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderCondition <EOL> class FileFinderDownloadActionOptions ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderDownloadActionOptions <EOL> class FileFinderAction ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderAction <EOL> class FileFinderArgs ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderArgs <EOL> class FileFinderResult ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FileFinderResult <EOL> class FileFinder ( transfer . MultiGetFileMixin , <EOL> fingerprint . FingerprintFileMixin , <EOL> filesystem . GlobMixin , <EOL> flow . GRRFlow ) : <EOL> """<STR_LIT>""" <EOL> friendly_name = "<STR_LIT>" <EOL> category = "<STR_LIT>" <EOL> args_type = FileFinderArgs <EOL> behaviours = flow . GRRFlow . behaviours + "<STR_LIT>" <EOL> @ classmethod <EOL> def GetDefaultArgs ( cls , token = None ) : <EOL> _ = token <EOL> return cls . args_type ( paths = [ r"<STR_LIT>" ] ) <EOL> def Initialize ( self ) : <EOL> super ( FileFinder , self ) . Initialize ( ) <EOL> type_enum = FileFinderCondition . Type <EOL> self . condition_handlers = { <EOL> type_enum . MODIFICATION_TIME : ( self . ModificationTimeCondition , <NUM_LIT:0> ) , <EOL> type_enum . ACCESS_TIME : ( self . AccessTimeCondition , <NUM_LIT:0> ) , <EOL> type_enum . INODE_CHANGE_TIME : ( self . InodeChangeTimeCondition , <NUM_LIT:0> ) , <EOL> type_enum . SIZE : ( self . SizeCondition , <NUM_LIT:0> ) , <EOL> type_enum . CONTENTS_REGEX_MATCH : ( self . ContentsRegexMatchCondition , <NUM_LIT:1> ) , <EOL> type_enum . CONTENTS_LITERAL_MATCH : ( <EOL> self . ContentsLiteralMatchCondition , <NUM_LIT:1> ) <EOL> } <EOL> def _ConditionWeight ( self , condition_options ) : <EOL> _ , condition_weight = self . condition_handlers [ <EOL> condition_options . condition_type ] <EOL> return condition_weight <EOL> @ flow . StateHandler ( ) <EOL> def Start ( self ) : <EOL> """<STR_LIT>""" <EOL> super ( FileFinder , self ) . Start ( ) <EOL> if not self . args . paths : <EOL> return <EOL> self . state . Register ( "<STR_LIT>" , <NUM_LIT:0> ) <EOL> self . state . Register ( "<STR_LIT>" , <EOL> sorted ( self . args . conditions , key = self . _ConditionWeight ) ) <EOL> self . state . file_size = self . args . file_size <EOL> if self . args . pathtype in ( rdf_paths . PathSpec . PathType . MEMORY , <EOL> rdf_paths . PathSpec . PathType . REGISTRY ) : <EOL> self . args . no_file_type_check = True <EOL> if self . args . pathtype == rdf_paths . PathSpec . PathType . MEMORY : <EOL> for path in self . args . paths : <EOL> pathspec = rdf_paths . PathSpec ( <EOL> path = utils . SmartUnicode ( path ) , <EOL> pathtype = rdf_paths . PathSpec . PathType . MEMORY ) <EOL> aff4path = aff4 . AFF4Object . VFSGRRClient . PathspecToURN ( <EOL> pathspec , self . client_id ) <EOL> stat_entry = rdf_client . StatEntry ( aff4path = aff4path , pathspec = pathspec ) <EOL> self . ApplyCondition ( FileFinderResult ( stat_entry = stat_entry ) , <EOL> condition_index = <NUM_LIT:0> ) <EOL> else : <EOL> self . GlobForPaths ( self . args . paths , pathtype = self . args . pathtype , <EOL> no_file_type_check = self . args . no_file_type_check ) <EOL> def GlobReportMatch ( self , response ) : <EOL> """<STR_LIT>""" <EOL> super ( FileFinder , self ) . GlobReportMatch ( response ) <EOL> self . ApplyCondition ( FileFinderResult ( stat_entry = response ) , <EOL> condition_index = <NUM_LIT:0> ) <EOL> def ModificationTimeCondition ( self , response , condition_options , <EOL> condition_index ) : <EOL> """<STR_LIT>""" <EOL> settings = condition_options . modification_time <EOL> if ( settings . min_last_modified_time . AsSecondsFromEpoch ( ) <= <EOL> response . stat_entry . st_mtime <= <EOL> settings . max_last_modified_time . AsSecondsFromEpoch ( ) ) : <EOL> self . ApplyCondition ( response , condition_index + <NUM_LIT:1> ) <EOL> def AccessTimeCondition ( self , response , condition_options , condition_index ) : <EOL> """<STR_LIT>""" <EOL> settings = condition_options . access_time <EOL> if ( settings . min_last_access_time . AsSecondsFromEpoch ( ) <= <EOL> response . stat_entry . st_atime <= <EOL> settings . max_last_access_time . AsSecondsFromEpoch ( ) ) : <EOL> self . ApplyCondition ( response , condition_index + <NUM_LIT:1> ) <EOL> def InodeChangeTimeCondition ( self , response , condition_options , <EOL> condition_index ) : <EOL> """<STR_LIT>""" <EOL> settings = condition_options . inode_change_time <EOL> if ( settings . min_last_inode_change_time . AsSecondsFromEpoch ( ) <= <EOL> response . stat_entry . st_ctime <= <EOL> settings . max_last_inode_change_time . AsSecondsFromEpoch ( ) ) : <EOL> self . ApplyCondition ( response , condition_index + <NUM_LIT:1> ) <EOL> def SizeCondition ( self , response , condition_options , condition_index ) : <EOL> """<STR_LIT>""" <EOL> if not ( self . args . no_file_type_check or <EOL> stat . S_ISREG ( response . stat_entry . st_mode ) ) : <EOL> return <EOL> if ( condition_options . size . min_file_size <= <EOL> response . stat_entry . st_size <= <EOL> condition_options . size . max_file_size ) : <EOL> self . ApplyCondition ( response , condition_index + <NUM_LIT:1> ) <EOL> def ContentsRegexMatchCondition ( self , response , condition_options , <EOL> condition_index ) : <EOL> """<STR_LIT>""" <EOL> if not ( self . args . no_file_type_check or <EOL> stat . S_ISREG ( response . stat_entry . st_mode ) ) : <EOL> return <EOL> options = condition_options . contents_regex_match <EOL> grep_spec = rdf_client . GrepSpec ( <EOL> target = response . stat_entry . pathspec , <EOL> regex = options . regex , <EOL> mode = options . mode , <EOL> start_offset = options . start_offset , <EOL> length = options . length , <EOL> bytes_before = options . bytes_before , <EOL> bytes_after = options . bytes_after ) <EOL> self . CallClient ( <EOL> "<STR_LIT>" , request = grep_spec , next_state = "<STR_LIT>" , <EOL> request_data = dict ( <EOL> original_result = response , <EOL> condition_index = condition_index + <NUM_LIT:1> ) ) <EOL> def ContentsLiteralMatchCondition ( self , response , condition_options , <EOL> condition_index ) : <EOL> """<STR_LIT>""" <EOL> if not ( self . args . no_file_type_check or <EOL> stat . S_ISREG ( response . stat_entry . st_mode ) ) : <EOL> return <EOL> options = condition_options . contents_literal_match <EOL> grep_spec = rdf_client . GrepSpec ( <EOL> target = response . stat_entry . pathspec , <EOL> literal = options . literal , <EOL> mode = options . mode , <EOL> start_offset = options . start_offset , <EOL> length = options . length , <EOL> bytes_before = options . bytes_before , <EOL> bytes_after = options . bytes_after , <EOL> xor_in_key = options . xor_in_key , <EOL> xor_out_key = options . xor_out_key ) <EOL> self . CallClient ( <EOL> "<STR_LIT>" , request = grep_spec , next_state = "<STR_LIT>" , <EOL> request_data = dict ( <EOL> original_result = response , <EOL> condition_index = condition_index + <NUM_LIT:1> ) ) <EOL> @ flow . StateHandler ( ) <EOL> def ProcessGrep ( self , responses ) : <EOL> for response in responses : <EOL> if "<STR_LIT>" not in responses . request_data : <EOL> raise RuntimeError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> condition_index = responses . request_data [ "<STR_LIT>" ] <EOL> original_result = responses . request_data [ "<STR_LIT>" ] <EOL> original_result . matches . append ( response ) <EOL> self . ApplyCondition ( original_result , condition_index ) <EOL> def ApplyCondition ( self , response , condition_index ) : <EOL> """<STR_LIT>""" <EOL> if condition_index >= len ( self . state . sorted_conditions ) : <EOL> self . ProcessAction ( response ) <EOL> else : <EOL> condition_options = self . state . sorted_conditions [ condition_index ] <EOL> condition_handler , _ = self . condition_handlers [ <EOL> condition_options . condition_type ] <EOL> condition_handler ( response , condition_options , condition_index ) <EOL> def ProcessAction ( self , response ) : <EOL> """<STR_LIT>""" <EOL> action = self . state . args . action . action_type <EOL> if action == FileFinderAction . Action . STAT : <EOL> self . state . files_found += <NUM_LIT:1> <EOL> self . SendReply ( response ) <EOL> elif ( self . args . no_file_type_check or <EOL> stat . S_ISREG ( response . stat_entry . st_mode ) ) : <EOL> self . state . files_found += <NUM_LIT:1> <EOL> if action == FileFinderAction . Action . HASH : <EOL> self . FingerprintFile ( response . stat_entry . pathspec , <EOL> request_data = dict ( original_result = response ) ) <EOL> elif action == FileFinderAction . Action . DOWNLOAD : <EOL> file_size = response . stat_entry . st_size <EOL> if file_size > self . args . action . download . max_size : <EOL> self . Log ( "<STR_LIT>" , <EOL> response . stat_entry . pathspec . CollapsePath ( ) , file_size ) <EOL> self . FingerprintFile ( response . stat_entry . pathspec , <EOL> request_data = dict ( original_result = response ) ) <EOL> else : <EOL> self . StartFileFetch ( response . stat_entry . pathspec , <EOL> request_data = dict ( original_result = response ) ) <EOL> def ReceiveFileFingerprint ( self , urn , hash_obj , request_data = None ) : <EOL> """<STR_LIT>""" <EOL> if "<STR_LIT>" in request_data : <EOL> result = request_data [ "<STR_LIT>" ] <EOL> result . hash_entry = hash_obj <EOL> self . SendReply ( result ) <EOL> else : <EOL> raise RuntimeError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> def ReceiveFetchedFile ( self , unused_stat_entry , file_hash , <EOL> request_data = None ) : <EOL> """<STR_LIT>""" <EOL> if "<STR_LIT>" not in request_data : <EOL> raise RuntimeError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> result = request_data [ "<STR_LIT>" ] <EOL> result . hash_entry = file_hash <EOL> self . SendReply ( result ) <EOL> @ flow . StateHandler ( ) <EOL> def End ( self , responses ) : <EOL> super ( FileFinder , self ) . End ( ) <EOL> self . Log ( "<STR_LIT>" , self . state . files_found ) <EOL> if self . runner . output is not None : <EOL> urn = self . runner . output . urn <EOL> else : <EOL> urn = self . client_id <EOL> self . Notify ( "<STR_LIT>" , urn , <EOL> "<STR_LIT>" % self . state . files_found ) </s>
<s> """<STR_LIT>""" <EOL> import datetime <EOL> import os <EOL> from grr . lib import aff4 <EOL> from grr . lib import flow <EOL> from grr . lib import flow_utils <EOL> from grr . lib import utils <EOL> from grr . lib . flows . general import file_finder <EOL> from grr . lib . rdfvalues import structs as rdf_structs <EOL> from grr . parsers import chrome_history <EOL> from grr . parsers import firefox3_history <EOL> from grr . proto import flows_pb2 <EOL> class ChromeHistoryArgs ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . ChromeHistoryArgs <EOL> class ChromeHistory ( flow . GRRFlow ) : <EOL> """<STR_LIT>""" <EOL> category = "<STR_LIT>" <EOL> args_type = ChromeHistoryArgs <EOL> behaviours = flow . GRRFlow . behaviours + "<STR_LIT>" <EOL> @ flow . StateHandler ( next_state = "<STR_LIT>" ) <EOL> def Start ( self ) : <EOL> """<STR_LIT>""" <EOL> self . state . Register ( "<STR_LIT>" , <NUM_LIT:0> ) <EOL> self . state . Register ( "<STR_LIT>" , [ ] ) <EOL> if self . state . args . history_path : <EOL> self . state . history_paths . append ( self . state . args . history_path ) <EOL> if self . runner . output is not None : <EOL> self . runner . output = aff4 . FACTORY . Create ( <EOL> self . runner . output . urn , "<STR_LIT>" , token = self . token ) <EOL> if not self . state . history_paths : <EOL> self . state . history_paths = self . GuessHistoryPaths ( <EOL> self . state . args . username ) <EOL> if not self . state . history_paths : <EOL> raise flow . FlowError ( "<STR_LIT>" ) <EOL> filenames = [ "<STR_LIT>" ] <EOL> if self . state . args . get_archive : <EOL> filenames . append ( "<STR_LIT>" ) <EOL> for path in self . state . history_paths : <EOL> for fname in filenames : <EOL> self . CallFlow ( <EOL> "<STR_LIT>" , <EOL> paths = [ os . path . join ( path , fname ) ] , <EOL> pathtype = self . state . args . pathtype , <EOL> action = file_finder . FileFinderAction ( <EOL> action_type = file_finder . FileFinderAction . Action . DOWNLOAD ) , <EOL> next_state = "<STR_LIT>" ) <EOL> @ flow . StateHandler ( ) <EOL> def ParseFiles ( self , responses ) : <EOL> """<STR_LIT>""" <EOL> if responses : <EOL> for response in responses : <EOL> fd = aff4 . FACTORY . Open ( response . stat_entry . aff4path , token = self . token ) <EOL> hist = chrome_history . ChromeParser ( fd ) <EOL> count = <NUM_LIT:0> <EOL> for epoch64 , dtype , url , dat1 , dat2 , dat3 in hist . Parse ( ) : <EOL> count += <NUM_LIT:1> <EOL> str_entry = "<STR_LIT>" % ( <EOL> datetime . datetime . utcfromtimestamp ( epoch64 / <NUM_LIT> ) , url , <EOL> dat1 , dat2 , dat3 , dtype ) <EOL> if self . runner . output is not None : <EOL> self . runner . output . write ( utils . SmartStr ( str_entry ) + "<STR_LIT:\n>" ) <EOL> self . Log ( "<STR_LIT>" , count , <EOL> self . state . args . username , <EOL> response . stat_entry . pathspec . Basename ( ) ) <EOL> self . state . hist_count += count <EOL> def GuessHistoryPaths ( self , username ) : <EOL> """<STR_LIT>""" <EOL> client = aff4 . FACTORY . Open ( self . client_id , token = self . token ) <EOL> system = client . Get ( client . Schema . SYSTEM ) <EOL> user_info = flow_utils . GetUserInfo ( client , username ) <EOL> if not user_info : <EOL> self . Error ( "<STR_LIT>" . format ( username ) ) <EOL> return <EOL> paths = [ ] <EOL> if system == "<STR_LIT>" : <EOL> path = ( "<STR_LIT>" ) <EOL> for sw_path in [ "<STR_LIT>" , "<STR_LIT>" ] : <EOL> paths . append ( path . format ( <EOL> app_data = user_info . special_folders . local_app_data , sw = sw_path ) ) <EOL> elif system == "<STR_LIT>" : <EOL> path = "<STR_LIT>" <EOL> for sw_path in [ "<STR_LIT>" , "<STR_LIT>" ] : <EOL> paths . append ( path . format ( homedir = user_info . homedir , sw = sw_path ) ) <EOL> elif system == "<STR_LIT>" : <EOL> path = "<STR_LIT>" <EOL> for sw_path in [ "<STR_LIT>" , "<STR_LIT>" ] : <EOL> paths . append ( path . format ( homedir = user_info . homedir , sw = sw_path ) ) <EOL> else : <EOL> raise OSError ( "<STR_LIT>" ) <EOL> return paths <EOL> class FirefoxHistoryArgs ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . FirefoxHistoryArgs <EOL> class FirefoxHistory ( flow . GRRFlow ) : <EOL> """<STR_LIT>""" <EOL> category = "<STR_LIT>" <EOL> args_type = FirefoxHistoryArgs <EOL> behaviours = flow . GRRFlow . behaviours + "<STR_LIT>" <EOL> @ flow . StateHandler ( next_state = "<STR_LIT>" ) <EOL> def Start ( self ) : <EOL> """<STR_LIT>""" <EOL> self . state . Register ( "<STR_LIT>" , <NUM_LIT:0> ) <EOL> self . state . Register ( "<STR_LIT>" , [ ] ) <EOL> if self . args . history_path : <EOL> self . state . history_paths . append ( self . args . history_path ) <EOL> else : <EOL> self . state . history_paths = self . GuessHistoryPaths ( self . args . username ) <EOL> if not self . state . history_paths : <EOL> raise flow . FlowError ( "<STR_LIT>" ) <EOL> if self . runner . output is not None : <EOL> self . runner . output = aff4 . FACTORY . Create ( <EOL> self . runner . output . urn , "<STR_LIT>" , token = self . token ) <EOL> filename = "<STR_LIT>" <EOL> for path in self . state . history_paths : <EOL> self . CallFlow ( <EOL> "<STR_LIT>" , <EOL> paths = [ os . path . join ( path , "<STR_LIT>" , filename ) ] , <EOL> pathtype = self . state . args . pathtype , <EOL> action = file_finder . FileFinderAction ( <EOL> action_type = file_finder . FileFinderAction . Action . DOWNLOAD ) , <EOL> next_state = "<STR_LIT>" ) <EOL> @ flow . StateHandler ( ) <EOL> def ParseFiles ( self , responses ) : <EOL> """<STR_LIT>""" <EOL> if responses : <EOL> for response in responses : <EOL> fd = aff4 . FACTORY . Open ( response . stat_entry . aff4path , token = self . token ) <EOL> hist = firefox3_history . Firefox3History ( fd ) <EOL> count = <NUM_LIT:0> <EOL> for epoch64 , dtype , url , dat1 , in hist . Parse ( ) : <EOL> count += <NUM_LIT:1> <EOL> str_entry = "<STR_LIT>" % ( <EOL> datetime . datetime . utcfromtimestamp ( epoch64 / <NUM_LIT> ) , url , <EOL> dat1 , dtype ) <EOL> if self . runner . output is not None : <EOL> self . runner . output . write ( utils . SmartStr ( str_entry ) + "<STR_LIT:\n>" ) <EOL> self . Log ( "<STR_LIT>" , count , <EOL> self . args . username , response . stat_entry . pathspec . Basename ( ) ) <EOL> self . state . hist_count += count <EOL> def GuessHistoryPaths ( self , username ) : <EOL> """<STR_LIT>""" <EOL> fd = aff4 . FACTORY . Open ( self . client_id , token = self . token ) <EOL> system = fd . Get ( fd . Schema . SYSTEM ) <EOL> user_info = flow_utils . GetUserInfo ( fd , username ) <EOL> if not user_info : <EOL> self . Error ( "<STR_LIT>" . format ( username ) ) <EOL> return <EOL> paths = [ ] <EOL> if system == "<STR_LIT>" : <EOL> path = "<STR_LIT>" <EOL> paths . append ( path . format ( <EOL> app_data = user_info . special_folders . app_data ) ) <EOL> elif system == "<STR_LIT>" : <EOL> path = "<STR_LIT>" <EOL> paths . append ( path . format ( homedir = user_info . homedir ) ) <EOL> elif system == "<STR_LIT>" : <EOL> path = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> paths . append ( path . format ( homedir = user_info . homedir ) ) <EOL> else : <EOL> raise OSError ( "<STR_LIT>" ) <EOL> return paths <EOL> BROWSER_PATHS = { <EOL> "<STR_LIT>" : { <EOL> "<STR_LIT>" : [ "<STR_LIT>" ] , <EOL> "<STR_LIT>" : [ "<STR_LIT>" , <EOL> "<STR_LIT>" ] <EOL> } , <EOL> "<STR_LIT>" : { <EOL> "<STR_LIT>" : [ "<STR_LIT>" , <EOL> "<STR_LIT>" ] , <EOL> "<STR_LIT>" : [ "<STR_LIT>" ] , <EOL> "<STR_LIT>" : [ "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" ] <EOL> } , <EOL> "<STR_LIT>" : { <EOL> "<STR_LIT>" : [ "<STR_LIT>" ] , <EOL> "<STR_LIT>" : [ "<STR_LIT>" , <EOL> "<STR_LIT>" ] <EOL> } <EOL> } <EOL> class CacheGrepArgs ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = flows_pb2 . CacheGrepArgs <EOL> class CacheGrep ( flow . GRRFlow ) : <EOL> """<STR_LIT>""" <EOL> category = "<STR_LIT>" <EOL> args_type = CacheGrepArgs <EOL> behaviours = flow . GRRFlow . behaviours + "<STR_LIT>" <EOL> @ flow . StateHandler ( next_state = "<STR_LIT>" ) <EOL> def Start ( self ) : <EOL> """<STR_LIT>""" <EOL> client = aff4 . FACTORY . Open ( self . client_id , token = self . token ) <EOL> system = client . Get ( client . Schema . SYSTEM ) <EOL> paths = BROWSER_PATHS . get ( system ) <EOL> self . state . Register ( "<STR_LIT>" , [ ] ) <EOL> if self . args . check_chrome : <EOL> self . state . all_paths += paths . get ( "<STR_LIT>" , [ ] ) <EOL> if self . args . check_ie : <EOL> self . state . all_paths += paths . get ( "<STR_LIT>" , [ ] ) <EOL> if self . args . check_firefox : <EOL> self . state . all_paths += paths . get ( "<STR_LIT>" , [ ] ) <EOL> if not self . state . all_paths : <EOL> raise flow . FlowError ( "<STR_LIT>" % system ) <EOL> self . state . Register ( "<STR_LIT>" , [ ] ) <EOL> for user in self . args . grep_users : <EOL> user_info = flow_utils . GetUserInfo ( client , user ) <EOL> if not user_info : <EOL> raise flow . FlowError ( "<STR_LIT>" % user ) <EOL> self . state . users . append ( user_info ) <EOL> self . CallState ( next_state = "<STR_LIT>" ) <EOL> @ flow . StateHandler ( next_state = "<STR_LIT>" ) <EOL> def StartRequests ( self ) : <EOL> """<STR_LIT>""" <EOL> client = aff4 . FACTORY . Open ( self . client_id , token = self . token ) <EOL> if self . runner . output is not None : <EOL> self . runner . output . Set ( <EOL> self . runner . output . Schema . DESCRIPTION ( "<STR_LIT>" . format ( <EOL> self . args . data_regex ) ) ) <EOL> usernames = [ <EOL> "<STR_LIT>" % ( u . userdomain , u . username ) for u in self . state . users ] <EOL> usernames = [ u . lstrip ( "<STR_LIT:\\>" ) for u in usernames ] <EOL> condition = file_finder . FileFinderCondition ( <EOL> condition_type = <EOL> file_finder . FileFinderCondition . Type . CONTENTS_REGEX_MATCH , <EOL> contents_regex_match = file_finder . FileFinderContentsRegexMatchCondition ( <EOL> regex = self . args . data_regex , <EOL> mode = <EOL> file_finder . FileFinderContentsRegexMatchCondition . Mode . FIRST_HIT ) ) <EOL> for path in self . state . all_paths : <EOL> full_paths = flow_utils . InterpolatePath ( path , client , users = usernames ) <EOL> for full_path in full_paths : <EOL> self . CallFlow ( <EOL> "<STR_LIT>" , <EOL> paths = [ os . path . join ( full_path , "<STR_LIT>" ) ] , <EOL> pathtype = self . state . args . pathtype , <EOL> conditions = [ condition ] , <EOL> action = file_finder . FileFinderAction ( <EOL> action_type = file_finder . FileFinderAction . Action . DOWNLOAD ) , <EOL> next_state = "<STR_LIT>" ) <EOL> @ flow . StateHandler ( ) <EOL> def HandleResults ( self , responses ) : <EOL> """<STR_LIT>""" <EOL> for response in responses : <EOL> self . SendReply ( response . stat_entry ) </s>
<s> """<STR_LIT>""" </s>
<s> """<STR_LIT>""" <EOL> import re <EOL> from grr . lib import rdfvalue <EOL> from grr . lib import type_info <EOL> from grr . lib import utils <EOL> from grr . lib . rdfvalues import aff4_rdfvalues <EOL> from grr . lib . rdfvalues import test_base <EOL> class AFF4ObjectLabelTest ( test_base . RDFValueTestCase ) : <EOL> """<STR_LIT>""" <EOL> rdfvalue_class = aff4_rdfvalues . AFF4ObjectLabel <EOL> def GenerateSample ( self , number = <NUM_LIT:0> ) : <EOL> return aff4_rdfvalues . AFF4ObjectLabel ( <EOL> name = "<STR_LIT>" % number , <EOL> owner = "<STR_LIT:test>" , <EOL> timestamp = rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) ) <EOL> def testAlphanumericCharactersAreAllowed ( self ) : <EOL> aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , owner = "<STR_LIT:test>" ) <EOL> def testDotIsAllowed ( self ) : <EOL> aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , owner = "<STR_LIT:test>" ) <EOL> def testColonIsAllowed ( self ) : <EOL> aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , owner = "<STR_LIT:test>" ) <EOL> def testForwardSlashIsAllowed ( self ) : <EOL> aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , owner = "<STR_LIT:test>" ) <EOL> def testEmptyStringNameIsNotAllowed ( self ) : <EOL> self . assertRaises ( type_info . TypeValueError , aff4_rdfvalues . AFF4ObjectLabel , <EOL> name = "<STR_LIT>" , <EOL> owner = "<STR_LIT:test>" ) <EOL> def testNonAlphanumericsDotsColonOrForwardSlashAreNotAllowed ( self ) : <EOL> self . assertRaises ( type_info . TypeValueError , aff4_rdfvalues . AFF4ObjectLabel , <EOL> name = "<STR_LIT>" ) <EOL> self . assertRaises ( type_info . TypeValueError , aff4_rdfvalues . AFF4ObjectLabel , <EOL> name = "<STR_LIT>" ) <EOL> self . assertRaises ( type_info . TypeValueError , aff4_rdfvalues . AFF4ObjectLabel , <EOL> name = "<STR_LIT>" ) <EOL> self . assertRaises ( type_info . TypeValueError , aff4_rdfvalues . AFF4ObjectLabel , <EOL> name = "<STR_LIT>" ) <EOL> class AFF4ObjectLabelsListTest ( test_base . RDFValueTestCase ) : <EOL> """<STR_LIT>""" <EOL> rdfvalue_class = aff4_rdfvalues . AFF4ObjectLabelsList <EOL> def GenerateSample ( self , number = <NUM_LIT:0> ) : <EOL> label1 = aff4_rdfvalues . AFF4ObjectLabel ( <EOL> name = "<STR_LIT>" % number , <EOL> owner = "<STR_LIT:test>" , <EOL> timestamp = rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) ) <EOL> label2 = aff4_rdfvalues . AFF4ObjectLabel ( <EOL> name = "<STR_LIT>" % number , <EOL> owner = "<STR_LIT:test>" , <EOL> timestamp = rdfvalue . RDFDatetime ( ) . FromSecondsFromEpoch ( <NUM_LIT> ) ) <EOL> return aff4_rdfvalues . AFF4ObjectLabelsList ( labels = [ label1 , label2 ] ) <EOL> def testAddLabelAddsLabelWithSameNameButDifferentOwner ( self ) : <EOL> labels_list = aff4_rdfvalues . AFF4ObjectLabelsList ( ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:foo>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> self . assertEqual ( len ( labels_list . labels ) , <NUM_LIT:1> ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:foo>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> self . assertEqual ( len ( labels_list . labels ) , <NUM_LIT:2> ) <EOL> def testAddLabelDoesNotAddLabelWithSameNameAndOwner ( self ) : <EOL> labels_list = aff4_rdfvalues . AFF4ObjectLabelsList ( ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:foo>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> self . assertEqual ( len ( labels_list . labels ) , <NUM_LIT:1> ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:foo>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> self . assertEqual ( len ( labels_list . labels ) , <NUM_LIT:1> ) <EOL> def testStringifiedValueIsLabelsNamesWithoutOwners ( self ) : <EOL> labels_list = aff4_rdfvalues . AFF4ObjectLabelsList ( ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:bar>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:foo>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> self . assertEqual ( utils . SmartStr ( labels_list ) , "<STR_LIT>" ) <EOL> def testStringifiedRepresentationIsSorted ( self ) : <EOL> labels_list = aff4_rdfvalues . AFF4ObjectLabelsList ( ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:foo>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:bar>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> self . assertEqual ( utils . SmartStr ( labels_list ) , "<STR_LIT>" ) <EOL> def testStringifiedValueDoesNotHaveDuplicates ( self ) : <EOL> labels_list = aff4_rdfvalues . AFF4ObjectLabelsList ( ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:foo>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:bar>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:foo>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> self . assertEqual ( utils . SmartStr ( labels_list ) , "<STR_LIT>" ) <EOL> def testRegexForStringifiedValueMatchMatchesLabelsInList ( self ) : <EOL> labels_list = aff4_rdfvalues . AFF4ObjectLabelsList ( ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> self . assertTrue ( re . match ( <EOL> aff4_rdfvalues . AFF4ObjectLabelsList . RegexForStringifiedValueMatch ( <EOL> "<STR_LIT>" ) , str ( labels_list ) ) ) <EOL> self . assertTrue ( re . match ( <EOL> aff4_rdfvalues . AFF4ObjectLabelsList . RegexForStringifiedValueMatch ( <EOL> "<STR_LIT>" ) , str ( labels_list ) ) ) <EOL> self . assertTrue ( re . match ( <EOL> aff4_rdfvalues . AFF4ObjectLabelsList . RegexForStringifiedValueMatch ( <EOL> "<STR_LIT>" ) , str ( labels_list ) ) ) <EOL> self . assertTrue ( re . match ( <EOL> aff4_rdfvalues . AFF4ObjectLabelsList . RegexForStringifiedValueMatch ( <EOL> "<STR_LIT>" ) , str ( labels_list ) ) ) <EOL> def testRegexForStringifiedValueDoesNotMatchLabelsNotInList ( self ) : <EOL> labels_list = aff4_rdfvalues . AFF4ObjectLabelsList ( ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> self . assertFalse ( re . match ( <EOL> aff4_rdfvalues . AFF4ObjectLabelsList . RegexForStringifiedValueMatch ( "<STR_LIT:e>" ) , <EOL> str ( labels_list ) ) ) <EOL> self . assertFalse ( re . match ( <EOL> aff4_rdfvalues . AFF4ObjectLabelsList . RegexForStringifiedValueMatch ( "<STR_LIT>" ) , <EOL> str ( labels_list ) ) ) <EOL> self . assertFalse ( re . match ( <EOL> aff4_rdfvalues . AFF4ObjectLabelsList . RegexForStringifiedValueMatch ( <EOL> "<STR_LIT>" ) , str ( labels_list ) ) ) <EOL> self . assertFalse ( re . match ( <EOL> aff4_rdfvalues . AFF4ObjectLabelsList . RegexForStringifiedValueMatch ( <EOL> "<STR_LIT>" ) , str ( labels_list ) ) ) <EOL> def testGetSortedLabelSet ( self ) : <EOL> labels_list = aff4_rdfvalues . AFF4ObjectLabelsList ( ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT:foo>" , <EOL> owner = "<STR_LIT:test>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> labels_list . AddLabel ( aff4_rdfvalues . AFF4ObjectLabel ( name = "<STR_LIT>" , <EOL> owner = "<STR_LIT>" ) ) <EOL> self . assertItemsEqual ( labels_list . GetLabelNames ( ) , [ "<STR_LIT:foo>" , "<STR_LIT>" , "<STR_LIT>" ] ) <EOL> self . assertItemsEqual ( labels_list . GetLabelNames ( owner = "<STR_LIT>" ) , [ "<STR_LIT>" , <EOL> "<STR_LIT>" ] ) <EOL> self . assertEqual ( labels_list . GetLabelNames ( owner = "<STR_LIT>" ) , [ ] ) </s>
<s> """<STR_LIT>""" <EOL> import re <EOL> import urlparse <EOL> from grr . lib import config_lib <EOL> from grr . lib import rdfvalue <EOL> from grr . lib import type_info <EOL> from grr . lib . rdfvalues import structs as rdf_structs <EOL> from grr . proto import jobs_pb2 <EOL> from grr . proto import sysinfo_pb2 <EOL> class RegularExpression ( rdfvalue . RDFString ) : <EOL> """<STR_LIT>""" <EOL> context_help_url = "<STR_LIT>" <EOL> def ParseFromString ( self , value ) : <EOL> super ( RegularExpression , self ) . ParseFromString ( value ) <EOL> try : <EOL> self . _regex = re . compile ( self . _value , flags = re . I | re . S | re . M ) <EOL> except re . error : <EOL> raise type_info . TypeValueError ( "<STR_LIT>" ) <EOL> def Search ( self , text ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( text , rdfvalue . RDFString ) : <EOL> text = str ( text ) <EOL> return self . _regex . search ( text ) <EOL> def Match ( self , text ) : <EOL> if isinstance ( text , rdfvalue . RDFString ) : <EOL> text = str ( text ) <EOL> return self . _regex . match ( text ) <EOL> def FindIter ( self , text ) : <EOL> if isinstance ( text , rdfvalue . RDFString ) : <EOL> text = str ( text ) <EOL> return self . _regex . finditer ( text ) <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT>" % self . _value <EOL> class LiteralExpression ( rdfvalue . RDFBytes ) : <EOL> """<STR_LIT>""" <EOL> context_help_url = "<STR_LIT>" <EOL> class EmailAddress ( rdfvalue . RDFString ) : <EOL> """<STR_LIT>""" <EOL> _EMAIL_REGEX = re . compile ( r"<STR_LIT>" ) <EOL> def ParseFromString ( self , value ) : <EOL> super ( EmailAddress , self ) . ParseFromString ( value ) <EOL> self . _match = self . _EMAIL_REGEX . match ( self . _value ) <EOL> if not self . _match : <EOL> raise ValueError ( "<STR_LIT>" % self . _value ) <EOL> class DomainEmailAddress ( EmailAddress ) : <EOL> """<STR_LIT>""" <EOL> def ParseFromString ( self , value ) : <EOL> super ( DomainEmailAddress , self ) . ParseFromString ( value ) <EOL> domain = config_lib . CONFIG [ "<STR_LIT>" ] <EOL> if domain and self . _match . group ( <NUM_LIT:1> ) != domain : <EOL> raise ValueError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( self . _match . group ( <NUM_LIT:1> ) , domain ) ) <EOL> class AuthenticodeSignedData ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = jobs_pb2 . AuthenticodeSignedData <EOL> class PersistenceFile ( rdf_structs . RDFProtoStruct ) : <EOL> protobuf = jobs_pb2 . PersistenceFile <EOL> class URI ( rdf_structs . RDFProtoStruct ) : <EOL> """<STR_LIT>""" <EOL> protobuf = sysinfo_pb2 . URI <EOL> def ParseFromString ( self , value ) : <EOL> url = urlparse . urlparse ( value ) <EOL> if url . scheme : <EOL> self . transport = url . scheme <EOL> if url . netloc : <EOL> self . host = url . netloc <EOL> if url . path : <EOL> self . path = url . path <EOL> if url . query : <EOL> self . query = url . query <EOL> if url . fragment : <EOL> self . fragment = url . fragment <EOL> def SerializeToString ( self ) : <EOL> url = ( self . transport , self . host , self . path , self . query , self . fragment ) <EOL> return str ( urlparse . urlunsplit ( url ) ) </s>
<s> """<STR_LIT>""" <EOL> from grr . lib import flags <EOL> from grr . lib import test_lib <EOL> from grr . lib import timeseries <EOL> class TimeseriesTest ( test_lib . GRRBaseTest ) : <EOL> def makeSeries ( self ) : <EOL> s = timeseries . Timeseries ( ) <EOL> for i in range ( <NUM_LIT:1> , <NUM_LIT> ) : <EOL> s . Append ( i , ( i + <NUM_LIT:5> ) * <NUM_LIT> ) <EOL> return s <EOL> def testAppendFilterRange ( self ) : <EOL> s = self . makeSeries ( ) <EOL> self . assertEqual ( <NUM_LIT:100> , len ( s . data ) ) <EOL> self . assertEqual ( [ <NUM_LIT:1> , <NUM_LIT> ] , s . data [ <NUM_LIT:0> ] ) <EOL> self . assertEqual ( [ <NUM_LIT:100> , <NUM_LIT> ] , s . data [ - <NUM_LIT:1> ] ) <EOL> s . FilterRange ( <NUM_LIT> , <NUM_LIT> ) <EOL> self . assertEqual ( <NUM_LIT:10> , len ( s . data ) ) <EOL> self . assertEqual ( [ <NUM_LIT:5> , <NUM_LIT> ] , s . data [ <NUM_LIT:0> ] ) <EOL> self . assertEqual ( [ <NUM_LIT> , <NUM_LIT> ] , s . data [ - <NUM_LIT:1> ] ) <EOL> def testNormalize ( self ) : <EOL> s = self . makeSeries ( ) <EOL> s . Normalize ( <NUM_LIT:10> * <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) <EOL> self . assertEqual ( <NUM_LIT:5> , len ( s . data ) ) <EOL> self . assertEqual ( [ <NUM_LIT> , <NUM_LIT> ] , s . data [ <NUM_LIT:0> ] ) <EOL> self . assertEqual ( [ <NUM_LIT> , <NUM_LIT> ] , s . data [ - <NUM_LIT:1> ] ) <EOL> s = timeseries . Timeseries ( ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:1000> ) : <EOL> s . Append ( <NUM_LIT:0.5> , i * <NUM_LIT:10> ) <EOL> s . Normalize ( <NUM_LIT:200> , <NUM_LIT> , <NUM_LIT> ) <EOL> self . assertEqual ( <NUM_LIT> , len ( s . data ) ) <EOL> self . assertListEqual ( s . data [ <NUM_LIT:0> ] , [ <NUM_LIT:0.5> , <NUM_LIT> ] ) <EOL> self . assertListEqual ( s . data [ <NUM_LIT> ] , [ <NUM_LIT:0.5> , <NUM_LIT> ] ) <EOL> s = timeseries . Timeseries ( ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:1000> ) : <EOL> s . Append ( i , i * <NUM_LIT:10> ) <EOL> s . Normalize ( <NUM_LIT:200> , <NUM_LIT> , <NUM_LIT> , mode = timeseries . NORMALIZE_MODE_COUNTER ) <EOL> self . assertEqual ( <NUM_LIT> , len ( s . data ) ) <EOL> self . assertListEqual ( s . data [ <NUM_LIT:0> ] , [ <NUM_LIT> , <NUM_LIT> ] ) <EOL> self . assertListEqual ( s . data [ <NUM_LIT> ] , [ <NUM_LIT> , <NUM_LIT> ] ) <EOL> def testToDeltas ( self ) : <EOL> s = self . makeSeries ( ) <EOL> self . assertEqual ( <NUM_LIT:100> , len ( s . data ) ) <EOL> s . ToDeltas ( ) <EOL> self . assertEqual ( <NUM_LIT> , len ( s . data ) ) <EOL> self . assertEqual ( [ <NUM_LIT:1> , <NUM_LIT> ] , s . data [ <NUM_LIT:0> ] ) <EOL> self . assertEqual ( [ <NUM_LIT:1> , <NUM_LIT> ] , s . data [ - <NUM_LIT:1> ] ) <EOL> s = timeseries . Timeseries ( ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:1000> ) : <EOL> s . Append ( i , i * <NUM_LIT> ) <EOL> s . Normalize ( <NUM_LIT:20> * <NUM_LIT> , <EOL> <NUM_LIT> * <NUM_LIT> , <EOL> <NUM_LIT:1000> * <NUM_LIT> , <EOL> mode = timeseries . NORMALIZE_MODE_COUNTER ) <EOL> self . assertEqual ( <NUM_LIT> , len ( s . data ) ) <EOL> self . assertListEqual ( s . data [ <NUM_LIT:0> ] , [ <NUM_LIT> , int ( <NUM_LIT> * <NUM_LIT> ) ] ) <EOL> s . ToDeltas ( ) <EOL> self . assertEqual ( <NUM_LIT> , len ( s . data ) ) <EOL> self . assertListEqual ( s . data [ <NUM_LIT:0> ] , [ <NUM_LIT:20> , int ( <NUM_LIT> * <NUM_LIT> ) ] ) <EOL> self . assertListEqual ( s . data [ <NUM_LIT> ] , [ <NUM_LIT:20> , int ( <NUM_LIT> * <NUM_LIT> ) ] ) <EOL> def testNormalizeFillsGapsWithNone ( self ) : <EOL> s = timeseries . Timeseries ( ) <EOL> for i in range ( <NUM_LIT> , <NUM_LIT> ) : <EOL> s . Append ( i , ( i + <NUM_LIT:5> ) * <NUM_LIT> ) <EOL> for i in range ( <NUM_LIT> , <NUM_LIT> ) : <EOL> s . Append ( i , ( i + <NUM_LIT:5> ) * <NUM_LIT> ) <EOL> s . Normalize ( <NUM_LIT:10> * <NUM_LIT> , <NUM_LIT:10> * <NUM_LIT> , <NUM_LIT> * <NUM_LIT> ) <EOL> self . assertEqual ( <NUM_LIT:11> , len ( s . data ) ) <EOL> self . assertEqual ( [ None , <NUM_LIT> ] , s . data [ <NUM_LIT:0> ] ) <EOL> self . assertEqual ( [ <NUM_LIT> , <NUM_LIT> ] , s . data [ <NUM_LIT:1> ] ) <EOL> self . assertEqual ( [ None , <NUM_LIT> ] , s . data [ <NUM_LIT:5> ] ) <EOL> self . assertEqual ( [ None , <NUM_LIT> ] , s . data [ - <NUM_LIT:1> ] ) <EOL> def testMakeIncreasing ( self ) : <EOL> s = timeseries . Timeseries ( ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:5> ) : <EOL> s . Append ( i , i * <NUM_LIT:1000> ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:5> ) : <EOL> s . Append ( i , ( i + <NUM_LIT:6> ) * <NUM_LIT:1000> ) <EOL> self . assertEqual ( <NUM_LIT:10> , len ( s . data ) ) <EOL> self . assertEqual ( [ <NUM_LIT:4> , <NUM_LIT> ] , s . data [ - <NUM_LIT:1> ] ) <EOL> s . MakeIncreasing ( ) <EOL> self . assertEqual ( <NUM_LIT:10> , len ( s . data ) ) <EOL> self . assertEqual ( [ <NUM_LIT:8> , <NUM_LIT> ] , s . data [ - <NUM_LIT:1> ] ) <EOL> def testAddRescale ( self ) : <EOL> s1 = timeseries . Timeseries ( ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:5> ) : <EOL> s1 . Append ( i , i * <NUM_LIT:1000> ) <EOL> s2 = timeseries . Timeseries ( ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:5> ) : <EOL> s2 . Append ( <NUM_LIT:2> * i , i * <NUM_LIT:1000> ) <EOL> s1 . Add ( s2 ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:5> ) : <EOL> self . assertEqual ( <NUM_LIT:3> * i , s1 . data [ i ] [ <NUM_LIT:0> ] ) <EOL> s1 . Rescale ( <NUM_LIT:1> / <NUM_LIT> ) <EOL> for i in range ( <NUM_LIT:0> , <NUM_LIT:5> ) : <EOL> self . assertEqual ( i , s1 . data [ i ] [ <NUM_LIT:0> ] ) <EOL> def testMean ( self ) : <EOL> s = timeseries . Timeseries ( ) <EOL> self . assertEqual ( None , s . Mean ( ) ) <EOL> s = self . makeSeries ( ) <EOL> self . assertEqual ( <NUM_LIT:100> , len ( s . data ) ) <EOL> self . assertEqual ( <NUM_LIT:50> , s . Mean ( ) ) <EOL> def main ( argv ) : <EOL> test_lib . main ( argv ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> flags . StartMain ( main ) </s>
<s> """<STR_LIT>""" <EOL> import StringIO <EOL> from grr . lib import flags <EOL> from grr . lib import test_lib <EOL> from grr . lib . rdfvalues import anomaly as rdf_anomaly <EOL> from grr . lib . rdfvalues import client as rdf_client <EOL> from grr . lib . rdfvalues import paths as rdf_paths <EOL> from grr . parsers import linux_service_parser <EOL> def GenTestData ( paths , data , st_mode = <NUM_LIT> ) : <EOL> stats = [ ] <EOL> files = [ ] <EOL> for path in paths : <EOL> p = rdf_paths . PathSpec ( path = path , pathtype = "<STR_LIT>" ) <EOL> stats . append ( rdf_client . StatEntry ( pathspec = p , st_mode = st_mode ) ) <EOL> for val in data : <EOL> files . append ( StringIO . StringIO ( val ) ) <EOL> return stats , files <EOL> def GenInit ( svc , desc , start = ( "<STR_LIT:2>" , "<STR_LIT:3>" , "<STR_LIT:4>" , "<STR_LIT:5>" ) , stop = ( "<STR_LIT:1>" ) ) : <EOL> insserv = r"""<STR_LIT>""" <EOL> tmpl = r"""<STR_LIT>""" % ( svc , "<STR_LIT:U+0020>" . join ( start ) , "<STR_LIT:U+0020>" . join ( stop ) , desc ) <EOL> return { "<STR_LIT>" : insserv , "<STR_LIT>" % svc : tmpl } <EOL> def GenXinetd ( svc = "<STR_LIT:test>" , disable = "<STR_LIT>" ) : <EOL> defaults = r"""<STR_LIT>""" <EOL> tmpl = """<STR_LIT>""" % ( svc , disable ) <EOL> return { "<STR_LIT>" : defaults , "<STR_LIT>" % svc : tmpl } <EOL> class LinuxLSBInitParserTest ( test_lib . GRRBaseTest ) : <EOL> """<STR_LIT>""" <EOL> def testParseLSBInit ( self ) : <EOL> """<STR_LIT>""" <EOL> configs = GenInit ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> stats , files = GenTestData ( configs , configs . values ( ) ) <EOL> parser = linux_service_parser . LinuxLSBInitParser ( ) <EOL> results = list ( parser . ParseMultiple ( stats , files , None ) ) <EOL> self . assertIsInstance ( results [ <NUM_LIT:0> ] , rdf_client . LinuxServiceInformation ) <EOL> result = results [ <NUM_LIT:0> ] <EOL> self . assertEqual ( "<STR_LIT>" , result . name ) <EOL> self . assertEqual ( "<STR_LIT>" , result . description ) <EOL> self . assertEqual ( "<STR_LIT>" , result . start_mode ) <EOL> self . assertItemsEqual ( [ <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> , <NUM_LIT:5> ] , result . start_on ) <EOL> self . assertItemsEqual ( [ <NUM_LIT:1> ] , result . stop_on ) <EOL> self . assertItemsEqual ( [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , <EOL> "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , <EOL> "<STR_LIT>" ] , result . start_after ) <EOL> self . assertItemsEqual ( [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , <EOL> "<STR_LIT>" ] , result . stop_after ) <EOL> def testSkipBadLSBInit ( self ) : <EOL> """<STR_LIT>""" <EOL> empty = "<STR_LIT>" <EOL> snippet = r"""<STR_LIT>""" <EOL> unfinished = """<STR_LIT>""" <EOL> paths = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> vals = [ empty , snippet , unfinished ] <EOL> stats , files = GenTestData ( paths , vals ) <EOL> parser = linux_service_parser . LinuxLSBInitParser ( ) <EOL> results = list ( parser . ParseMultiple ( stats , files , None ) ) <EOL> self . assertFalse ( results ) <EOL> class LinuxXinetdParserTest ( test_lib . GRRBaseTest ) : <EOL> """<STR_LIT>""" <EOL> def testParseXinetd ( self ) : <EOL> """<STR_LIT>""" <EOL> configs = GenXinetd ( "<STR_LIT>" , "<STR_LIT:yes>" ) <EOL> configs . update ( GenXinetd ( "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> stats , files = GenTestData ( configs , configs . values ( ) ) <EOL> parser = linux_service_parser . LinuxXinetdParser ( ) <EOL> results = list ( parser . ParseMultiple ( stats , files , None ) ) <EOL> self . assertEqual ( <NUM_LIT:2> , len ( results ) ) <EOL> self . assertItemsEqual ( [ "<STR_LIT>" , "<STR_LIT>" ] , [ r . name for r in results ] ) <EOL> for rslt in results : <EOL> self . assertFalse ( rslt . start_on ) <EOL> self . assertFalse ( rslt . stop_on ) <EOL> self . assertFalse ( rslt . stop_after ) <EOL> if rslt . name == "<STR_LIT>" : <EOL> self . assertFalse ( rslt . start_mode ) <EOL> self . assertFalse ( rslt . start_after ) <EOL> self . assertFalse ( rslt . starts ) <EOL> else : <EOL> self . assertEqual ( "<STR_LIT>" , str ( rslt . start_mode ) ) <EOL> self . assertItemsEqual ( [ "<STR_LIT>" ] , list ( rslt . start_after ) ) <EOL> self . assertTrue ( rslt . starts ) <EOL> class LinuxSysVInitParserTest ( test_lib . GRRBaseTest ) : <EOL> """<STR_LIT>""" <EOL> results = None <EOL> def setUp ( self , * args , ** kwargs ) : <EOL> super ( LinuxSysVInitParserTest , self ) . setUp ( * args , ** kwargs ) <EOL> if self . results is None : <EOL> dirs = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> d_stat , d_files = GenTestData ( dirs , [ "<STR_LIT>" ] * len ( dirs ) , st_mode = <NUM_LIT> ) <EOL> files = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> f_stat , f_files = GenTestData ( files , [ "<STR_LIT>" ] * len ( files ) ) <EOL> links = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , <EOL> "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , <EOL> "<STR_LIT>" ] <EOL> l_stat , l_files = GenTestData ( links , [ "<STR_LIT>" ] * len ( links ) , st_mode = <NUM_LIT> ) <EOL> stats = d_stat + f_stat + l_stat <EOL> files = d_files + f_files + l_files <EOL> parser = linux_service_parser . LinuxSysVInitParser ( ) <EOL> self . results = list ( parser . ParseMultiple ( stats , files , None ) ) <EOL> def testParseServices ( self ) : <EOL> """<STR_LIT>""" <EOL> services = { s . name : s for s in self . results if isinstance <EOL> ( s , rdf_client . LinuxServiceInformation ) } <EOL> self . assertEqual ( <NUM_LIT:5> , len ( services ) ) <EOL> self . assertItemsEqual ( [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] , services ) <EOL> self . assertItemsEqual ( [ <NUM_LIT:2> ] , services [ "<STR_LIT>" ] . start_on ) <EOL> self . assertItemsEqual ( [ <NUM_LIT:1> , <NUM_LIT:6> ] , services [ "<STR_LIT>" ] . stop_on ) <EOL> self . assertTrue ( services [ "<STR_LIT>" ] . starts ) <EOL> self . assertItemsEqual ( [ <NUM_LIT:1> ] , services [ "<STR_LIT>" ] . start_on ) <EOL> self . assertTrue ( services [ "<STR_LIT>" ] . starts ) <EOL> def testDetectAnomalies ( self ) : <EOL> anomalies = [ a for a in self . results if isinstance ( a , rdf_anomaly . Anomaly ) ] <EOL> self . assertEqual ( <NUM_LIT:1> , len ( anomalies ) ) <EOL> rslt = anomalies [ <NUM_LIT:0> ] <EOL> self . assertEqual ( "<STR_LIT>" , rslt . explanation ) <EOL> self . assertEqual ( [ "<STR_LIT>" ] , rslt . finding ) <EOL> self . assertEqual ( "<STR_LIT>" , rslt . type ) <EOL> def main ( args ) : <EOL> test_lib . main ( args ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> flags . StartMain ( main ) </s>
<s> """<STR_LIT>""" </s>
<s> """<STR_LIT>""" <EOL> import argparse <EOL> import os <EOL> from grr . lib import access_control <EOL> from grr . lib import aff4 <EOL> from grr . lib import data_store <EOL> from grr . lib import flags <EOL> from grr . lib import rdfvalue <EOL> from grr . lib import test_lib <EOL> from grr . lib import utils <EOL> from grr . tools . export_plugins import collection_files_plugin <EOL> class CollectionFilesExportPluginTest ( test_lib . GRRBaseTest ) : <EOL> def setUp ( self ) : <EOL> super ( CollectionFilesExportPluginTest , self ) . setUp ( ) <EOL> client_ids = self . SetupClients ( <NUM_LIT:1> ) <EOL> self . client_id = client_ids [ <NUM_LIT:0> ] <EOL> self . out = self . client_id . Add ( "<STR_LIT>" ) <EOL> data_store . default_token = access_control . ACLToken ( username = "<STR_LIT:user>" , <EOL> reason = "<STR_LIT>" ) <EOL> def CreateDir ( self , dirpath ) : <EOL> path = self . out . Add ( dirpath ) <EOL> fd = aff4 . FACTORY . Create ( path , "<STR_LIT>" , token = self . token ) <EOL> fd . Close ( ) <EOL> def CreateFile ( self , filepath ) : <EOL> path = self . out . Add ( filepath ) <EOL> fd = aff4 . FACTORY . Create ( path , "<STR_LIT>" , token = self . token ) <EOL> fd . Write ( "<STR_LIT>" ) <EOL> fd . Close ( ) <EOL> return path <EOL> def CreateCollection ( self , collection_path , paths ) : <EOL> with aff4 . FACTORY . Create ( collection_path , "<STR_LIT>" , <EOL> token = self . token ) as fd : <EOL> for p in paths : <EOL> fd . Add ( rdfvalue . RDFURN ( p ) ) <EOL> def testExportsFilesFromRDFURNs ( self ) : <EOL> """<STR_LIT>""" <EOL> testfile1_path = self . CreateFile ( "<STR_LIT>" ) <EOL> self . CreateDir ( "<STR_LIT>" ) <EOL> testfile2_path = self . CreateFile ( "<STR_LIT>" ) <EOL> collection_path = self . client_id . Add ( "<STR_LIT>" ) <EOL> self . CreateCollection ( collection_path , [ testfile1_path , testfile2_path ] ) <EOL> plugin = collection_files_plugin . CollectionFilesExportPlugin ( ) <EOL> parser = argparse . ArgumentParser ( ) <EOL> plugin . ConfigureArgParser ( parser ) <EOL> with utils . TempDirectory ( ) as tmpdir : <EOL> plugin . Run ( parser . parse_args ( args = [ <EOL> "<STR_LIT>" , <EOL> str ( collection_path ) , <EOL> "<STR_LIT>" , <EOL> tmpdir ] ) ) <EOL> expected_outdir = os . path . join ( tmpdir , self . out . Path ( ) [ <NUM_LIT:1> : ] ) <EOL> self . assertTrue ( "<STR_LIT>" in os . listdir ( expected_outdir ) ) <EOL> self . assertTrue ( "<STR_LIT>" in os . listdir ( expected_outdir ) ) <EOL> self . assertTrue ( "<STR_LIT>" in os . listdir ( <EOL> os . path . join ( expected_outdir , "<STR_LIT>" ) ) ) <EOL> def main ( argv ) : <EOL> test_lib . main ( argv ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> flags . StartMain ( main ) </s>
<s> """<STR_LIT>""" <EOL> import argparse <EOL> import cStringIO as StringIO <EOL> import httplib <EOL> import os <EOL> import os . path <EOL> import re <EOL> import signal <EOL> import sys <EOL> import tarfile <EOL> import threading <EOL> import traceback <EOL> import urlparse <EOL> MAX_READ = <NUM_LIT> <EOL> def main ( args ) : <EOL> """<STR_LIT>""" <EOL> signal . signal ( signal . SIGINT , signal . SIG_DFL ) <EOL> args = list ( args ) <EOL> url = os . environ . get ( '<STR_LIT>' ) <EOL> if '<STR_LIT>' in args [ <NUM_LIT:0> ] : <EOL> args . pop ( <NUM_LIT:0> ) <EOL> if len ( args ) > <NUM_LIT:1> and args [ <NUM_LIT:0> ] == '<STR_LIT>' : <EOL> args . pop ( <NUM_LIT:0> ) <EOL> url = args . pop ( <NUM_LIT:0> ) <EOL> if args : <EOL> args [ <NUM_LIT:0> ] = os . path . basename ( args [ <NUM_LIT:0> ] ) <EOL> if not url : <EOL> sys . exit ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' % <EOL> ( args [ <NUM_LIT:0> ] if args else '<STR_LIT>' ) ) <EOL> try : <EOL> params = PARSER . parse_args ( args ) <EOL> except ValueError : <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> sys . stdout = os . fdopen ( sys . stdout . fileno ( ) , '<STR_LIT:w>' , <NUM_LIT:0> ) <EOL> sys . stderr = os . fdopen ( sys . stderr . fileno ( ) , '<STR_LIT:w>' , <NUM_LIT:0> ) <EOL> exit_code = <NUM_LIT:1> <EOL> try : <EOL> client = LabDeviceProxyClient ( url , sys . stdout , sys . stderr ) <EOL> exit_code = client . Call ( * params ) <EOL> except : <EOL> sys . stderr . write ( GetStack ( ) ) <EOL> sys . exit ( exit_code ) <EOL> class LabDeviceProxyClient ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , url , stdout , stderr ) : <EOL> self . _url = ( url if '<STR_LIT>' in url else ( '<STR_LIT>' % url ) ) <EOL> self . _stdout = stdout <EOL> self . _stderr = stderr <EOL> def Call ( self , * params ) : <EOL> """<STR_LIT>""" <EOL> connection = _LabHTTPConnection ( urlparse . urlsplit ( self . _url ) . netloc ) <EOL> try : <EOL> self . _SendRequest ( params , connection ) <EOL> return self . _ReadResponse ( params , connection ) <EOL> finally : <EOL> connection . close ( ) <EOL> def _SendRequest ( self , params , connection ) : <EOL> """<STR_LIT>""" <EOL> connection . putrequest ( '<STR_LIT:POST>' , '<STR_LIT>' . join ( urlparse . urlsplit ( self . _url ) [ <NUM_LIT:2> : ] ) ) <EOL> connection . putheader ( '<STR_LIT:Content-Type>' , '<STR_LIT>' ) <EOL> connection . putheader ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> connection . putheader ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> connection . endheaders ( ) <EOL> for param in params : <EOL> param . SendTo ( connection ) <EOL> connection . send ( '<STR_LIT>' ) <EOL> def _ReadResponse ( self , params , connection ) : <EOL> """<STR_LIT>""" <EOL> response = connection . getresponse ( ) <EOL> if response . status != httplib . OK : <EOL> raise RuntimeError ( '<STR_LIT>' % ( <EOL> response . status , response . reason ) ) <EOL> if response . getheader ( '<STR_LIT>' ) != '<STR_LIT>' : <EOL> raise RuntimeError ( '<STR_LIT>' % response . msg ) <EOL> from_stream = response <EOL> id_to_fp = { } <EOL> id_to_fp [ '<STR_LIT:1>' ] = self . _stdout <EOL> id_to_fp [ '<STR_LIT:2>' ] = self . _stderr <EOL> id_to_fp [ '<STR_LIT>' ] = StringIO . StringIO ( ) <EOL> id_to_fn = { } <EOL> for index , param in enumerate ( params ) : <EOL> if isinstance ( param , OutputFileParameter ) : <EOL> id_to_fn [ '<STR_LIT>' % index ] = param . value <EOL> try : <EOL> while True : <EOL> header = ChunkHeader ( ) <EOL> header . Parse ( from_stream . readline ( ) ) <EOL> if header . len_ <= <NUM_LIT:0> : <EOL> break <EOL> handler_id = header . id_ <EOL> fp = id_to_fp . get ( handler_id ) <EOL> if not fp and handler_id not in id_to_fn : <EOL> raise ValueError ( '<STR_LIT>' % header ) <EOL> if header . is_absent_ or header . is_empty_ : <EOL> ReadExactly ( from_stream , header . len_ ) <EOL> else : <EOL> if not fp : <EOL> fn = id_to_fn [ handler_id ] <EOL> if header . is_tar_ : <EOL> fp = Untar ( fn ) <EOL> elif os . path . isfile ( fn ) or not os . path . exists ( fn ) : <EOL> fp = open ( fn , '<STR_LIT:wb>' ) <EOL> else : <EOL> raise ValueError ( '<STR_LIT>' % header ) <EOL> id_to_fp [ handler_id ] = fp <EOL> bytes_read = <NUM_LIT:0> <EOL> while bytes_read < header . len_ : <EOL> data = from_stream . read ( min ( MAX_READ , header . len_ - bytes_read ) ) <EOL> bytes_read += len ( data ) <EOL> fp . write ( data ) <EOL> if ReadExactly ( from_stream , <NUM_LIT:2> ) != '<STR_LIT:\r\n>' : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> finally : <EOL> for handler_id in id_to_fn : <EOL> if handler_id in id_to_fp : <EOL> id_to_fp [ handler_id ] . close ( ) <EOL> errcode_stream = id_to_fp [ '<STR_LIT>' ] <EOL> return int ( errcode_stream . getvalue ( ) ) if errcode_stream . tell ( ) else None <EOL> class _LabHTTPResponse ( httplib . HTTPResponse ) : <EOL> """<STR_LIT>""" <EOL> def readline ( self ) : <EOL> return self . fp . readline ( ) <EOL> def _read_chunked ( self , amt ) : <EOL> """<STR_LIT>""" <EOL> return self . fp . _sock . recv ( amt ) <EOL> class _LabHTTPConnection ( httplib . HTTPConnection ) : <EOL> response_class = _LabHTTPResponse <EOL> class Parameter ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , value ) : <EOL> self . value = value <EOL> self . index = None <EOL> def SendTo ( self , to_stream ) : <EOL> """<STR_LIT>""" <EOL> header = ChunkHeader ( '<STR_LIT>' % self . index ) <EOL> SendChunk ( header , str ( self . value ) , to_stream ) <EOL> def __repr__ ( self ) : <EOL> return str ( self . value ) <EOL> class AndroidSerialParameter ( Parameter ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , serial ) : <EOL> super ( AndroidSerialParameter , self ) . __init__ ( serial ) <EOL> if not re . match ( r'<STR_LIT>' , serial ) : <EOL> raise ValueError ( '<STR_LIT>' % serial ) <EOL> def __repr__ ( self ) : <EOL> return '<STR_LIT>' % str ( self . value ) <EOL> class IOSDeviceIdParameter ( Parameter ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , udid ) : <EOL> super ( IOSDeviceIdParameter , self ) . __init__ ( udid ) <EOL> if not re . match ( r'<STR_LIT>' , udid ) : <EOL> raise ValueError ( '<STR_LIT>' % udid ) <EOL> def __repr__ ( self ) : <EOL> return '<STR_LIT>' % str ( self . value ) <EOL> class InputFileParameter ( Parameter ) : <EOL> """<STR_LIT>""" <EOL> def SendTo ( self , to_stream ) : <EOL> """<STR_LIT>""" <EOL> in_fn = self . value <EOL> header = ChunkHeader ( '<STR_LIT>' % self . index ) <EOL> header . in_ = os . path . basename ( in_fn ) <EOL> if os . path . isfile ( in_fn ) : <EOL> with open ( in_fn , '<STR_LIT:r>' ) as file_object : <EOL> data = file_object . read ( MAX_READ ) <EOL> if not data : <EOL> SendChunk ( header , None , to_stream ) <EOL> else : <EOL> while data : <EOL> SendChunk ( header , data , to_stream ) <EOL> data = file_object . read ( MAX_READ ) <EOL> elif os . path . exists ( in_fn ) : <EOL> header . is_tar_ = True <EOL> SendTar ( in_fn , os . path . basename ( in_fn ) + '<STR_LIT:/>' , header , to_stream ) <EOL> else : <EOL> header . is_absent_ = True <EOL> SendChunk ( header , None , to_stream ) <EOL> def __repr__ ( self ) : <EOL> return '<STR_LIT>' % self . value <EOL> class OutputFileParameter ( Parameter ) : <EOL> """<STR_LIT>""" <EOL> def SendTo ( self , to_stream ) : <EOL> """<STR_LIT>""" <EOL> out_fn = self . value <EOL> header = ChunkHeader ( '<STR_LIT>' % self . index ) <EOL> if os . path . isdir ( out_fn ) : <EOL> header . is_tar_ = True <EOL> header . out_ = '<STR_LIT:.>' <EOL> else : <EOL> if not os . path . exists ( out_fn ) : <EOL> header . is_absent_ = True <EOL> header . out_ = os . path . basename ( out_fn ) <EOL> SendChunk ( header , None , to_stream ) <EOL> def __repr__ ( self ) : <EOL> return '<STR_LIT>' % self . value <EOL> class ParameterNamespace ( argparse . Namespace ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , params = None ) : <EOL> super ( ParameterNamespace , self ) . __init__ ( ) <EOL> self . params = ( params if params is not None else [ ] ) <EOL> def _Append ( self , value ) : <EOL> param = ( value if isinstance ( value , Parameter ) else Parameter ( value ) ) <EOL> param . index = len ( self . params ) <EOL> self . params . append ( param ) <EOL> def __setattr__ ( self , name , value ) : <EOL> super ( ParameterNamespace , self ) . __setattr__ ( name , value ) <EOL> if name and name [ <NUM_LIT:0> ] == '<STR_LIT:_>' : <EOL> name = '<STR_LIT>' % ( '<STR_LIT:->' if name [ <NUM_LIT:1> ] == '<STR_LIT:_>' else name [ <NUM_LIT:1> ] , name [ <NUM_LIT:2> : ] ) <EOL> self . _Append ( name ) <EOL> if isinstance ( value , list ) : <EOL> for v in value : <EOL> self . _Append ( v ) <EOL> elif value and value is not True : <EOL> self . _Append ( value ) <EOL> class ParameterDecl ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> self . args = args <EOL> self . kwargs = kwargs <EOL> class ParameterParser ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , prog , * decls , ** kwargs ) : <EOL> m = kwargs <EOL> if '<STR_LIT>' not in m : <EOL> m [ '<STR_LIT>' ] = False <EOL> self . p = argparse . ArgumentParser ( prog = prog , ** m ) <EOL> for decl in decls : <EOL> self . AddParameter ( * decl . args , ** decl . kwargs ) <EOL> def AddSubparsers ( self , * args ) : <EOL> def GetParser ( ** kwargs ) : <EOL> return kwargs [ '<STR_LIT>' ] <EOL> sp = self . p . add_subparsers ( parser_class = GetParser , dest = '<STR_LIT>' ) <EOL> for parser in args : <EOL> sp . add_parser ( parser . p . prog , parser = parser . p ) <EOL> return self <EOL> def AddParameter ( self , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> m = kwargs <EOL> if '<STR_LIT:default>' not in m : <EOL> m [ '<STR_LIT:default>' ] = argparse . SUPPRESS <EOL> if '<STR_LIT>' in m : <EOL> self . p . add_argument ( * args , ** m ) <EOL> else : <EOL> for arg in args : <EOL> if '<STR_LIT>' in m : <EOL> del m [ '<STR_LIT>' ] <EOL> if arg [ <NUM_LIT:0> ] == '<STR_LIT:->' : <EOL> m [ '<STR_LIT>' ] = '<STR_LIT>' % ( '<STR_LIT:_>' if arg [ <NUM_LIT:1> ] == '<STR_LIT:->' else arg [ <NUM_LIT:1> ] , arg [ <NUM_LIT:2> : ] ) <EOL> self . p . add_argument ( arg , ** m ) <EOL> return self <EOL> def parse_args ( self , args , namespace = None ) : <EOL> ret = [ ] <EOL> if namespace is None : <EOL> namespace = ParameterNamespace ( ret ) <EOL> try : <EOL> self . p . parse_args ( args , namespace ) <EOL> except : <EOL> raise ValueError <EOL> return ret <EOL> class DAction ( argparse . Action ) : <EOL> """<STR_LIT>""" <EOL> def __call__ ( self , parser , namespace , value , name ) : <EOL> setattr ( namespace , self . dest + value [ <NUM_LIT:0> ] , True ) <EOL> def _CreateParser ( ) : <EOL> """<STR_LIT>""" <EOL> idevice_app_runner = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = IOSDeviceIdParameter ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str , nargs = '<STR_LIT:*>' , action = DAction ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str , nargs = argparse . REMAINDER ) ) <EOL> idevice_id = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) ) <EOL> idevice_date = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = IOSDeviceIdParameter ) ) <EOL> idevice_diagnostics = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = IOSDeviceIdParameter ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str , choices = [ '<STR_LIT>' ] ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str , choices = [ '<STR_LIT>' , '<STR_LIT>' ] ) ) <EOL> idevice_image_mounter = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = IOSDeviceIdParameter ) , <EOL> ParameterDecl ( '<STR_LIT:image>' , type = InputFileParameter ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = InputFileParameter ) ) <EOL> idevice_info = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = IOSDeviceIdParameter ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) ) <EOL> idevice_installer = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = IOSDeviceIdParameter ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = InputFileParameter ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = str ) ) <EOL> idevicefs_ls = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str , nargs = argparse . OPTIONAL ) ) <EOL> idevicefs_pull = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = OutputFileParameter ) ) <EOL> idevicefs_push = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , type = InputFileParameter ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str , nargs = argparse . OPTIONAL ) ) <EOL> idevicefs_rm = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str ) ) <EOL> idevicefs_parsers = [ <EOL> ParameterParser ( '<STR_LIT>' ) , <EOL> idevicefs_ls , idevicefs_pull , idevicefs_push , idevicefs_rm ] <EOL> idevice_fs = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = IOSDeviceIdParameter ) ) <EOL> idevice_fs . AddSubparsers ( * idevicefs_parsers ) <EOL> idevice_screenshot = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = IOSDeviceIdParameter ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = OutputFileParameter ) ) <EOL> idevice_syslog = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , type = IOSDeviceIdParameter ) ) <EOL> idevice_parser = [ <EOL> idevice_app_runner , idevice_date , idevice_diagnostics , idevice_fs , <EOL> idevice_id , idevice_image_mounter , idevice_info , idevice_installer , <EOL> idevice_screenshot , idevice_syslog ] <EOL> adb_connect = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT:host>' , type = str ) ) <EOL> adb_devices = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) ) <EOL> adb_install = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT:file>' , type = InputFileParameter ) ) <EOL> adb_logcat = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT:-c>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = int ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = int ) , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = int ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT>' , nargs = argparse . REMAINDER ) ) <EOL> adb_pull = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = OutputFileParameter ) ) <EOL> adb_push = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , type = InputFileParameter ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str ) ) <EOL> adb_root = ParameterParser ( <EOL> '<STR_LIT:root>' ) <EOL> adb_shell = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , type = str ) , <EOL> ParameterDecl ( '<STR_LIT:args>' , nargs = argparse . REMAINDER ) ) <EOL> adb_uninstall = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , action = '<STR_LIT:store_true>' ) , <EOL> ParameterDecl ( '<STR_LIT>' , type = str ) ) <EOL> adb_waitfordevices = ParameterParser ( <EOL> '<STR_LIT>' ) <EOL> adb_parsers = [ <EOL> ParameterParser ( '<STR_LIT>' ) , <EOL> adb_connect , adb_devices , adb_install , adb_logcat , adb_pull , <EOL> adb_push , adb_root , adb_shell , adb_uninstall , adb_waitfordevices ] <EOL> adb_parser = ParameterParser ( <EOL> '<STR_LIT>' , <EOL> ParameterDecl ( '<STR_LIT>' , type = AndroidSerialParameter ) ) <EOL> adb_parser . AddSubparsers ( * adb_parsers ) <EOL> parser = ParameterParser ( None ) <EOL> parser . AddSubparsers ( adb_parser , * idevice_parser ) <EOL> return parser <EOL> PARSER = _CreateParser ( ) <EOL> class ChunkHeader ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , id_ = None ) : <EOL> self . len_ = None <EOL> self . id_ = id_ <EOL> self . in_ = None <EOL> self . out_ = None <EOL> self . is_absent_ = None <EOL> self . is_empty_ = None <EOL> self . is_tar_ = None <EOL> def Parse ( self , line ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> if not line . endswith ( '<STR_LIT:\r\n>' ) : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> len_and_csv = line [ : - <NUM_LIT:2> ] . split ( '<STR_LIT:;>' , <NUM_LIT:1> ) <EOL> if len ( len_and_csv ) > <NUM_LIT:1> : <EOL> for item in len_and_csv [ <NUM_LIT:1> ] . split ( '<STR_LIT:U+002C>' ) : <EOL> k , v = item . strip ( ) . split ( '<STR_LIT:=>' , <NUM_LIT:1> ) <EOL> self . _Validate ( k , v ) <EOL> k += '<STR_LIT:_>' <EOL> if not hasattr ( self , k ) : <EOL> pass <EOL> if k . startswith ( '<STR_LIT>' ) : <EOL> v = ( '<STR_LIT:true>' == v . lower ( ) ) <EOL> setattr ( self , k , v ) <EOL> self . len_ = max ( <NUM_LIT:0> , int ( len_and_csv [ <NUM_LIT:0> ] . strip ( ) , <NUM_LIT:16> ) ) <EOL> except : <EOL> raise ValueError ( '<STR_LIT>' , line ) <EOL> def Format ( self ) : <EOL> """<STR_LIT>""" <EOL> ret = '<STR_LIT>' <EOL> for k , v in sorted ( vars ( self ) . iteritems ( ) ) : <EOL> if v is not None and k [ - <NUM_LIT:1> ] == '<STR_LIT:_>' and k != '<STR_LIT>' : <EOL> k = k [ : - <NUM_LIT:1> ] <EOL> v = str ( v ) <EOL> self . _Validate ( k , v ) <EOL> ret += '<STR_LIT>' % ( '<STR_LIT:U+002C>' if ret else '<STR_LIT>' , k , v ) <EOL> ret = '<STR_LIT>' % ( self . len_ , ret ) <EOL> return ret <EOL> def _Validate ( self , key , value ) : <EOL> """<STR_LIT>""" <EOL> if not re . match ( r'<STR_LIT>' , key ) : <EOL> raise ValueError ( '<STR_LIT>' % ( self . id_ , key ) ) <EOL> if not re . match ( r'<STR_LIT>' , value ) : <EOL> raise ValueError ( '<STR_LIT>' % ( <EOL> self . id_ , key , value ) ) <EOL> def __eq__ ( self , other ) : <EOL> return vars ( self ) == vars ( other ) <EOL> def __ne__ ( self , other ) : <EOL> return vars ( self ) != vars ( other ) <EOL> def __repr__ ( self ) : <EOL> return self . Format ( ) [ : - <NUM_LIT:2> ] <EOL> def SendChunk ( header , data , to_stream ) : <EOL> """<STR_LIT>""" <EOL> send = getattr ( to_stream , '<STR_LIT>' , None ) <EOL> if send is None : <EOL> send = getattr ( to_stream , '<STR_LIT>' ) <EOL> if not data : <EOL> header . is_empty_ = True <EOL> data = '<STR_LIT:->' <EOL> header . len_ = len ( data ) <EOL> send ( header . Format ( ) ) <EOL> send ( data ) <EOL> send ( '<STR_LIT:\r\n>' ) <EOL> def ReadExactly ( from_stream , num_bytes ) : <EOL> """<STR_LIT>""" <EOL> pieces = [ ] <EOL> bytes_read = <NUM_LIT:0> <EOL> while bytes_read < num_bytes : <EOL> data = from_stream . read ( min ( MAX_READ , num_bytes - bytes_read ) ) <EOL> bytes_read += len ( data ) <EOL> pieces . append ( data ) <EOL> return '<STR_LIT>' . join ( pieces ) <EOL> def GetStack ( ) : <EOL> trc = '<STR_LIT>' <EOL> stackstr = ( <EOL> trc + '<STR_LIT>' . join ( traceback . format_list ( <EOL> traceback . extract_stack ( ) [ : - <NUM_LIT:2> ] ) ) + '<STR_LIT:U+0020>' + <EOL> traceback . format_exc ( ) . lstrip ( trc ) ) <EOL> return stackstr <EOL> class ChunkedOutputStream ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , header , to_stream ) : <EOL> self . _header = header <EOL> self . _to_stream = to_stream <EOL> def write ( self , buf ) : <EOL> if buf : <EOL> SendChunk ( self . _header , buf , self . _to_stream ) <EOL> def flush ( self ) : <EOL> self . _to_stream . flush ( ) <EOL> def close ( self ) : <EOL> pass <EOL> def SendTar ( from_fn , to_arcname , header , to_stream ) : <EOL> """<STR_LIT>""" <EOL> tar_stream = ChunkedOutputStream ( header , to_stream ) <EOL> to_tar = tarfile . open ( mode = '<STR_LIT>' , fileobj = tar_stream ) <EOL> to_tar . add ( from_fn , arcname = to_arcname ) <EOL> to_tar . close ( ) <EOL> class UntarPipe ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> self . cv = threading . Condition ( ) <EOL> self . buf = [ ] <EOL> self . closed = False <EOL> def write ( self , data ) : <EOL> """<STR_LIT>""" <EOL> with self . cv : <EOL> if self . closed : <EOL> raise RuntimeError ( '<STR_LIT>' ) <EOL> self . buf . append ( data ) <EOL> if len ( self . buf ) == <NUM_LIT:1> : <EOL> self . cv . notify ( ) <EOL> def read ( self , max_bytes ) : <EOL> """<STR_LIT>""" <EOL> with self . cv : <EOL> while not self . buf : <EOL> if self . closed : <EOL> return '<STR_LIT>' <EOL> self . cv . wait ( ) <EOL> if len ( self . buf [ <NUM_LIT:0> ] ) <= max_bytes : <EOL> return self . buf . pop ( <NUM_LIT:0> ) <EOL> ret = self . buf [ <NUM_LIT:0> ] [ : max_bytes ] <EOL> self . buf [ <NUM_LIT:0> ] = self . buf [ <NUM_LIT:0> ] [ max_bytes : ] <EOL> return ret <EOL> def close ( self ) : <EOL> with self . cv : <EOL> if not self . closed : <EOL> self . closed = True <EOL> self . cv . notify ( ) <EOL> class UntarThread ( threading . Thread ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , from_fp , to_fn ) : <EOL> super ( UntarThread , self ) . __init__ ( ) <EOL> self . _from_fp = from_fp <EOL> to_fn = os . path . normpath ( to_fn ) <EOL> to_dn = ( to_fn if os . path . isdir ( to_fn ) else os . path . dirname ( to_fn ) ) <EOL> to_dn = ( to_dn if to_dn else '<STR_LIT:.>' ) <EOL> self . _to_fn = to_fn <EOL> self . _to_dn = to_dn <EOL> def run ( self ) : <EOL> from_tar = tarfile . open ( mode = '<STR_LIT>' , fileobj = self . _from_fp ) <EOL> while True : <EOL> tar_entry = from_tar . next ( ) <EOL> if not tar_entry : <EOL> break <EOL> fn = os . path . normpath ( os . path . join ( self . _to_dn , tar_entry . name ) ) <EOL> if ( re . match ( r'<STR_LIT>' , fn ) if self . _to_dn == '<STR_LIT:.>' else <EOL> not ( fn == self . _to_dn or fn . startswith ( self . _to_dn + '<STR_LIT:/>' ) ) ) : <EOL> raise ValueError ( '<STR_LIT>' % tar_entry . name ) <EOL> from_tar . extract ( tar_entry , self . _to_dn ) <EOL> from_tar . close ( ) <EOL> def Untar ( to_fn ) : <EOL> """<STR_LIT>""" <EOL> ret = UntarPipe ( ) <EOL> UntarThread ( ret , to_fn ) . start ( ) <EOL> return ret <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> main ( sys . argv ) </s>
<s> """<STR_LIT>""" <EOL> import mock <EOL> from google . apputils import basetest <EOL> import profiles <EOL> class ProfilesModuleTest ( basetest . TestCase ) : <EOL> def testGenerateUUID ( self ) : <EOL> self . assertIsInstance ( profiles . GenerateUUID ( '<STR_LIT:a>' ) , str ) <EOL> self . assertTrue ( profiles . GenerateUUID ( '<STR_LIT:a>' ) . isupper ( ) ) <EOL> self . assertEqual ( profiles . GenerateUUID ( '<STR_LIT:a>' ) , <EOL> profiles . GenerateUUID ( '<STR_LIT:a>' ) ) <EOL> def testValidatePayload ( self ) : <EOL> payload = { } <EOL> with self . assertRaises ( profiles . PayloadValidationError ) : <EOL> profiles . ValidatePayload ( payload ) <EOL> payload . update ( { profiles . PAYLOADKEYS_IDENTIFIER : '<STR_LIT:a>' , <EOL> profiles . PAYLOADKEYS_DISPLAYNAME : '<STR_LIT:a>' , <EOL> profiles . PAYLOADKEYS_TYPE : '<STR_LIT>' } ) <EOL> profiles . ValidatePayload ( payload ) <EOL> self . assertEqual ( payload . get ( profiles . PAYLOADKEYS_UUID ) , <EOL> profiles . GenerateUUID ( '<STR_LIT:a>' ) ) <EOL> self . assertEqual ( payload . get ( profiles . PAYLOADKEYS_ENABLED ) , True ) <EOL> self . assertEqual ( payload . get ( profiles . PAYLOADKEYS_VERSION ) , <NUM_LIT:1> ) <EOL> class ProfileClassTest ( basetest . TestCase ) : <EOL> """<STR_LIT>""" <EOL> def _GetValidProfile ( self , include_payload = True ) : <EOL> profile = profiles . Profile ( ) <EOL> profile . Set ( profiles . PAYLOADKEYS_DISPLAYNAME , '<STR_LIT>' ) <EOL> profile . Set ( profiles . PAYLOADKEYS_IDENTIFIER , '<STR_LIT>' ) <EOL> profile . Set ( profiles . PAYLOADKEYS_ORG , '<STR_LIT>' ) <EOL> profile . Set ( profiles . PAYLOADKEYS_SCOPE , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> profile . Set ( profiles . PAYLOADKEYS_TYPE , '<STR_LIT>' ) <EOL> if include_payload : <EOL> profile . AddPayload ( self . _GetValidPayload ( ) ) <EOL> return profile <EOL> def _GetValidPayload ( self ) : <EOL> test_payload = { profiles . PAYLOADKEYS_IDENTIFIER : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_DISPLAYNAME : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_TYPE : '<STR_LIT>' } <EOL> return test_payload <EOL> def testInit ( self ) : <EOL> """<STR_LIT>""" <EOL> profile = profiles . Profile ( ) <EOL> self . assertIsNotNone ( profile . _profile ) <EOL> self . assertEqual ( profile . _profile [ profiles . PAYLOADKEYS_CONTENT ] , [ ] ) <EOL> def testGet ( self ) : <EOL> profile = profiles . Profile ( ) <EOL> profile . _profile [ '<STR_LIT>' ] = '<STR_LIT>' <EOL> self . assertEqual ( profile . Get ( profiles . PAYLOADKEYS_CONTENT ) , [ ] ) <EOL> self . assertEqual ( profile . Get ( '<STR_LIT>' ) , '<STR_LIT>' ) <EOL> def testSet ( self ) : <EOL> profile = profiles . Profile ( ) <EOL> profile . Set ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> profile . Set ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . assertEqual ( profile . _profile [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> self . assertEqual ( profile . _profile [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> def testStr ( self ) : <EOL> profile = self . _GetValidProfile ( ) <EOL> self . assertEqual ( profile . __str__ ( ) , '<STR_LIT>' ) <EOL> def testAddPayload ( self ) : <EOL> profile = self . _GetValidProfile ( include_payload = False ) <EOL> test_payload = self . _GetValidPayload ( ) <EOL> with self . assertRaises ( profiles . PayloadValidationError ) : <EOL> profile . AddPayload ( '<STR_LIT>' ) <EOL> profile . AddPayload ( test_payload ) <EOL> self . assertEqual ( profile . Get ( profiles . PAYLOADKEYS_CONTENT ) , [ test_payload ] ) <EOL> def testValidateProfile ( self ) : <EOL> profile = profiles . Profile ( ) <EOL> with self . assertRaises ( profiles . ProfileValidationError ) : <EOL> profile . _ValidateProfile ( ) <EOL> profile = self . _GetValidProfile ( include_payload = False ) <EOL> with self . assertRaises ( profiles . ProfileValidationError ) : <EOL> profile . _ValidateProfile ( ) <EOL> profile . AddPayload ( self . _GetValidPayload ( ) ) <EOL> profile . _ValidateProfile ( ) <EOL> self . assertIsNotNone ( profile . Get ( profiles . PAYLOADKEYS_UUID ) ) <EOL> self . assertIsNotNone ( profile . Get ( profiles . PAYLOADKEYS_VERSION ) ) <EOL> @ mock . patch . object ( profiles . plistlib , '<STR_LIT>' ) <EOL> def testSaveSuccess ( self , mock_writeplist ) : <EOL> profile = self . _GetValidProfile ( ) <EOL> profile . Save ( '<STR_LIT>' ) <EOL> mock_writeplist . assert_called_once_with ( profile . _profile , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . plistlib , '<STR_LIT>' ) <EOL> def testSaveIOError ( self , mock_writeplist ) : <EOL> profile = self . _GetValidProfile ( ) <EOL> mock_writeplist . side_effect = IOError <EOL> with self . assertRaises ( profiles . ProfileSaveError ) : <EOL> profile . Save ( '<STR_LIT>' ) <EOL> mock_writeplist . assert_called_once_with ( profile . _profile , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . gmacpyutil , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . Profile , '<STR_LIT>' ) <EOL> def testInstallSuccess ( self , mock_save , mock_runprocess ) : <EOL> profile = self . _GetValidProfile ( ) <EOL> mock_runprocess . return_value = [ '<STR_LIT>' , None , <NUM_LIT:0> ] <EOL> profile . Install ( ) <EOL> mock_save . assert_called_once_with ( mock . ANY ) <EOL> mock_runprocess . assert_called_once_with ( <EOL> [ profiles . CMD_PROFILES , '<STR_LIT>' , '<STR_LIT>' , mock . ANY ] , <EOL> sudo = None , sudo_password = None ) <EOL> @ mock . patch . object ( profiles . gmacpyutil , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . Profile , '<STR_LIT>' ) <EOL> def testInstallSudoPassword ( self , mock_save , mock_runprocess ) : <EOL> profile = self . _GetValidProfile ( ) <EOL> mock_runprocess . return_value = [ '<STR_LIT>' , None , <NUM_LIT:0> ] <EOL> profile . Install ( sudo_password = '<STR_LIT>' ) <EOL> mock_save . assert_called_once_with ( mock . ANY ) <EOL> mock_runprocess . assert_called_once_with ( <EOL> [ profiles . CMD_PROFILES , '<STR_LIT>' , '<STR_LIT>' , mock . ANY ] , <EOL> sudo = '<STR_LIT>' , sudo_password = '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . gmacpyutil , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . Profile , '<STR_LIT>' ) <EOL> def testInstallCommandFail ( self , mock_save , mock_runprocess ) : <EOL> profile = self . _GetValidProfile ( ) <EOL> mock_runprocess . return_value = [ '<STR_LIT>' , '<STR_LIT>' , <NUM_LIT> ] <EOL> with self . assertRaisesRegexp ( profiles . ProfileInstallationError , <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) : <EOL> profile . Install ( sudo_password = '<STR_LIT>' ) <EOL> mock_save . assert_called_once_with ( mock . ANY ) <EOL> mock_runprocess . assert_called_once_with ( <EOL> [ profiles . CMD_PROFILES , '<STR_LIT>' , '<STR_LIT>' , mock . ANY ] , <EOL> sudo = '<STR_LIT>' , sudo_password = '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . gmacpyutil , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . Profile , '<STR_LIT>' ) <EOL> def testInstallCommandException ( self , mock_save , mock_runprocess ) : <EOL> profile = self . _GetValidProfile ( ) <EOL> mock_runprocess . side_effect = profiles . gmacpyutil . GmacpyutilException <EOL> with self . assertRaisesRegexp ( profiles . ProfileInstallationError , <EOL> '<STR_LIT>' ) : <EOL> profile . Install ( sudo_password = '<STR_LIT>' ) <EOL> mock_save . assert_called_once_with ( mock . ANY ) <EOL> mock_runprocess . assert_called_once_with ( <EOL> [ profiles . CMD_PROFILES , '<STR_LIT>' , '<STR_LIT>' , mock . ANY ] , <EOL> sudo = '<STR_LIT>' , sudo_password = '<STR_LIT>' ) <EOL> class NetworkProfileClassTest ( basetest . TestCase ) : <EOL> """<STR_LIT>""" <EOL> def testInit ( self ) : <EOL> profile = profiles . NetworkProfile ( '<STR_LIT>' ) <EOL> self . assertEqual ( profile . Get ( profiles . PAYLOADKEYS_DISPLAYNAME ) , <EOL> '<STR_LIT>' ) <EOL> self . assertEqual ( profile . Get ( profiles . PAYLOADKEYS_DESCRIPTION ) , <EOL> '<STR_LIT>' ) <EOL> self . assertEqual ( profile . Get ( profiles . PAYLOADKEYS_IDENTIFIER ) , <EOL> '<STR_LIT>' ) <EOL> self . assertEqual ( profile . Get ( profiles . PAYLOADKEYS_SCOPE ) , <EOL> [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> self . assertEqual ( profile . Get ( profiles . PAYLOADKEYS_TYPE ) , '<STR_LIT>' ) <EOL> self . assertEqual ( profile . Get ( profiles . PAYLOADKEYS_CONTENT ) , [ ] ) <EOL> def testGenerateID ( self ) : <EOL> profile = profiles . NetworkProfile ( '<STR_LIT>' ) <EOL> self . assertEqual ( profile . _GenerateID ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' ) <EOL> self . assertEqual ( profile . _GenerateID ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . NetworkProfile , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . crypto , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . crypto , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . crypto , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . certs , '<STR_LIT>' ) <EOL> def testAddMachineCertificateSuccess ( self , mock_certificate , mock_pkcs12 , <EOL> mock_loadcert , mock_loadkey , <EOL> mock_addpayload ) : <EOL> mock_certobj = mock . MagicMock ( ) <EOL> mock_certobj . subject_cn = '<STR_LIT>' <EOL> mock_certobj . osx_fingerprint = '<STR_LIT>' <EOL> mock_certificate . return_value = mock_certobj <EOL> mock_pkcs12obj = mock . MagicMock ( ) <EOL> mock_pkcs12obj . export . return_value = '<STR_LIT>' <EOL> mock_pkcs12 . return_value = mock_pkcs12obj <EOL> mock_loadcert . return_value = '<STR_LIT>' <EOL> mock_loadkey . return_value = '<STR_LIT>' <EOL> profile = profiles . NetworkProfile ( '<STR_LIT>' ) <EOL> profile . AddMachineCertificate ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> mock_pkcs12 . assert_called_once_with ( ) <EOL> mock_pkcs12obj . set_certificate . assert_called_once_with ( '<STR_LIT>' ) <EOL> mock_pkcs12obj . set_privatekey . assert_called_once_with ( '<STR_LIT>' ) <EOL> mock_pkcs12obj . export . assert_called_once_with ( '<STR_LIT>' ) <EOL> mock_loadcert . assert_called_once_with ( <NUM_LIT:1> , '<STR_LIT>' ) <EOL> mock_loadkey . assert_called_once_with ( <NUM_LIT:1> , '<STR_LIT>' ) <EOL> mock_addpayload . assert_called_once_with ( <EOL> { profiles . PAYLOADKEYS_IDENTIFIER : <EOL> '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_TYPE : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_DISPLAYNAME : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_ENABLED : True , <EOL> profiles . PAYLOADKEYS_VERSION : <NUM_LIT:1> , <EOL> profiles . PAYLOADKEYS_CONTENT : profiles . plistlib . Data ( <EOL> '<STR_LIT>' ) , <EOL> profiles . PAYLOADKEYS_UUID : mock . ANY , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> @ mock . patch . object ( profiles . crypto , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . crypto , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . crypto , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . certs , '<STR_LIT>' ) <EOL> def testAddMachineCertificateInvalidKey ( self , mock_certificate , mock_pkcs12 , <EOL> mock_loadcert , mock_loadkey ) : <EOL> mock_certobj = mock . MagicMock ( ) <EOL> mock_certobj . subject_cn = '<STR_LIT>' <EOL> mock_certobj . osx_fingerprint = '<STR_LIT>' <EOL> mock_certificate . return_value = mock_certobj <EOL> mock_pkcs12obj = mock . MagicMock ( ) <EOL> mock_pkcs12obj . export . side_effect = profiles . crypto . Error <EOL> mock_pkcs12 . return_value = mock_pkcs12obj <EOL> mock_loadcert . return_value = '<STR_LIT>' <EOL> mock_loadkey . return_value = '<STR_LIT>' <EOL> profile = profiles . NetworkProfile ( '<STR_LIT>' ) <EOL> with self . assertRaises ( profiles . CertificateError ) : <EOL> profile . AddMachineCertificate ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . certs , '<STR_LIT>' ) <EOL> def testAddMachineCertificateBadCert ( self , mock_certificate ) : <EOL> mock_certificate . side_effect = profiles . certs . CertError <EOL> profile = profiles . NetworkProfile ( '<STR_LIT>' ) <EOL> with self . assertRaises ( profiles . CertificateError ) : <EOL> profile . AddMachineCertificate ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . NetworkProfile , '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . certs , '<STR_LIT>' ) <EOL> def testAddAnchorCertificateSuccess ( self , mock_certificate , mock_addpayload ) : <EOL> mock_certobj = mock . MagicMock ( ) <EOL> mock_certobj . subject_cn = '<STR_LIT>' <EOL> mock_certobj . osx_fingerprint = '<STR_LIT>' <EOL> mock_certificate . return_value = mock_certobj <EOL> profile = profiles . NetworkProfile ( '<STR_LIT>' ) <EOL> profile . AddAnchorCertificate ( '<STR_LIT>' ) <EOL> mock_certificate . assert_called_once_with ( '<STR_LIT>' ) <EOL> mock_addpayload . assert_called_once_with ( <EOL> { profiles . PAYLOADKEYS_IDENTIFIER : <EOL> '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_TYPE : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_DISPLAYNAME : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_CONTENT : profiles . plistlib . Data ( '<STR_LIT>' ) , <EOL> profiles . PAYLOADKEYS_ENABLED : True , <EOL> profiles . PAYLOADKEYS_VERSION : <NUM_LIT:1> , <EOL> profiles . PAYLOADKEYS_UUID : mock . ANY } ) <EOL> @ mock . patch . object ( profiles . certs , '<STR_LIT>' ) <EOL> def testAddAnchorCertificateBadCert ( self , mock_certificate ) : <EOL> mock_certificate . side_effect = profiles . certs . CertError <EOL> profile = profiles . NetworkProfile ( '<STR_LIT>' ) <EOL> with self . assertRaises ( profiles . CertificateError ) : <EOL> profile . AddAnchorCertificate ( '<STR_LIT>' ) <EOL> @ mock . patch . object ( profiles . NetworkProfile , '<STR_LIT>' ) <EOL> def testAddNetworkPayloadSSID ( self , mock_addpayload ) : <EOL> profile = profiles . NetworkProfile ( '<STR_LIT>' ) <EOL> profile . _auth_cert = '<STR_LIT>' <EOL> profile . _anchor_certs = [ '<STR_LIT>' ] <EOL> profile . AddTrustedServer ( '<STR_LIT>' ) <EOL> profile . AddNetworkPayload ( '<STR_LIT>' ) <EOL> eap_client_data = { '<STR_LIT>' : [ <NUM_LIT> ] , <EOL> '<STR_LIT>' : <EOL> [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : <EOL> [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : False } <EOL> mock_addpayload . assert_called_once_with ( <EOL> { '<STR_LIT>' : True , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_DISPLAYNAME : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_IDENTIFIER : <EOL> '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_TYPE : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : eap_client_data } ) <EOL> @ mock . patch . object ( profiles . NetworkProfile , '<STR_LIT>' ) <EOL> def testAddNetworkPayloadWired ( self , mock_addpayload ) : <EOL> profile = profiles . NetworkProfile ( '<STR_LIT>' ) <EOL> profile . _auth_cert = '<STR_LIT>' <EOL> profile . _anchor_certs = [ '<STR_LIT>' ] <EOL> profile . AddTrustedServer ( '<STR_LIT>' ) <EOL> profile . AddNetworkPayload ( '<STR_LIT>' ) <EOL> eap_client_data = { '<STR_LIT>' : [ <NUM_LIT> ] , <EOL> '<STR_LIT>' : <EOL> [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : <EOL> [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : False } <EOL> mock_addpayload . assert_called_once_with ( <EOL> { '<STR_LIT>' : True , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_DISPLAYNAME : '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_IDENTIFIER : <EOL> '<STR_LIT>' , <EOL> profiles . PAYLOADKEYS_TYPE : '<STR_LIT>' , <EOL> '<STR_LIT>' : eap_client_data } ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> basetest . main ( ) </s>
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> import sys <EOL> import gflags <EOL> FLAGS = gflags . FLAGS <EOL> class Error ( Exception ) : <EOL> pass <EOL> class UsageError ( Error ) : <EOL> pass <EOL> def run ( ) : <EOL> try : <EOL> argv = FLAGS ( sys . argv ) <EOL> sys . exit ( sys . modules [ '<STR_LIT:__main__>' ] . main ( argv ) ) <EOL> except ( UsageError , gflags . FlagsError ) as err : <EOL> print '<STR_LIT>' % ( <EOL> err , sys . argv , FLAGS ) <EOL> sys . exit ( <NUM_LIT:1> ) </s>
<s> r'''<STR_LIT>''' <EOL> from connection import RedirectConnection , SocksConnection , TproxyConnection <EOL> from server import Server <EOL> import handlers </s>
<s> r'''<STR_LIT>''' <EOL> from nogotofail . mitm . connection import RedirectConnection <EOL> from nogotofail . mitm . connection . handlers . selector import default_connection_selector , default_ssl_connection_selector , default_data_selector <EOL> from nogotofail . mitm import util <EOL> import socket <EOL> import select <EOL> import os <EOL> import sys <EOL> import logging <EOL> import time <EOL> class Server : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , port , app_blame , connection_class = RedirectConnection , <EOL> handler_selector = default_connection_selector , <EOL> ssl_handler_selector = default_ssl_connection_selector , <EOL> data_handler_selector = default_data_selector , <EOL> block_non_clients = False , ipv6 = False ) : <EOL> self . kill = False <EOL> self . port = port <EOL> self . read_fds = set ( ) <EOL> self . write_fds = set ( ) <EOL> self . ex_fds = set ( ) <EOL> self . _local_server_sockets = [ ] <EOL> self . fds = { } <EOL> self . connections = { } <EOL> self . connection_class = connection_class <EOL> self . handler_selector = handler_selector <EOL> self . ssl_handler_selector = ssl_handler_selector <EOL> self . data_handler_selector = data_handler_selector <EOL> self . app_blame = app_blame <EOL> self . logger = logging . getLogger ( "<STR_LIT>" ) <EOL> self . block_non_clients = block_non_clients <EOL> self . ipv6 = ipv6 <EOL> self . last_reap = time . time ( ) <EOL> def start_listening ( self ) : <EOL> self . _local_server_sockets = self . _create_server_sockets ( ) <EOL> for sock in self . _local_server_sockets : <EOL> self . read_fds . add ( sock ) <EOL> @ property <EOL> def select_fds ( self ) : <EOL> return self . read_fds , self . write_fds , self . ex_fds <EOL> def on_select ( self , r , w , x ) : <EOL> for fd in r + w + x : <EOL> if fd in self . _local_server_sockets : <EOL> self . _on_server_socket_select ( fd ) <EOL> else : <EOL> self . _on_connection_socket_select ( fd ) <EOL> now = time . time ( ) <EOL> if ( len ( r ) == <NUM_LIT:0> and now - self . last_reap > <NUM_LIT> ) or now - self . last_reap > <NUM_LIT> : <EOL> self . last_reap = now <EOL> for conn in set ( self . connections . values ( ) ) : <EOL> if not isinstance ( conn , self . connection_class ) : <EOL> continue <EOL> if now - conn . last_used > <NUM_LIT> : <EOL> self . remove ( conn ) <EOL> def remove ( self , connection ) : <EOL> connection . close ( handler_initiated = False ) <EOL> self . _remove_fds ( connection ) <EOL> def setup_connection ( self , client_socket ) : <EOL> if self . block_non_clients : <EOL> if not self . app_blame . client_available ( <EOL> client_socket . getpeername ( ) [ <NUM_LIT:0> ] ) : <EOL> self . logger . debug ( "<STR_LIT>" , <EOL> client_socket . getpeername ( ) [ <NUM_LIT:0> ] ) <EOL> client_socket . close ( ) <EOL> return <EOL> connection = ( <EOL> self . connection_class ( <EOL> self , client_socket , <EOL> self . handler_selector , <EOL> self . ssl_handler_selector , <EOL> self . data_handler_selector , <EOL> self . app_blame ) ) <EOL> if connection . start ( ) : <EOL> self . set_select_fds ( connection ) <EOL> def shutdown ( self ) : <EOL> for sock in self . read_fds | self . write_fds | self . ex_fds : <EOL> util . close_quietly ( sock ) <EOL> def set_select_fds ( self , connection ) : <EOL> """<STR_LIT>""" <EOL> self . _remove_fds ( connection ) <EOL> new_fds = connection . select_fds <EOL> self . fds [ connection ] = new_fds <EOL> r , w , x = new_fds <EOL> self . read_fds . update ( r ) <EOL> self . write_fds . update ( w ) <EOL> self . ex_fds . update ( x ) <EOL> for fd in set ( r + w + x ) : <EOL> self . connections [ fd ] = connection <EOL> def is_remote_mitm_server ( self , host , port ) : <EOL> """<STR_LIT>""" <EOL> local_v4 , local_v6 = util . get_interface_addresses ( ) <EOL> if host in local_v4 or host in local_v6 : <EOL> for socket in self . _local_server_sockets : <EOL> local = socket . getsockname ( ) <EOL> if local [ <NUM_LIT:1> ] == port : <EOL> return True <EOL> return False <EOL> def _create_server_sockets ( self ) : <EOL> sockets = [ ] <EOL> for family in [ socket . AF_INET , socket . AF_INET6 ] : <EOL> if family == socket . AF_INET6 and not self . ipv6 : <EOL> break <EOL> local_server_socket = socket . socket ( family = family ) <EOL> if family == socket . AF_INET6 : <EOL> local_server_socket . setsockopt ( socket . IPPROTO_IPV6 , socket . IPV6_V6ONLY , <NUM_LIT:1> ) <EOL> local_server_socket . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , <NUM_LIT:1> ) <EOL> self . connection_class . setup_server_socket ( local_server_socket ) <EOL> local_server_socket . bind ( ( "<STR_LIT>" , self . port ) ) <EOL> local_server_socket . listen ( <NUM_LIT:5> ) <EOL> sockets . append ( local_server_socket ) <EOL> return sockets <EOL> def _remove_fds ( self , connection ) : <EOL> if connection in self . fds : <EOL> r , w , x = self . fds [ connection ] <EOL> for fd in r : <EOL> self . read_fds . remove ( fd ) <EOL> self . connections . pop ( fd ) <EOL> for fd in w : <EOL> self . write_fds . remove ( fd ) <EOL> self . connections . pop ( fd ) <EOL> for fd in x : <EOL> self . ex_fds . remove ( fd ) <EOL> self . connections . pop ( fd ) <EOL> del self . fds [ connection ] <EOL> def _on_server_socket_select ( self , fd ) : <EOL> client_socket , client_address = None , ( None , None ) <EOL> try : <EOL> ( client_socket , client_address ) = ( <EOL> fd . accept ( ) ) <EOL> self . setup_connection ( client_socket ) <EOL> except socket . error as e : <EOL> self . logger . error ( <EOL> "<STR_LIT>" % client_address [ <NUM_LIT:0> ] ) <EOL> self . logger . exception ( e ) <EOL> util . close_quietly ( client_socket ) <EOL> def _on_connection_socket_select ( self , fd ) : <EOL> try : <EOL> conn = self . connections [ fd ] <EOL> except KeyError : <EOL> return <EOL> try : <EOL> cont = conn . bridge ( fd ) <EOL> if not cont : <EOL> self . remove ( conn ) <EOL> except Exception as e : <EOL> self . logger . exception ( e ) <EOL> self . remove ( conn ) </s>
<s> r'''<STR_LIT>''' <EOL> from nogotofail . mitm . util import Constants <EOL> from nogotofail . mitm . util . tls . types import parse <EOL> from nogotofail . mitm . util . tls . types import Cipher , Extension , Version , Random , CompressionMethod <EOL> from nogotofail . mitm . util . tls . types import TlsNotEnoughDataError <EOL> import base64 <EOL> import struct <EOL> class ServerHelloDone ( object ) : <EOL> def __init__ ( self ) : <EOL> pass <EOL> @ staticmethod <EOL> def from_stream ( body ) : <EOL> return ServerHelloDone ( ) , <NUM_LIT:0> <EOL> def to_bytes ( self ) : <EOL> return "<STR_LIT>" <EOL> class ServerHello ( object ) : <EOL> def __init__ ( <EOL> self , version , random , session_id , cipher , compression_method , <EOL> extensions ) : <EOL> self . version = version <EOL> self . random = random <EOL> self . session_id = session_id <EOL> self . cipher = cipher <EOL> self . compression_method = compression_method <EOL> self . extension_list = extensions <EOL> self . extensions = { ext . name : ext for ext in extensions } <EOL> @ staticmethod <EOL> def from_stream ( body ) : <EOL> """<STR_LIT>""" <EOL> version , index = Version . from_stream ( body ) <EOL> random , read_amt = Random . from_stream ( body [ index : ] ) <EOL> index += read_amt <EOL> sessionid_length = struct . unpack_from ( "<STR_LIT:B>" , body , index ) [ <NUM_LIT:0> ] <EOL> index += <NUM_LIT:1> <EOL> session_id , read_amt = ( <EOL> parse . parse_tls_list ( <EOL> body [ index : ] , sessionid_length , <EOL> parse . parse_opaque ) ) <EOL> index += read_amt <EOL> cipher , read_amt = Cipher . from_stream ( body [ index : ] ) <EOL> index += read_amt <EOL> method , read_amt = CompressionMethod . from_stream ( body [ index : ] ) <EOL> index += read_amt <EOL> extensions = [ ] <EOL> if len ( body ) != index : <EOL> extensions_length = struct . unpack_from ( "<STR_LIT>" , body , index ) [ <NUM_LIT:0> ] <EOL> index += <NUM_LIT:2> <EOL> extensions , read_amt = ( <EOL> parse . parse_tls_list ( <EOL> body [ index : ] , extensions_length , <EOL> Extension . from_stream ) ) <EOL> index += read_amt <EOL> return ServerHello ( <EOL> version , random , session_id , cipher , method , extensions ) , index <EOL> def to_bytes ( self ) : <EOL> return ( <EOL> self . version . to_bytes ( ) + self . random . to_bytes ( ) + parse . to_tls_list ( <EOL> self . session_id , <EOL> parse . to_opaque , <EOL> "<STR_LIT:B>" ) + <EOL> self . cipher . to_bytes ( ) + self . compression_method . to_bytes ( ) + <EOL> ( <EOL> "<STR_LIT>" <EOL> if len ( self . extension_list ) == <NUM_LIT:0> else parse . to_tls_list ( <EOL> self . extension_list , Extension . to_bytes , "<STR_LIT>" ) ) ) <EOL> def __str__ ( self ) : <EOL> extensions = "<STR_LIT:\n>" . join ( <EOL> map ( lambda s : "<STR_LIT:\t>" + str ( s ) , self . extension_list ) ) <EOL> session_id = "<STR_LIT>" <EOL> return "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" % ( self . version , self . random , self . session_id , self . cipher , self . compression_method , extensions ) <EOL> class Certificate ( object ) : <EOL> """<STR_LIT>""" <EOL> certificates = None <EOL> def __init__ ( self , certificates ) : <EOL> self . certificates = certificates <EOL> @ staticmethod <EOL> def from_stream ( body ) : <EOL> num_certificates = struct . unpack_from ( "<STR_LIT>" , "<STR_LIT:\x00>" + body [ : <NUM_LIT:3> ] ) [ <NUM_LIT:0> ] <EOL> certificates , read_amt = parse . parse_tls_list ( body [ <NUM_LIT:3> : ] , num_certificates , Certificate . _parse_certificate ) <EOL> return Certificate ( certificates ) , read_amt + <NUM_LIT:3> <EOL> def to_bytes ( self ) : <EOL> return parse . to_tls_list ( self . certificates , Certificate . _write_certificate , "<STR_LIT>" ) [ <NUM_LIT:1> : ] <EOL> def __str__ ( self ) : <EOL> return ( "<STR_LIT>" + <EOL> "<STR_LIT>" % ( len ( self . certificates ) ) + <EOL> "<STR_LIT:\n>" . join ( [ "<STR_LIT>" % ( i , cert . encode ( "<STR_LIT>" ) ) for i , cert in enumerate ( self . certificates ) ] ) ) <EOL> @ staticmethod <EOL> def _parse_certificate ( buf ) : <EOL> length = struct . unpack_from ( "<STR_LIT>" , "<STR_LIT:\x00>" + buf [ : <NUM_LIT:3> ] ) [ <NUM_LIT:0> ] <EOL> data = buf [ <NUM_LIT:3> : <NUM_LIT:3> + length ] <EOL> if len ( data ) != length : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> return data , length + <NUM_LIT:3> <EOL> @ staticmethod <EOL> def _write_certificate ( certificate_bytes ) : <EOL> return struct . pack ( "<STR_LIT>" , len ( certificate_bytes ) ) [ <NUM_LIT:1> : ] + certificate_bytes <EOL> class ClientHello ( object ) : <EOL> def __init__ ( <EOL> self , version , random , session_id , ciphers , compression_methods , <EOL> extensions ) : <EOL> self . version = version <EOL> self . random = random <EOL> self . session_id = session_id <EOL> self . ciphers = ciphers <EOL> self . compression_methods = compression_methods <EOL> self . extension_list = extensions <EOL> self . extensions = { ext . type : ext for ext in extensions } <EOL> def __str__ ( self ) : <EOL> extensions = "<STR_LIT:\n>" . join ( <EOL> map ( lambda s : "<STR_LIT:\t>" + str ( s ) , self . extension_list ) ) <EOL> ciphers = "<STR_LIT:\n>" . join ( map ( lambda s : "<STR_LIT:\t>" + str ( s ) , self . ciphers ) ) <EOL> methods = "<STR_LIT:\n>" . join ( <EOL> map ( lambda s : "<STR_LIT:\t>" + str ( s ) , self . compression_methods ) ) <EOL> session_id = "<STR_LIT>" <EOL> return "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" "<STR_LIT>" % ( self . version , self . random , self . session_id , ciphers , methods , extensions ) <EOL> @ staticmethod <EOL> def from_stream ( body ) : <EOL> """<STR_LIT>""" <EOL> version , index = Version . from_stream ( body ) <EOL> random , read_amt = Random . from_stream ( body [ index : ] ) <EOL> index += read_amt <EOL> sessionid_length = struct . unpack_from ( "<STR_LIT:B>" , body , index ) [ <NUM_LIT:0> ] <EOL> index += <NUM_LIT:1> <EOL> session_id , read_amt = ( <EOL> parse . parse_tls_list ( <EOL> body [ index : ] , sessionid_length , <EOL> parse . parse_opaque ) ) <EOL> index += read_amt <EOL> cipher_length = struct . unpack_from ( "<STR_LIT>" , body , index ) [ <NUM_LIT:0> ] <EOL> index += <NUM_LIT:2> <EOL> ciphers , read_amt = ( <EOL> parse . parse_tls_list ( <EOL> body [ index : ] , cipher_length , <EOL> Cipher . from_stream ) ) <EOL> index += read_amt <EOL> compression_length = struct . unpack_from ( "<STR_LIT:B>" , body , index ) [ <NUM_LIT:0> ] <EOL> index += <NUM_LIT:1> <EOL> compression_methods , read_amt = ( <EOL> parse . parse_tls_list ( <EOL> body [ index : ] , compression_length , <EOL> CompressionMethod . from_stream ) ) <EOL> index += read_amt <EOL> extensions = [ ] <EOL> if index != len ( body ) : <EOL> extensions_length = struct . unpack_from ( "<STR_LIT>" , body , index ) [ <NUM_LIT:0> ] <EOL> index += <NUM_LIT:2> <EOL> extensions , read_amt = ( <EOL> parse . parse_tls_list ( <EOL> body [ index : ] , extensions_length , <EOL> Extension . from_stream ) ) <EOL> index += read_amt <EOL> return ClientHello ( <EOL> version , random , session_id , ciphers , compression_methods , <EOL> extensions ) , index <EOL> def to_bytes ( self ) : <EOL> return ( self . version . to_bytes ( ) + <EOL> self . random . to_bytes ( ) + <EOL> parse . to_tls_list ( self . session_id , parse . to_opaque , "<STR_LIT:B>" ) + <EOL> parse . to_tls_list ( self . ciphers , Cipher . to_bytes , "<STR_LIT>" ) + <EOL> parse . to_tls_list ( <EOL> self . compression_methods , <EOL> CompressionMethod . to_bytes , <EOL> "<STR_LIT:B>" ) + <EOL> ( <EOL> "<STR_LIT>" <EOL> if len ( self . extension_list ) == <NUM_LIT:0> else parse . to_tls_list ( <EOL> self . extension_list , Extension . to_bytes , "<STR_LIT>" ) ) ) <EOL> class OpaqueMessage ( object ) : <EOL> def __init__ ( self , body ) : <EOL> self . body = body <EOL> @ staticmethod <EOL> def from_stream ( body ) : <EOL> return OpaqueMessage ( body ) , len ( body ) <EOL> def to_bytes ( self ) : <EOL> return self . body <EOL> name_map = { <EOL> <NUM_LIT:0> : "<STR_LIT>" , <EOL> <NUM_LIT:1> : "<STR_LIT>" , <EOL> <NUM_LIT:2> : "<STR_LIT>" , <EOL> <NUM_LIT:11> : "<STR_LIT>" , <EOL> <NUM_LIT:12> : "<STR_LIT>" , <EOL> <NUM_LIT> : "<STR_LIT>" , <EOL> <NUM_LIT> : "<STR_LIT>" , <EOL> <NUM_LIT:15> : "<STR_LIT>" , <EOL> <NUM_LIT:16> : "<STR_LIT>" , <EOL> <NUM_LIT:20> : "<STR_LIT>" , <EOL> } <EOL> class HandshakeMessage ( object ) : <EOL> class TYPE ( Constants ) : <EOL> _constants = { name . upper ( ) : value for value , name in name_map . items ( ) } <EOL> type_map = { <EOL> TYPE . CLIENT_HELLO : ClientHello , <EOL> TYPE . SERVER_HELLO : ServerHello , <EOL> TYPE . CERTIFICATE : Certificate , <EOL> TYPE . SERVER_HELLO_DONE : ServerHelloDone , <EOL> } <EOL> def __init__ ( self , type , obj ) : <EOL> self . obj = obj <EOL> self . type = type <EOL> @ staticmethod <EOL> def from_stream ( body ) : <EOL> msg_type , length = struct . unpack ( "<STR_LIT>" , body [ <NUM_LIT:0> ] + "<STR_LIT:\x00>" + body [ <NUM_LIT:1> : <NUM_LIT:4> ] ) <EOL> if msg_type not in name_map : <EOL> raise ValueError ( "<STR_LIT>" % msg_type ) <EOL> body = body [ <NUM_LIT:4> : <NUM_LIT:4> + length ] <EOL> if length != len ( body ) : <EOL> raise TlsNotEnoughDataError ( ) <EOL> type = HandshakeMessage . type_map . get ( msg_type , OpaqueMessage ) <EOL> obj , size = type . from_stream ( body ) <EOL> if len ( body ) != size : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> return HandshakeMessage ( msg_type , obj ) , length + <NUM_LIT:4> <EOL> def to_bytes ( self ) : <EOL> obj_bytes = self . obj . to_bytes ( ) <EOL> return struct . pack ( "<STR_LIT:B>" , self . type ) + struct . pack ( <EOL> "<STR_LIT>" , len ( obj_bytes ) ) [ <NUM_LIT:1> : ] + obj_bytes <EOL> def __str__ ( self ) : <EOL> return ( "<STR_LIT>" <EOL> % ( name_map . get ( self . type ) , self . type ) ) </s>
<s> from django . conf import urls <EOL> from oauth2client . contrib . django_util import views <EOL> urlpatterns = [ <EOL> urls . url ( r'<STR_LIT>' , views . oauth2_callback , name = "<STR_LIT>" ) , <EOL> urls . url ( r'<STR_LIT>' , views . oauth2_authorize , name = "<STR_LIT>" ) <EOL> ] <EOL> urls = ( urlpatterns , "<STR_LIT>" , "<STR_LIT>" ) </s>
<s> import json <EOL> import unittest <EOL> from django . conf . urls import include , url <EOL> from django . core import exceptions <EOL> from django import http <EOL> from django import test <EOL> import mock <EOL> from oauth2client . client import FlowExchangeError , OAuth2WebServerFlow <EOL> import django . conf <EOL> from oauth2client . contrib import django_util <EOL> from oauth2client . contrib . django_util import decorators <EOL> from oauth2client . contrib . django_util import site <EOL> from oauth2client . contrib . django_util import storage <EOL> from oauth2client . contrib . django_util import views <EOL> from six . moves import http_client <EOL> from six . moves . urllib import parse <EOL> urlpatterns = [ <EOL> url ( r'<STR_LIT>' , include ( site . urls ) ) <EOL> ] <EOL> urlpatterns += [ url ( r'<STR_LIT>' , include ( site . urls ) ) ] <EOL> class OAuth2SetupTest ( unittest . TestCase ) : <EOL> @ mock . patch ( "<STR_LIT>" ) <EOL> def test_settings_initialize ( self , clientsecrets ) : <EOL> django . conf . settings . GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = '<STR_LIT>' <EOL> clientsecrets . loadfile . return_value = ( <EOL> clientsecrets . TYPE_WEB , <EOL> { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> ) <EOL> oauth2_settings = django_util . OAuth2Settings ( django . conf . settings ) <EOL> self . assertTrue ( clientsecrets . loadfile . called ) <EOL> self . assertEqual ( oauth2_settings . client_id , '<STR_LIT>' ) <EOL> self . assertEqual ( oauth2_settings . client_secret , '<STR_LIT>' ) <EOL> @ mock . patch ( "<STR_LIT>" ) <EOL> def test_settings_initialize_invalid_type ( self , clientsecrets ) : <EOL> django . conf . settings . GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = '<STR_LIT>' <EOL> clientsecrets . loadfile . return_value = ( <EOL> "<STR_LIT>" , <EOL> { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> ) <EOL> self . assertRaises ( <EOL> ValueError , <EOL> django_util . OAuth2Settings . __init__ , <EOL> object . __new__ ( django_util . OAuth2Settings ) , <EOL> django . conf . settings ) <EOL> @ mock . patch ( "<STR_LIT>" ) <EOL> def test_no_settings ( self , clientsecrets ) : <EOL> django . conf . settings . GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = None <EOL> django . conf . settings . GOOGLE_OAUTH2_CLIENT_SECRET = None <EOL> django . conf . settings . GOOGLE_OAUTH2_CLIENT_ID = None <EOL> self . assertRaises ( <EOL> exceptions . ImproperlyConfigured , <EOL> django_util . OAuth2Settings . __init__ , <EOL> object . __new__ ( django_util . OAuth2Settings ) , <EOL> django . conf . settings ) <EOL> @ mock . patch ( "<STR_LIT>" ) <EOL> def test_no_session_middleware ( self , clientsecrets ) : <EOL> old_classes = django . conf . settings . MIDDLEWARE_CLASSES <EOL> django . conf . settings . MIDDLEWARE_CLASSES = ( ) <EOL> self . assertRaises ( <EOL> exceptions . ImproperlyConfigured , <EOL> django_util . OAuth2Settings . __init__ , <EOL> object . __new__ ( django_util . OAuth2Settings ) , <EOL> django . conf . settings ) <EOL> django . conf . settings . MIDDLEWARE_CLASSES = old_classes <EOL> class TestWithSession ( test . TestCase ) : <EOL> def setUp ( self ) : <EOL> self . factory = test . RequestFactory ( ) <EOL> from django . contrib . sessions . backends . file import SessionStore <EOL> store = SessionStore ( ) <EOL> store . save ( ) <EOL> self . session = store <EOL> class OAuth2EnabledDecoratorTest ( TestWithSession ) : <EOL> def test_no_credentials_without_credentials ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' ) <EOL> request . session = self . session <EOL> @ decorators . oauth_enabled <EOL> def test_view ( request ) : <EOL> return http . HttpResponse ( "<STR_LIT:test>" ) <EOL> response = test_view ( request ) <EOL> self . assertEquals ( response . status_code , http_client . OK ) <EOL> self . assertIsNotNone ( request . oauth ) <EOL> self . assertFalse ( request . oauth . has_credentials ( ) ) <EOL> self . assertIsNone ( request . oauth . http ) <EOL> @ mock . patch ( '<STR_LIT>' ) <EOL> def test_has_credentials_in_storage ( self , OAuth2Credentials ) : <EOL> request = self . factory . get ( '<STR_LIT>' ) <EOL> request . session = mock . MagicMock ( ) <EOL> credentials_mock = mock . Mock ( <EOL> scopes = set ( django . conf . settings . GOOGLE_OAUTH2_SCOPES ) ) <EOL> credentials_mock . has_scopes . return_value = True <EOL> credentials_mock . invalid = False <EOL> OAuth2Credentials . from_json . return_value = credentials_mock <EOL> @ decorators . oauth_enabled <EOL> def test_view ( request ) : <EOL> return http . HttpResponse ( "<STR_LIT:test>" ) <EOL> response = test_view ( request ) <EOL> self . assertEquals ( response . status_code , http_client . OK ) <EOL> self . assertEquals ( response . content , b"<STR_LIT:test>" ) <EOL> self . assertTrue ( request . oauth . has_credentials ( ) ) <EOL> self . assertIsNotNone ( request . oauth . http ) <EOL> @ mock . patch ( '<STR_LIT>' ) <EOL> def test_specified_scopes ( self , OAuth2Credentials ) : <EOL> request = self . factory . get ( '<STR_LIT>' ) <EOL> request . session = mock . MagicMock ( ) <EOL> credentials_mock = mock . Mock ( <EOL> scopes = set ( django . conf . settings . GOOGLE_OAUTH2_SCOPES ) ) <EOL> credentials_mock . has_scopes = True <EOL> credentials_mock . is_valid = True <EOL> OAuth2Credentials . from_json . return_value = credentials_mock <EOL> @ decorators . oauth_enabled ( scopes = [ '<STR_LIT>' ] ) <EOL> def test_view ( request ) : <EOL> return http . HttpResponse ( "<STR_LIT>" ) <EOL> response = test_view ( request ) <EOL> self . assertEquals ( response . status_code , http_client . OK ) <EOL> self . assertIsNotNone ( request . oauth ) <EOL> self . assertFalse ( request . oauth . has_credentials ( ) ) <EOL> class OAuth2RequiredDecoratorTest ( TestWithSession ) : <EOL> def test_redirects_without_credentials ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' ) <EOL> request . session = self . session <EOL> @ decorators . oauth_required <EOL> def test_view ( request ) : <EOL> return http . HttpResponse ( "<STR_LIT:test>" ) <EOL> response = test_view ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseRedirect ) ) <EOL> self . assertEquals ( parse . urlparse ( response [ '<STR_LIT>' ] ) . path , <EOL> "<STR_LIT>" ) <EOL> self . assertTrue ( <EOL> "<STR_LIT>" in parse . urlparse ( response [ '<STR_LIT>' ] ) . query ) <EOL> self . assertEquals ( response . status_code , <NUM_LIT> ) <EOL> @ mock . patch ( '<STR_LIT>' , autospec = True ) <EOL> def test_has_credentials_in_storage ( self , UserOAuth2 ) : <EOL> request = self . factory . get ( '<STR_LIT>' ) <EOL> request . session = mock . MagicMock ( ) <EOL> @ decorators . oauth_required <EOL> def test_view ( request ) : <EOL> return http . HttpResponse ( "<STR_LIT:test>" ) <EOL> my_user_oauth = mock . MagicMock ( ) <EOL> UserOAuth2 . return_value = my_user_oauth <EOL> my_user_oauth . has_credentials . return_value = True <EOL> response = test_view ( request ) <EOL> self . assertEquals ( response . status_code , http_client . OK ) <EOL> self . assertEquals ( response . content , b"<STR_LIT:test>" ) <EOL> @ mock . patch ( '<STR_LIT>' ) <EOL> def test_has_credentials_in_storage_no_scopes ( self , OAuth2Credentials ) : <EOL> request = self . factory . get ( '<STR_LIT>' ) <EOL> request . session = mock . MagicMock ( ) <EOL> credentials_mock = mock . Mock ( <EOL> scopes = set ( django . conf . settings . GOOGLE_OAUTH2_SCOPES ) ) <EOL> credentials_mock . has_scopes . return_value = False <EOL> OAuth2Credentials . from_json . return_value = credentials_mock <EOL> @ decorators . oauth_required <EOL> def test_view ( request ) : <EOL> return http . HttpResponse ( "<STR_LIT:test>" ) <EOL> response = test_view ( request ) <EOL> self . assertEquals ( response . status_code , <NUM_LIT> ) <EOL> @ mock . patch ( '<STR_LIT>' ) <EOL> def test_specified_scopes ( self , OAuth2Credentials ) : <EOL> request = self . factory . get ( '<STR_LIT>' ) <EOL> request . session = mock . MagicMock ( ) <EOL> credentials_mock = mock . Mock ( <EOL> scopes = set ( django . conf . settings . GOOGLE_OAUTH2_SCOPES ) ) <EOL> credentials_mock . has_scopes = False <EOL> OAuth2Credentials . from_json . return_value = credentials_mock <EOL> @ decorators . oauth_required ( scopes = [ '<STR_LIT>' ] ) <EOL> def test_view ( request ) : <EOL> return http . HttpResponse ( "<STR_LIT>" ) <EOL> response = test_view ( request ) <EOL> self . assertEquals ( response . status_code , <NUM_LIT> ) <EOL> class Oauth2AuthorizeTest ( TestWithSession ) : <EOL> def test_authorize_works ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' ) <EOL> request . session = self . session <EOL> response = views . oauth2_authorize ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseRedirect ) ) <EOL> def test_authorize_works_explicit_return_url ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' , data = { <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } ) <EOL> request . session = self . session <EOL> response = views . oauth2_authorize ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseRedirect ) ) <EOL> class Oauth2CallbackTest ( TestWithSession ) : <EOL> def setUp ( self ) : <EOL> global mycallback <EOL> mycallback = mock . Mock ( ) <EOL> super ( Oauth2CallbackTest , self ) . setUp ( ) <EOL> self . CSRF_TOKEN = "<STR_LIT>" <EOL> self . RETURN_URL = "<STR_LIT>" <EOL> self . fake_state = { <EOL> '<STR_LIT>' : self . CSRF_TOKEN , <EOL> '<STR_LIT>' : self . RETURN_URL , <EOL> '<STR_LIT>' : django . conf . settings . GOOGLE_OAUTH2_SCOPES <EOL> } <EOL> @ mock . patch ( "<STR_LIT>" ) <EOL> def test_callback_works ( self , pickle ) : <EOL> request = self . factory . get ( '<STR_LIT>' , data = { <EOL> "<STR_LIT:state>" : json . dumps ( self . fake_state ) , <EOL> "<STR_LIT:code>" : <NUM_LIT> <EOL> } ) <EOL> self . session [ '<STR_LIT>' ] = self . CSRF_TOKEN <EOL> flow = OAuth2WebServerFlow ( <EOL> client_id = '<STR_LIT>' , <EOL> client_secret = '<STR_LIT>' , <EOL> scope = [ '<STR_LIT:email>' ] , <EOL> state = json . dumps ( self . fake_state ) , <EOL> redirect_uri = request . build_absolute_uri ( "<STR_LIT>" ) ) <EOL> self . session [ '<STR_LIT>' . format ( self . CSRF_TOKEN ) ] = pickle . dumps ( flow ) <EOL> flow . step2_exchange = mock . Mock ( ) <EOL> pickle . loads . return_value = flow <EOL> request . session = self . session <EOL> response = views . oauth2_callback ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseRedirect ) ) <EOL> self . assertEquals ( response . status_code , <NUM_LIT> ) <EOL> self . assertEquals ( response [ '<STR_LIT>' ] , self . RETURN_URL ) <EOL> @ mock . patch ( "<STR_LIT>" ) <EOL> def test_callback_handles_bad_flow_exchange ( self , pickle ) : <EOL> request = self . factory . get ( '<STR_LIT>' , data = { <EOL> "<STR_LIT:state>" : json . dumps ( self . fake_state ) , <EOL> "<STR_LIT:code>" : <NUM_LIT> <EOL> } ) <EOL> self . session [ '<STR_LIT>' ] = self . CSRF_TOKEN <EOL> flow = OAuth2WebServerFlow ( <EOL> client_id = '<STR_LIT>' , <EOL> client_secret = '<STR_LIT>' , <EOL> scope = [ '<STR_LIT:email>' ] , <EOL> state = json . dumps ( self . fake_state ) , <EOL> redirect_uri = request . build_absolute_uri ( "<STR_LIT>" ) ) <EOL> self . session [ '<STR_LIT>' . format ( self . CSRF_TOKEN ) ] = pickle . dumps ( flow ) <EOL> def local_throws ( code ) : <EOL> raise FlowExchangeError ( "<STR_LIT:test>" ) <EOL> flow . step2_exchange = local_throws <EOL> pickle . loads . return_value = flow <EOL> request . session = self . session <EOL> response = views . oauth2_callback ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseBadRequest ) ) <EOL> def test_error_returns_bad_request ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' , data = { <EOL> "<STR_LIT:error>" : "<STR_LIT>" , <EOL> } ) <EOL> response = views . oauth2_callback ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseBadRequest ) ) <EOL> self . assertTrue ( b"<STR_LIT>" in response . content ) <EOL> def test_no_session ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' , data = { <EOL> "<STR_LIT:code>" : <NUM_LIT> , <EOL> "<STR_LIT:state>" : json . dumps ( self . fake_state ) <EOL> } ) <EOL> request . session = self . session <EOL> response = views . oauth2_callback ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseBadRequest ) ) <EOL> self . assertEquals ( <EOL> response . content , b'<STR_LIT>' ) <EOL> def test_missing_state_returns_bad_request ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' , data = { <EOL> "<STR_LIT:code>" : <NUM_LIT> <EOL> } ) <EOL> self . session [ '<STR_LIT>' ] = "<STR_LIT>" <EOL> request . session = self . session <EOL> response = views . oauth2_callback ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseBadRequest ) ) <EOL> def test_bad_state ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' , data = { <EOL> "<STR_LIT:code>" : <NUM_LIT> , <EOL> "<STR_LIT:state>" : json . dumps ( { "<STR_LIT>" : "<STR_LIT:state>" } ) <EOL> } ) <EOL> self . session [ '<STR_LIT>' ] = "<STR_LIT>" <EOL> request . session = self . session <EOL> response = views . oauth2_callback ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseBadRequest ) ) <EOL> self . assertEquals ( response . content , b'<STR_LIT>' ) <EOL> def test_bad_csrf ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' , data = { <EOL> "<STR_LIT:state>" : json . dumps ( self . fake_state ) , <EOL> "<STR_LIT:code>" : <NUM_LIT> <EOL> } ) <EOL> self . session [ '<STR_LIT>' ] = "<STR_LIT>" <EOL> request . session = self . session <EOL> response = views . oauth2_callback ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseBadRequest ) ) <EOL> self . assertEquals ( response . content , b'<STR_LIT>' ) <EOL> def test_no_saved_flow ( self ) : <EOL> request = self . factory . get ( '<STR_LIT>' , data = { <EOL> "<STR_LIT:state>" : json . dumps ( self . fake_state ) , <EOL> "<STR_LIT:code>" : <NUM_LIT> <EOL> } ) <EOL> self . session [ '<STR_LIT>' ] = self . CSRF_TOKEN <EOL> self . session [ '<STR_LIT>' . format ( self . CSRF_TOKEN ) ] = None <EOL> request . session = self . session <EOL> response = views . oauth2_callback ( request ) <EOL> self . assertTrue ( isinstance ( response , http . HttpResponseBadRequest ) ) <EOL> self . assertEquals ( response . content , b'<STR_LIT>' ) <EOL> class MockObjectWithSession ( object ) : <EOL> def __init__ ( self , session ) : <EOL> self . session = session <EOL> class StorageTest ( TestWithSession ) : <EOL> def test_session_delete ( self ) : <EOL> self . session [ storage . _CREDENTIALS_KEY ] = "<STR_LIT>" <EOL> request = MockObjectWithSession ( self . session ) <EOL> django_storage = storage . get_storage ( request ) <EOL> django_storage . delete ( ) <EOL> self . assertIsNone ( self . session . get ( storage . _CREDENTIALS_KEY ) ) <EOL> def test_session_delete_nothing ( self ) : <EOL> request = MockObjectWithSession ( self . session ) <EOL> django_storage = storage . get_storage ( request ) <EOL> django_storage . delete ( ) </s>
<s> """<STR_LIT>""" <EOL> import json <EOL> import logging <EOL> from enum import Enum <EOL> import openhtf <EOL> from openhtf import util <EOL> from openhtf . exe import phase_data <EOL> from openhtf . io import test_record <EOL> from openhtf . util import data <EOL> from openhtf . util import logs <EOL> from openhtf . util import measurements <EOL> _LOG = logging . getLogger ( __name__ ) <EOL> class BlankDutIdError ( Exception ) : <EOL> """<STR_LIT>""" <EOL> class FrameworkError ( Exception ) : <EOL> """<STR_LIT>""" <EOL> class TestRecordAlreadyFinishedError ( Exception ) : <EOL> """<STR_LIT>""" <EOL> class TestState ( object ) : <EOL> """<STR_LIT>""" <EOL> State = Enum ( '<STR_LIT>' , [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> def __init__ ( self , test_data , plug_map , dut_id , station_id ) : <EOL> self . _state = self . State . CREATED <EOL> self . record = test_record . TestRecord ( <EOL> dut_id = dut_id , station_id = station_id , code_info = test_data . code_info , <EOL> metadata = test_data . metadata ) <EOL> self . logger = logging . getLogger ( logs . RECORD_LOGGER ) <EOL> self . _record_handler = logs . RecordHandler ( self . record ) <EOL> self . logger . addHandler ( self . _record_handler ) <EOL> self . phase_data = phase_data . PhaseData ( self . logger , plug_map , self . record ) <EOL> self . running_phase_record = None <EOL> self . pending_phases = list ( test_data . phases ) <EOL> def __del__ ( self ) : <EOL> self . logger . removeHandler ( self . _record_handler ) <EOL> def AsJSON ( self ) : <EOL> """<STR_LIT>""" <EOL> return json . dumps ( data . ConvertToBaseTypes ( self ) ) <EOL> def _asdict ( self ) : <EOL> """<STR_LIT>""" <EOL> return { <EOL> '<STR_LIT:status>' : self . _state . name , <EOL> '<STR_LIT>' : self . record , <EOL> '<STR_LIT>' : self . phase_data , <EOL> '<STR_LIT>' : self . running_phase_record , <EOL> '<STR_LIT>' : [ ( phase . func . __name__ , phase . func . __doc__ ) <EOL> for phase in self . pending_phases ] } <EOL> def GetLastRunPhaseName ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . running_phase_record : <EOL> return self . running_phase_record . name <EOL> return None <EOL> def SetStateFromPhaseOutcome ( self , phase_outcome ) : <EOL> """<STR_LIT>""" <EOL> if phase_outcome . raised_exception : <EOL> self . record . outcome = test_record . Outcome . ERROR <EOL> code = str ( type ( phase_outcome . phase_result ) . __name__ ) <EOL> description = str ( phase_outcome . phase_result ) . decode ( '<STR_LIT:utf8>' , '<STR_LIT:replace>' ) <EOL> self . record . AddOutcomeDetails ( code , description ) <EOL> self . _state = self . State . COMPLETED <EOL> elif phase_outcome . is_timeout : <EOL> self . record . outcome = test_record . Outcome . TIMEOUT <EOL> self . _state = self . State . COMPLETED <EOL> elif phase_outcome . phase_result == openhtf . PhaseResult . FAIL : <EOL> self . record . outcome = test_record . Outcome . FAIL <EOL> self . _state = self . State . COMPLETED <EOL> return self . _state == self . State . COMPLETED <EOL> def SetStateRunning ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _state = self . State . RUNNING <EOL> def SetStateFinished ( self ) : <EOL> """<STR_LIT>""" <EOL> if any ( meas . outcome != measurements . Outcome . PASS <EOL> for phase in self . record . phases <EOL> for meas in phase . measurements . itervalues ( ) ) : <EOL> self . record . outcome = test_record . Outcome . FAIL <EOL> else : <EOL> self . record . outcome = test_record . Outcome . PASS <EOL> def GetFinishedRecord ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . record . end_time_millis : <EOL> raise TestRecordAlreadyFinishedError ( '<STR_LIT>' , <EOL> self . record . end_time_millis ) <EOL> if not self . record . dut_id : <EOL> raise BlankDutIdError ( <EOL> '<STR_LIT>' ) <EOL> if not self . record . outcome : <EOL> raise FrameworkError ( <EOL> '<STR_LIT>' ) <EOL> self . logger . debug ( '<STR_LIT>' , <EOL> self . record . outcome . name ) <EOL> self . record . end_time_millis = util . TimeMillis ( ) <EOL> self . logger . removeHandler ( self . _record_handler ) <EOL> return self . record <EOL> def __str__ ( self ) : <EOL> return '<STR_LIT>' % ( <EOL> type ( self ) . __name__ , self . record . dut_id , self . record . station_id , <EOL> self . GetLastRunPhaseName ( ) , <EOL> ) <EOL> __repr__ = __str__ </s>
<s> """<STR_LIT>""" <EOL> import argparse <EOL> import collections <EOL> import functools <EOL> import logging <EOL> import os <EOL> import re <EOL> import sys <EOL> import traceback <EOL> from datetime import datetime <EOL> from openhtf import util <EOL> from openhtf . util import argv <EOL> from openhtf . util import functions <EOL> DEFAULT_LEVEL = '<STR_LIT>' <EOL> DEFAULT_LOGFILE_LEVEL = '<STR_LIT>' <EOL> QUIET = False <EOL> LOGFILE = None <EOL> LEVEL_CHOICES = [ '<STR_LIT>' , '<STR_LIT:info>' , '<STR_LIT>' , '<STR_LIT:error>' , '<STR_LIT>' ] <EOL> ARG_PARSER = argv . ModuleParser ( ) <EOL> ARG_PARSER . add_argument ( <EOL> '<STR_LIT>' , default = DEFAULT_LEVEL , choices = LEVEL_CHOICES , <EOL> action = argv . StoreInModule , target = '<STR_LIT>' % __name__ , <EOL> help = '<STR_LIT>' ) <EOL> ARG_PARSER . add_argument ( <EOL> '<STR_LIT>' , action = argv . StoreInModule , target = '<STR_LIT>' % __name__ , <EOL> proxy = argparse . _StoreTrueAction , help = "<STR_LIT>" ) <EOL> ARG_PARSER . add_argument ( <EOL> '<STR_LIT>' , action = argv . StoreInModule , target = '<STR_LIT>' % __name__ , <EOL> help = '<STR_LIT>' ) <EOL> ARG_PARSER . add_argument ( <EOL> '<STR_LIT>' , default = DEFAULT_LEVEL , choices = LEVEL_CHOICES , <EOL> action = argv . StoreInModule , target = '<STR_LIT>' % __name__ , <EOL> help = '<STR_LIT>' ) <EOL> LOGGER_PREFIX = '<STR_LIT>' <EOL> RECORD_LOGGER = '<STR_LIT:.>' . join ( ( LOGGER_PREFIX , '<STR_LIT>' ) ) <EOL> _LOGONCE_SEEN = set ( ) <EOL> LogRecord = collections . namedtuple ( <EOL> '<STR_LIT>' , '<STR_LIT>' ) <EOL> def LogOnce ( log_func , msg , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> if msg not in _LOGONCE_SEEN : <EOL> log_func ( msg , * args , ** kwargs ) <EOL> _LOGONCE_SEEN . add ( msg ) <EOL> class MacAddressLogFilter ( logging . Filter ) : <EOL> """<STR_LIT>""" <EOL> MAC_REPLACE_RE = re . compile ( r"""<STR_LIT>""" , re . IGNORECASE | re . VERBOSE ) <EOL> MAC_REPLACEMENT = r'<STR_LIT>' <EOL> def __init__ ( self ) : <EOL> super ( MacAddressLogFilter , self ) . __init__ ( ) <EOL> def filter ( self , record ) : <EOL> if self . MAC_REPLACE_RE . search ( record . getMessage ( ) ) : <EOL> record . msg = self . MAC_REPLACE_RE . sub ( self . MAC_REPLACEMENT , record . msg ) <EOL> record . args = tuple ( [ <EOL> self . MAC_REPLACE_RE . sub ( self . MAC_REPLACEMENT , str ( arg ) ) <EOL> if isinstance ( arg , basestring ) <EOL> else arg for arg in record . args ] ) <EOL> return True <EOL> MAC_FILTER = MacAddressLogFilter ( ) <EOL> class RecordHandler ( logging . Handler ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , test_record ) : <EOL> super ( RecordHandler , self ) . __init__ ( level = logging . DEBUG ) <EOL> self . _test_record = test_record <EOL> self . addFilter ( MAC_FILTER ) <EOL> def emit ( self , record ) : <EOL> """<STR_LIT>""" <EOL> message = record . getMessage ( ) <EOL> if record . exc_info : <EOL> message += '<STR_LIT:\n>' + '<STR_LIT>' . join ( traceback . format_exception ( <EOL> * record . exc_info ) ) <EOL> message = message . decode ( '<STR_LIT:utf8>' , '<STR_LIT:replace>' ) <EOL> log_record = LogRecord ( <EOL> record . levelno , record . name , os . path . basename ( record . pathname ) , <EOL> record . lineno , int ( record . created * <NUM_LIT:1000> ) , message <EOL> ) <EOL> self . _test_record . log_records . append ( log_record ) <EOL> @ functions . CallOnce <EOL> def SetupLogger ( ) : <EOL> """<STR_LIT>""" <EOL> record_logger = logging . getLogger ( RECORD_LOGGER ) <EOL> record_logger . propagate = False <EOL> record_logger . setLevel ( logging . DEBUG ) <EOL> record_logger . addHandler ( logging . StreamHandler ( stream = sys . stdout ) ) <EOL> logger = logging . getLogger ( LOGGER_PREFIX ) <EOL> logger . propagate = False <EOL> logger . setLevel ( logging . DEBUG ) <EOL> formatter = logging . Formatter ( '<STR_LIT>' ) <EOL> if LOGFILE : <EOL> try : <EOL> cur_time = str ( util . TimeMillis ( ) ) <EOL> file_handler = logging . FileHandler ( '<STR_LIT>' % ( LOGFILE , cur_time ) ) <EOL> file_handler . setFormatter ( formatter ) <EOL> file_handler . setLevel ( DEFAULT_LOGFILE_LEVEL . upper ( ) ) <EOL> file_handler . addFilter ( MAC_FILTER ) <EOL> logger . addHandler ( file_handler ) <EOL> except IOError as exception : <EOL> print ( '<STR_LIT>' <EOL> '<STR_LIT>' % exception ) <EOL> if not QUIET : <EOL> console_handler = logging . StreamHandler ( stream = sys . stderr ) <EOL> console_handler . setFormatter ( formatter ) <EOL> console_handler . setLevel ( DEFAULT_LEVEL . upper ( ) ) <EOL> console_handler . addFilter ( MAC_FILTER ) <EOL> logger . addHandler ( console_handler ) </s>
<s> """<STR_LIT>""" <EOL> import unittest <EOL> from pinject import annotations <EOL> from pinject import binding_keys <EOL> class BindingKeyTest ( unittest . TestCase ) : <EOL> def test_repr ( self ) : <EOL> binding_key = binding_keys . BindingKey ( <EOL> '<STR_LIT>' , annotations . Annotation ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( <EOL> '<STR_LIT>' , <EOL> repr ( binding_key ) ) <EOL> def test_str ( self ) : <EOL> binding_key = binding_keys . BindingKey ( <EOL> '<STR_LIT>' , annotations . Annotation ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( <EOL> '<STR_LIT>' , <EOL> str ( binding_key ) ) <EOL> def test_annotation_as_adjective ( self ) : <EOL> binding_key = binding_keys . BindingKey ( <EOL> '<STR_LIT>' , annotations . Annotation ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( '<STR_LIT>' , <EOL> binding_key . annotation_as_adjective ( ) ) <EOL> def test_equal_if_same_arg_name_and_annotation ( self ) : <EOL> binding_key_one = binding_keys . BindingKey ( <EOL> '<STR_LIT>' , annotations . Annotation ( '<STR_LIT>' ) ) <EOL> binding_key_two = binding_keys . BindingKey ( <EOL> '<STR_LIT>' , annotations . Annotation ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( binding_key_one , binding_key_two ) <EOL> self . assertEqual ( hash ( binding_key_one ) , hash ( binding_key_two ) ) <EOL> self . assertEqual ( str ( binding_key_one ) , str ( binding_key_two ) ) <EOL> def test_unequal_if_not_same_arg_name ( self ) : <EOL> binding_key_one = binding_keys . BindingKey ( <EOL> '<STR_LIT>' , annotations . Annotation ( '<STR_LIT>' ) ) <EOL> binding_key_two = binding_keys . BindingKey ( <EOL> '<STR_LIT>' , annotations . Annotation ( '<STR_LIT>' ) ) <EOL> self . assertNotEqual ( binding_key_one , binding_key_two ) <EOL> self . assertNotEqual ( hash ( binding_key_one ) , hash ( binding_key_two ) ) <EOL> self . assertNotEqual ( str ( binding_key_one ) , str ( binding_key_two ) ) <EOL> def test_unequal_if_not_same_annotation ( self ) : <EOL> binding_key_one = binding_keys . BindingKey ( <EOL> '<STR_LIT>' , annotations . Annotation ( '<STR_LIT>' ) ) <EOL> binding_key_two = binding_keys . BindingKey ( <EOL> '<STR_LIT>' , annotations . Annotation ( '<STR_LIT>' ) ) <EOL> self . assertNotEqual ( binding_key_one , binding_key_two ) <EOL> self . assertNotEqual ( hash ( binding_key_one ) , hash ( binding_key_two ) ) <EOL> self . assertNotEqual ( str ( binding_key_one ) , str ( binding_key_two ) ) <EOL> class NewBindingKeyTest ( unittest . TestCase ) : <EOL> def test_without_annotation ( self ) : <EOL> binding_key = binding_keys . new ( '<STR_LIT>' ) <EOL> self . assertEqual ( '<STR_LIT>' , <EOL> str ( binding_key ) ) <EOL> def test_with_annotation ( self ) : <EOL> binding_key = binding_keys . new ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . assertEqual ( <EOL> '<STR_LIT>' , <EOL> str ( binding_key ) ) </s>
<s> from pygtrie import * </s>
<s> import struct <EOL> from mod_pywebsocket import common <EOL> from mod_pywebsocket import stream <EOL> def web_socket_do_extra_handshake ( request ) : <EOL> pass <EOL> def web_socket_transfer_data ( request ) : <EOL> while True : <EOL> line = request . ws_stream . receive_message ( ) <EOL> if line is None : <EOL> return <EOL> code , reason = line . split ( '<STR_LIT:U+0020>' , <NUM_LIT:1> ) <EOL> if code is None or reason is None : <EOL> return <EOL> request . ws_stream . close_connection ( int ( code ) , reason ) <EOL> def web_socket_passive_closing_handshake ( request ) : <EOL> code , reason = request . ws_close_code , request . ws_close_reason <EOL> if code == common . STATUS_NO_STATUS_RECEIVED : <EOL> code = None <EOL> reason = '<STR_LIT>' <EOL> return code , reason </s>
<s> """<STR_LIT>""" <EOL> from distutils . core import setup , Extension <EOL> import sys <EOL> _PACKAGE_NAME = '<STR_LIT>' <EOL> _USE_FAST_MASKING = False <EOL> if sys . version < '<STR_LIT>' : <EOL> print >> sys . stderr , '<STR_LIT>' % _PACKAGE_NAME <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> if _USE_FAST_MASKING : <EOL> setup ( ext_modules = [ <EOL> Extension ( <EOL> '<STR_LIT>' , <EOL> [ '<STR_LIT>' ] , <EOL> swig_opts = [ '<STR_LIT>' ] ) ] ) <EOL> setup ( author = '<STR_LIT>' , <EOL> author_email = '<STR_LIT>' , <EOL> description = '<STR_LIT>' , <EOL> long_description = ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> license = '<STR_LIT>' , <EOL> name = _PACKAGE_NAME , <EOL> packages = [ _PACKAGE_NAME , _PACKAGE_NAME + '<STR_LIT>' ] , <EOL> url = '<STR_LIT>' , <EOL> version = '<STR_LIT>' , <EOL> ) </s>
<s> """<STR_LIT>""" <EOL> def no_web_socket_do_extra_handshake ( request ) : <EOL> pass <EOL> def web_socket_transfer_data ( request ) : <EOL> request . connection . write ( <EOL> '<STR_LIT>' % <EOL> ( request . ws_resource , request . ws_protocol ) ) </s>