code
stringlengths 9
256k
|
---|
<s> from django . db import models <EOL> class Restaurant ( models . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:255> ) <EOL> class Bar ( Restaurant ) : <EOL> min_age = models . IntegerField ( ) <EOL> class Pizzeria ( Restaurant ) : <EOL> specialty = models . CharField ( max_length = <NUM_LIT:255> ) <EOL> class PizzeriaBar ( Bar , Pizzeria ) : <EOL> pizza_bar_specific_field = models . CharField ( max_length = <NUM_LIT:255> ) </s>
|
<s> from lino . utils . test import DocTest <EOL> from lino . utils . djangotest import WebIndexTestCase </s>
|
<s> from django . db import models <EOL> from lino . api import dd <EOL> class Foo ( dd . Model ) : <EOL> name = models . CharField ( max_length = <NUM_LIT:100> , blank = True ) <EOL> remarks = models . TextField ( "<STR_LIT>" , blank = True ) <EOL> input_mask_test = dd . CharField ( <EOL> "<STR_LIT>" , <EOL> blank = True , <EOL> max_length = <NUM_LIT:200> , <EOL> help_text = """<STR_LIT>""" , <EOL> mask_re = '<STR_LIT>' ) <EOL> class Foos ( dd . Table ) : <EOL> model = Foo <EOL> column_names = '<STR_LIT>' <EOL> detail_layout = """<STR_LIT>""" <EOL> insert_layout = """<STR_LIT>""" </s>
|
<s> import os <EOL> import sys <EOL> sys . path . insert ( <NUM_LIT:0> , os . path . abspath ( '<STR_LIT:..>' ) ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> os . environ [ "<STR_LIT>" ] = "<STR_LIT>" <EOL> from django . core . management import execute_from_command_line <EOL> execute_from_command_line ( sys . argv ) </s>
|
<s> from lino . projects . std . settings import * <EOL> class Site ( Site ) : <EOL> demo_fixtures = "<STR_LIT>" <EOL> languages = '<STR_LIT>' <EOL> def get_installed_apps ( self ) : <EOL> yield super ( Site , self ) . get_installed_apps ( ) <EOL> yield '<STR_LIT>' <EOL> yield '<STR_LIT>' <EOL> yield '<STR_LIT>' <EOL> yield '<STR_LIT>' <EOL> yield '<STR_LIT>' <EOL> yield '<STR_LIT>' <EOL> yield '<STR_LIT>' <EOL> def setup_menu ( self , profile , main ) : <EOL> m = main . add_menu ( "<STR_LIT>" , _ ( "<STR_LIT>" ) ) <EOL> m . add_action ( MyEntries ) <EOL> SITE = Site ( globals ( ) ) </s>
|
<s> from __future__ import unicode_literals <EOL> from past . builtins import basestring <EOL> from builtins import object <EOL> """<STR_LIT>""" <EOL> import logging <EOL> logger = logging . getLogger ( __name__ ) <EOL> import os <EOL> from os . path import join , dirname , exists <EOL> import sys <EOL> import time <EOL> import codecs <EOL> import atexit <EOL> from django . conf import settings <EOL> from django . core import exceptions <EOL> from django . utils . encoding import force_text <EOL> from django . db import models <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from lino import AFTER17 <EOL> from lino . utils import codetime <EOL> from lino . core import layouts <EOL> from lino . core import actors <EOL> from lino . core import actions <EOL> from lino . core import fields <EOL> from lino . core import dbtables <EOL> from lino . core import tables <EOL> from lino . core import constants <EOL> from lino . core import views <EOL> from lino . utils import class_dict_items <EOL> from lino . utils . memo import Parser <EOL> from lino . core . requests import ActorRequest <EOL> from lino . core . model import Model <EOL> from lino . core . store import Store <EOL> from lino . core . renderer import HtmlRenderer , TextRenderer <EOL> from lino . core . signals import ( pre_ui_build , post_ui_build , <EOL> pre_analyze , post_analyze ) <EOL> from . plugin import Plugin <EOL> from . ddh import DisableDeleteHandler <EOL> from . utils import resolve_model <EOL> from . utils import is_devserver <EOL> from . utils import full_model_name as fmn <EOL> from . utils import obj2str <EOL> from . utils import get_models <EOL> from . exceptions import ChangedAPI <EOL> from . gfks import GenericForeignKey <EOL> def set_default_verbose_name ( f ) : <EOL> """<STR_LIT>""" <EOL> if f . verbose_name == f . name . replace ( '<STR_LIT:_>' , '<STR_LIT:U+0020>' ) : <EOL> f . verbose_name = f . rel . model . _meta . verbose_name <EOL> CLONEABLE_ATTRS = frozenset ( """<STR_LIT>""" . split ( ) ) <EOL> GFK_TARGETS = ( models . AutoField , models . IntegerField ) <EOL> class CallbackChoice ( object ) : <EOL> def __init__ ( self , name , func , label ) : <EOL> self . name = name <EOL> self . func = func <EOL> self . label = label <EOL> class Callback ( object ) : <EOL> """<STR_LIT>""" <EOL> title = _ ( '<STR_LIT>' ) <EOL> def __init__ ( self , ar , message ) : <EOL> self . message = message <EOL> self . choices = [ ] <EOL> self . choices_dict = { } <EOL> self . ar = ar <EOL> def __repr__ ( self ) : <EOL> return "<STR_LIT>" % self . message <EOL> def set_title ( self , title ) : <EOL> self . title = title <EOL> def add_choice ( self , name , func , label ) : <EOL> """<STR_LIT>""" <EOL> assert not name in self . choices_dict <EOL> allowed_names = ( "<STR_LIT:yes>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) <EOL> if not name in allowed_names : <EOL> raise Exception ( "<STR_LIT>" % allowed_names ) <EOL> cbc = CallbackChoice ( name , func , label ) <EOL> self . choices . append ( cbc ) <EOL> self . choices_dict [ name ] = cbc <EOL> return cbc <EOL> class Kernel ( object ) : <EOL> """<STR_LIT>""" <EOL> default_ui = None <EOL> def __init__ ( self , site ) : <EOL> self . pending_threads = { } <EOL> self . site = site <EOL> self . GFK_LIST = [ ] <EOL> self . kernel_startup ( site ) <EOL> self . code_mtime = codetime ( ) <EOL> self . memo_parser = Parser ( ) <EOL> def url2html ( parser , s ) : <EOL> url_text = s . split ( None , <NUM_LIT:1> ) <EOL> if len ( url_text ) == <NUM_LIT:1> : <EOL> url = text = url_text [ <NUM_LIT:0> ] <EOL> else : <EOL> url , text = url_text <EOL> return '<STR_LIT>' % ( url , text ) <EOL> self . memo_parser . register_command ( '<STR_LIT:url>' , url2html ) <EOL> if site . build_js_cache_on_startup is None : <EOL> site . build_js_cache_on_startup = not ( <EOL> settings . DEBUG or is_devserver ( ) ) <EOL> for a in actors . actors_list : <EOL> if a . get_welcome_messages is not None : <EOL> site . add_welcome_handler ( a . get_welcome_messages ) <EOL> pre_ui_build . send ( self ) <EOL> self . html_renderer = HtmlRenderer ( self ) <EOL> self . text_renderer = TextRenderer ( self ) <EOL> self . reserved_names = [ getattr ( constants , n ) <EOL> for n in constants . URL_PARAMS ] <EOL> names = set ( ) <EOL> for n in self . reserved_names : <EOL> if n in names : <EOL> raise Exception ( "<STR_LIT>" % n ) <EOL> names . add ( n ) <EOL> for p in site . installed_plugins : <EOL> p . on_ui_init ( self ) <EOL> ui = None <EOL> if self . site . default_ui is not None : <EOL> ui = self . site . plugins . resolve ( self . site . default_ui ) <EOL> if ui is None : <EOL> raise Exception ( <EOL> "<STR_LIT>" <EOL> % ( self . site . default_ui , list ( self . site . plugins . keys ( ) ) ) ) <EOL> ui . url_prefix = None <EOL> else : <EOL> for p in self . site . installed_plugins : <EOL> if p . ui_handle_attr_name is not None : <EOL> ui = p <EOL> break <EOL> if ui is not None : <EOL> self . default_renderer = ui . renderer <EOL> self . default_ui = ui <EOL> post_ui_build . send ( self ) <EOL> if self . default_ui is not None : <EOL> for res in actors . actors_list : <EOL> for ba in res . get_actions ( ) : <EOL> if ba . action . params_layout is not None : <EOL> ba . action . params_layout . get_layout_handle ( <EOL> self . default_ui ) <EOL> def kernel_startup ( kernel , self ) : <EOL> """<STR_LIT>""" <EOL> if len ( sys . argv ) == <NUM_LIT:0> : <EOL> process_name = '<STR_LIT>' <EOL> else : <EOL> process_name = '<STR_LIT:U+0020>' . join ( sys . argv ) <EOL> logger . info ( "<STR_LIT>" , <EOL> process_name , settings . SETTINGS_MODULE , os . getpid ( ) ) <EOL> def goodbye ( ) : <EOL> logger . info ( "<STR_LIT>" , process_name , os . getpid ( ) ) <EOL> atexit . register ( goodbye ) <EOL> models_list = get_models ( include_auto_created = True ) <EOL> self . setup_model_spec ( self , '<STR_LIT>' ) <EOL> self . setup_model_spec ( self , '<STR_LIT>' ) <EOL> for app_name_model , p in list ( self . override_modlib_models . items ( ) ) : <EOL> m = '<STR_LIT:.>' . join ( app_name_model . split ( '<STR_LIT:.>' ) [ - <NUM_LIT:2> : ] ) <EOL> resolve_model ( <EOL> m , <EOL> strict = "<STR_LIT>" % <EOL> p . __class__ . __module__ ) <EOL> for model in models_list : <EOL> if '<STR_LIT>' in model . __dict__ : <EOL> raise Exception ( "<STR_LIT>" , model ) <EOL> model . _lino_ddh = DisableDeleteHandler ( model ) <EOL> Model . django2lino ( model ) <EOL> if isinstance ( model . hidden_columns , basestring ) : <EOL> model . hidden_columns = frozenset ( <EOL> fields . fields_list ( model , model . hidden_columns ) ) <EOL> if isinstance ( model . active_fields , basestring ) : <EOL> model . active_fields = frozenset ( <EOL> fields . fields_list ( model , model . active_fields ) ) <EOL> if isinstance ( model . allow_cascaded_delete , basestring ) : <EOL> model . allow_cascaded_delete = frozenset ( <EOL> fields . fields_list ( model , model . allow_cascaded_delete ) ) <EOL> qsf = model . quick_search_fields <EOL> if qsf is None : <EOL> fields_list = [ ] <EOL> for field in model . _meta . fields : <EOL> if isinstance ( field , models . CharField ) : <EOL> fields_list . append ( field . name ) <EOL> model . quick_search_fields = frozenset ( fields_list ) <EOL> elif isinstance ( qsf , frozenset ) : <EOL> pass <EOL> elif isinstance ( qsf , basestring ) : <EOL> model . quick_search_fields = frozenset ( <EOL> fields . fields_list ( model , model . quick_search_fields ) ) <EOL> else : <EOL> raise ChangedAPI ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" . format ( <EOL> model , qsf ) ) <EOL> if model . _meta . abstract : <EOL> raise Exception ( "<STR_LIT>" ) <EOL> for f in model . _meta . virtual_fields : <EOL> if isinstance ( f , GenericForeignKey ) : <EOL> kernel . GFK_LIST . append ( f ) <EOL> if self . user_profiles_module : <EOL> from importlib import import_module <EOL> import_module ( self . user_profiles_module ) <EOL> self . setup_choicelists ( ) <EOL> self . setup_workflows ( ) <EOL> for model in models_list : <EOL> if model . _meta . auto_created : <EOL> continue <EOL> for f in model . _meta . get_fields ( ) : <EOL> m = f . model <EOL> if f . __class__ is models . CharField and f . null : <EOL> msg = "<STR_LIT>" % ( f . name , model ) <EOL> raise Exception ( msg ) <EOL> elif isinstance ( f , models . ForeignKey ) : <EOL> if isinstance ( f . rel . model , basestring ) : <EOL> raise Exception ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % <EOL> ( f . rel . model , f . name , model , models_list ) ) <EOL> set_default_verbose_name ( f ) <EOL> """<STR_LIT>""" <EOL> if not hasattr ( f . rel . model , '<STR_LIT>' ) : <EOL> raise Exception ( "<STR_LIT>" ) <EOL> f . rel . model . _lino_ddh . add_fk ( m or model , f ) <EOL> kernel . protect_foreignkeys ( models_list ) <EOL> for p in self . installed_plugins : <EOL> if isinstance ( p , Plugin ) : <EOL> p . before_analyze ( ) <EOL> pre_analyze . send ( self , models_list = models_list ) <EOL> self . setup_actions ( ) <EOL> for model in models_list : <EOL> """<STR_LIT>""" <EOL> model . on_analyze ( self ) <EOL> for k , v in class_dict_items ( model ) : <EOL> if isinstance ( v , fields . VirtualField ) : <EOL> v . attach_to_model ( model , k ) <EOL> actors . discover ( ) <EOL> logger . debug ( "<STR_LIT>" ) <EOL> for a in actors . actors_list : <EOL> a . class_init ( ) <EOL> dbtables . discover ( ) <EOL> actions . discover_choosers ( ) <EOL> for a in actors . actors_list : <EOL> a . on_analyze ( self ) <EOL> post_analyze . send ( self , models_list = models_list ) <EOL> if False : <EOL> logger . info ( "<STR_LIT>" , <EOL> '<STR_LIT:U+002CU+0020>' . join ( [ li . django_code for li in self . languages ] ) , <EOL> len ( self . modules ) , <EOL> len ( models_list ) , <EOL> len ( actors . actors_list ) ) <EOL> self . setup_layouts ( ) <EOL> self . on_each_app ( '<STR_LIT>' ) <EOL> for a in actors . actors_list : <EOL> a . after_site_setup ( self ) <EOL> self . resolve_virtual_fields ( ) <EOL> def protect_foreignkeys ( self , models_list ) : <EOL> """<STR_LIT>""" <EOL> from lino . mixins . polymorphic import Polymorphic <EOL> def must_protect ( m , fk , model ) : <EOL> if fk . name in m . allow_cascaded_delete : <EOL> return False <EOL> if m is model : <EOL> return True <EOL> if issubclass ( m , model ) : <EOL> if issubclass ( m , Polymorphic ) : <EOL> return False <EOL> return True <EOL> for model in models_list : <EOL> for m , fk in model . _lino_ddh . fklist : <EOL> assert fk . rel . model is model <EOL> if fk . rel . on_delete == models . CASCADE : <EOL> if must_protect ( m , fk , model ) : <EOL> msg = ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) . format ( fmn ( m ) , fk . name ) <EOL> logger . debug ( msg ) <EOL> fk . rel . on_delete = models . PROTECT <EOL> else : <EOL> if fk . name in m . allow_cascaded_delete : <EOL> msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) . format ( <EOL> fmn ( m ) , fk . name ) <EOL> raise Exception ( msg ) <EOL> if fk . rel . on_delete == models . SET_NULL : <EOL> if not fk . null : <EOL> msg = ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> msg = msg . format ( fmn ( m ) , fk . name , fk . rel . model ) <EOL> raise Exception ( msg ) <EOL> else : <EOL> msg = ( "<STR_LIT>" ) . format ( <EOL> fmn ( m ) , fk . name , fk . rel . on_delete ) <EOL> logger . debug ( msg ) <EOL> def get_generic_related ( self , obj ) : <EOL> """<STR_LIT>""" <EOL> if len ( self . GFK_LIST ) == <NUM_LIT:0> : <EOL> return <EOL> from django . contrib . contenttypes . models import ContentType <EOL> if not isinstance ( obj . _meta . pk , GFK_TARGETS ) : <EOL> return <EOL> obj_ct = ContentType . objects . get_for_model ( obj . __class__ ) <EOL> for gfk in self . GFK_LIST : <EOL> fk_field = gfk . model . _meta . get_field ( gfk . fk_field ) <EOL> kw = dict ( ) <EOL> kw [ gfk . fk_field ] = obj . pk <EOL> kw [ gfk . ct_field ] = obj_ct <EOL> ct = ContentType . objects . get_for_model ( gfk . model ) <EOL> yield gfk , fk_field , ct . get_all_objects_for_this_type ( ** kw ) <EOL> def get_broken_generic_related ( self , model ) : <EOL> """<STR_LIT>""" <EOL> gfks = [ f for f in self . GFK_LIST if f . model is model ] <EOL> if len ( gfks ) : <EOL> for gfk in gfks : <EOL> fk_field = gfk . model . _meta . get_field ( gfk . fk_field ) <EOL> kw = { gfk . ct_field + '<STR_LIT>' : False } <EOL> qs = model . objects . filter ( ** kw ) <EOL> for obj in qs : <EOL> fk = getattr ( obj , gfk . fk_field ) <EOL> ct = getattr ( obj , gfk . ct_field ) <EOL> pointed_model = ct . model_class ( ) <EOL> try : <EOL> pointed_model . objects . get ( pk = fk ) <EOL> except pointed_model . DoesNotExist : <EOL> msg = "<STR_LIT>" <EOL> obj . _message = msg . format ( <EOL> gfk . fk_field , fk , fmn ( pointed_model ) ) <EOL> if gfk . name in model . allow_cascaded_delete : <EOL> obj . _todo = '<STR_LIT>' <EOL> elif fk_field . null : <EOL> obj . _todo = '<STR_LIT>' <EOL> else : <EOL> obj . _todo = '<STR_LIT>' <EOL> yield obj <EOL> def abandon_response ( self ) : <EOL> return self . success ( _ ( "<STR_LIT>" ) ) <EOL> def field2elem ( self , lui , field , ** kw ) : <EOL> pass <EOL> def run_callback ( self , request , thread_id , button_id ) : <EOL> """<STR_LIT>""" <EOL> thread_id = int ( thread_id ) <EOL> cb = self . pending_threads . pop ( thread_id , None ) <EOL> if cb is None : <EOL> ar = ActorRequest ( request , renderer = self . default_renderer ) <EOL> logger . debug ( "<STR_LIT>" % ( <EOL> thread_id , list ( self . pending_threads . keys ( ) ) ) ) <EOL> ar . error ( "<STR_LIT>" % thread_id ) <EOL> return self . render_action_response ( ar ) <EOL> ar = cb . ar . actor . request_from ( cb . ar ) <EOL> for k in CLONEABLE_ATTRS : <EOL> setattr ( ar , k , getattr ( cb . ar , k ) ) <EOL> for c in cb . choices : <EOL> if c . name == button_id : <EOL> a = ar . bound_action . action <EOL> if self . site . log_each_action_request and not a . readonly : <EOL> logger . info ( "<STR_LIT>" . format ( <EOL> thread_id , cb . message , c . name ) ) <EOL> try : <EOL> c . func ( ar ) <EOL> except Warning as e : <EOL> ar . error ( e , alert = True ) <EOL> return self . render_action_response ( ar ) <EOL> ar . error ( "<STR_LIT>" % ( button_id , thread_id ) ) <EOL> return self . render_action_response ( ar ) <EOL> def add_callback ( self , ar , * msgs ) : <EOL> """<STR_LIT>""" <EOL> if len ( msgs ) > <NUM_LIT:1> : <EOL> msg = '<STR_LIT:\n>' . join ( [ force_text ( s ) for s in msgs ] ) <EOL> else : <EOL> msg = msgs [ <NUM_LIT:0> ] <EOL> return Callback ( ar , msg ) <EOL> def set_callback ( self , ar , cb ) : <EOL> """<STR_LIT:U+0020>""" <EOL> h = hash ( cb ) <EOL> self . pending_threads [ h ] = cb <EOL> buttons = dict ( ) <EOL> for c in cb . choices : <EOL> buttons [ c . name ] = c . label <EOL> ar . success ( <EOL> cb . message , xcallback = dict ( <EOL> id = h , <EOL> title = cb . title , <EOL> buttons = buttons ) ) <EOL> def run_action ( self , ar ) : <EOL> """<STR_LIT>""" <EOL> a = ar . bound_action . action <EOL> if self . site . log_each_action_request and not a . readonly : <EOL> flds = [ ] <EOL> A = flds . append <EOL> a = ar . bound_action . action <EOL> A ( ar . get_user ( ) . username ) <EOL> A ( ar . bound_action . full_name ( ) ) <EOL> A ( obj2str ( ar . master_instance ) ) <EOL> A ( obj2str ( ar . selected_rows ) ) <EOL> logger . info ( "<STR_LIT>" . format ( '<STR_LIT:U+0020>' . join ( flds ) ) ) <EOL> try : <EOL> a . run_from_ui ( ar ) <EOL> if a . parameters and not a . no_params_window : <EOL> ar . set_response ( close_window = True ) <EOL> except exceptions . ValidationError as e : <EOL> ar . error ( ar . ah . actor . error2str ( e ) , alert = True ) <EOL> except Warning as e : <EOL> ar . error ( e , alert = True ) <EOL> return self . render_action_response ( ar ) <EOL> def setup_handle ( self , h , ar ) : <EOL> """<STR_LIT>""" <EOL> if h . actor . is_abstract ( ) : <EOL> return <EOL> if isinstance ( h , tables . TableHandle ) : <EOL> he = set ( h . actor . hidden_columns | h . actor . hidden_elements ) <EOL> ll = layouts . ColumnsLayout ( <EOL> h . actor . get_column_names ( ar ) , <EOL> h . actor , hidden_elements = he ) <EOL> h . list_layout = ll . get_layout_handle ( self . default_ui ) <EOL> else : <EOL> h . list_layout = None <EOL> if h . actor . params_layout : <EOL> h . params_layout_handle = h . actor . make_params_layout_handle ( self ) <EOL> h . store = Store ( h ) <EOL> def render_action_response ( self , ar ) : <EOL> """<STR_LIT>""" <EOL> return views . json_response ( ar . response , ar . content_type ) <EOL> def row_action_button ( self , * args , ** kw ) : <EOL> """<STR_LIT>""" <EOL> return self . default_renderer . row_action_button ( * args , ** kw ) <EOL> _must_build = False <EOL> def must_build_site_cache ( self ) : <EOL> self . _must_build = True <EOL> def make_cache_file ( self , fn , write , force = False ) : <EOL> """<STR_LIT>""" <EOL> fn = join ( settings . MEDIA_ROOT , fn ) <EOL> if not force and not self . _must_build and exists ( fn ) : <EOL> mtime = os . stat ( fn ) . st_mtime <EOL> if mtime > self . code_mtime : <EOL> logger . debug ( "<STR_LIT>" , fn , time . ctime ( mtime ) ) <EOL> return <NUM_LIT:0> <EOL> logger . info ( "<STR_LIT>" , fn ) <EOL> self . site . makedirs_if_missing ( dirname ( fn ) ) <EOL> f = codecs . open ( fn , '<STR_LIT:w>' , encoding = '<STR_LIT:utf-8>' ) <EOL> try : <EOL> write ( f ) <EOL> f . close ( ) <EOL> return <NUM_LIT:1> <EOL> except Exception : <EOL> f . close ( ) <EOL> if not self . site . keep_erroneous_cache_files : <EOL> os . remove ( fn ) <EOL> raise </s>
|
<s> """<STR_LIT>""" <EOL> from __future__ import unicode_literals <EOL> from builtins import object <EOL> import datetime <EOL> import logging <EOL> logger = logging . getLogger ( __name__ ) <EOL> from django . db import models <EOL> from django . conf import settings <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from django . utils . translation import pgettext_lazy as pgettext <EOL> from django . core . exceptions import ValidationError <EOL> from lino . api import dd <EOL> from lino . core . model import Model <EOL> from lino . core . choicelists import Choice <EOL> from lino . utils . format_date import fdl <EOL> from lino . utils . ranges import isrange <EOL> from lino . utils . format_date import fds <EOL> from lino . core . utils import ParameterPanel <EOL> def rangefmt ( r ) : <EOL> return fds ( r [ <NUM_LIT:0> ] ) + '<STR_LIT>' + fds ( r [ <NUM_LIT:1> ] ) <EOL> class ObservedEvent ( Choice ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , value , ** kwargs ) : <EOL> super ( ObservedEvent , self ) . __init__ ( value , name = value , ** kwargs ) <EOL> def add_filter ( self , qs , pv ) : <EOL> return qs <EOL> class DatePeriod ( Model ) : <EOL> """<STR_LIT>""" <EOL> class Meta ( object ) : <EOL> abstract = True <EOL> empty_period_text = "<STR_LIT>" <EOL> start_date = models . DateField ( _ ( "<STR_LIT>" ) , blank = True , null = True ) <EOL> end_date = models . DateField ( _ ( "<STR_LIT>" ) , blank = True , null = True ) <EOL> def full_clean ( self , * args , ** kw ) : <EOL> if not isrange ( self . start_date , self . end_date ) : <EOL> raise ValidationError ( _ ( "<STR_LIT>" ) ) <EOL> super ( DatePeriod , self ) . full_clean ( * args , ** kw ) <EOL> def get_period ( self ) : <EOL> return ( self . start_date , self . end_date ) <EOL> def is_past ( self ) : <EOL> return ( self . end_date and self . end_date <= dd . today ( ) ) <EOL> def is_future ( self ) : <EOL> return ( self . start_date and self . start_date > settings . SITE . today ( ) ) <EOL> def get_period_text ( self ) : <EOL> if self . start_date and self . end_date : <EOL> if self . start_date == self . end_date : <EOL> s = fdl ( self . start_date ) <EOL> return pgettext ( "<STR_LIT:date>" , "<STR_LIT>" ) % s <EOL> else : <EOL> kw = dict ( ) <EOL> kw . update ( a = fdl ( self . start_date ) ) <EOL> kw . update ( b = fdl ( self . end_date ) ) <EOL> return pgettext ( "<STR_LIT>" , "<STR_LIT>" ) % kw <EOL> elif self . start_date : <EOL> s = fdl ( self . start_date ) <EOL> if self . is_future ( ) : <EOL> return pgettext ( "<STR_LIT>" , "<STR_LIT>" ) % s <EOL> else : <EOL> return pgettext ( "<STR_LIT>" , "<STR_LIT>" ) % s <EOL> elif self . end_date : <EOL> s = fdl ( self . end_date ) <EOL> return pgettext ( "<STR_LIT>" , "<STR_LIT>" ) % s <EOL> return self . empty_period_text <EOL> get_default_start_date = None <EOL> get_default_end_date = None <EOL> @ classmethod <EOL> def get_parameter_fields ( cls , ** fields ) : <EOL> fields . update ( <EOL> start_date = models . DateField ( <EOL> _ ( "<STR_LIT>" ) , blank = True , null = True , <EOL> default = cls . get_default_start_date , <EOL> help_text = _ ( "<STR_LIT>" ) ) ) <EOL> fields . update ( <EOL> end_date = models . DateField ( <EOL> _ ( "<STR_LIT>" ) , <EOL> blank = True , null = True , <EOL> default = cls . get_default_end_date , <EOL> help_text = _ ( "<STR_LIT>" ) ) ) <EOL> return super ( DatePeriod , cls ) . get_parameter_fields ( ** fields ) <EOL> class ObservedPeriod ( ParameterPanel ) : <EOL> """<STR_LIT>""" <EOL> get_default_start_date = None <EOL> get_default_end_date = None <EOL> def __init__ ( self , <EOL> verbose_name_start = _ ( "<STR_LIT>" ) , <EOL> verbose_name_end = _ ( "<STR_LIT>" ) , ** kw ) : <EOL> kw . update ( <EOL> start_date = models . DateField ( <EOL> verbose_name_start , blank = True , null = True , <EOL> default = self . get_default_start_date , <EOL> help_text = _ ( "<STR_LIT>" ) ) , <EOL> end_date = models . DateField ( <EOL> verbose_name_end , <EOL> blank = True , null = True , <EOL> default = self . get_default_end_date , <EOL> help_text = _ ( "<STR_LIT>" ) ) , <EOL> ) <EOL> super ( ObservedPeriod , self ) . __init__ ( ** kw ) <EOL> class Yearly ( ObservedPeriod ) : <EOL> """<STR_LIT>""" <EOL> def get_default_start_date ( self ) : <EOL> D = datetime . date <EOL> return D ( D . today ( ) . year , <NUM_LIT:1> , <NUM_LIT:1> ) <EOL> def get_default_end_date ( self ) : <EOL> D = datetime . date <EOL> return D ( D . today ( ) . year , <NUM_LIT:12> , <NUM_LIT> ) <EOL> class Today ( ParameterPanel ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , verbose_name = _ ( "<STR_LIT>" ) , ** kw ) : <EOL> kw . update ( <EOL> today = models . DateField ( <EOL> verbose_name , blank = True , null = True , <EOL> default = settings . SITE . today , <EOL> help_text = _ ( "<STR_LIT>" ) ) , <EOL> ) <EOL> super ( Today , self ) . __init__ ( ** kw ) </s>
|
<s> """<STR_LIT>""" <EOL> from lino . api import ad , _ <EOL> class Plugin ( ad . Plugin ) : <EOL> "<STR_LIT>" <EOL> verbose_name = _ ( "<STR_LIT>" ) <EOL> needs_plugins = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> hide_region = False <EOL> """<STR_LIT>""" <EOL> region_label = _ ( '<STR_LIT>' ) <EOL> """<STR_LIT>""" <EOL> def before_analyze ( self ) : <EOL> super ( Plugin , self ) . before_analyze ( ) <EOL> contacts = self . site . modules . contacts <EOL> if self . hide_region : <EOL> for m in ( contacts . Person , contacts . Company ) : <EOL> m . hide_elements ( '<STR_LIT>' ) <EOL> if False : <EOL> from lino . api import dd <EOL> for m in ( contacts . Person , contacts . Company ) : <EOL> m . define_action ( merge_row = dd . MergeAction ( m ) ) <EOL> def setup_main_menu ( self , site , profile , m ) : <EOL> m = m . add_menu ( self . app_label , self . verbose_name ) <EOL> for a in ( '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' ) : <EOL> m . add_action ( a ) <EOL> def setup_config_menu ( self , site , profile , m ) : <EOL> m = m . add_menu ( self . app_label , self . verbose_name ) <EOL> m . add_action ( '<STR_LIT>' ) <EOL> m . add_action ( '<STR_LIT>' ) <EOL> def setup_explorer_menu ( self , site , profile , m ) : <EOL> m = m . add_menu ( self . app_label , self . verbose_name ) <EOL> m . add_action ( '<STR_LIT>' ) </s>
|
<s> """<STR_LIT>""" </s>
|
<s> """<STR_LIT>""" <EOL> from builtins import str <EOL> from builtins import object <EOL> import logging <EOL> logger = logging . getLogger ( __name__ ) <EOL> from django . conf import settings <EOL> from django . contrib . contenttypes import models as contenttypes <EOL> from django . contrib . contenttypes . models import ContentType <EOL> from django . utils . encoding import force_text <EOL> from django . db import models <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from lino . api import dd , rt <EOL> from lino . utils . instantiator import Instantiator <EOL> class FieldSeparators ( dd . ChoiceList ) : <EOL> pass <EOL> class Filter ( dd . Model ) : <EOL> name = models . CharField ( _ ( "<STR_LIT:Name>" ) , max_length = <NUM_LIT:200> ) <EOL> content_type = dd . ForeignKey ( contenttypes . ContentType , <EOL> verbose_name = _ ( "<STR_LIT>" ) ) <EOL> field_sep = models . CharField ( _ ( "<STR_LIT>" ) , max_length = <NUM_LIT:10> ) <EOL> help_text = dd . RichTextField ( _ ( "<STR_LIT>" ) , <EOL> blank = True , null = True , format = '<STR_LIT>' ) <EOL> class Filters ( dd . Table ) : <EOL> model = Filter <EOL> column_names = "<STR_LIT>" <EOL> detail_layout = """<STR_LIT>""" <EOL> class Item ( mixins . Sequenced ) : <EOL> class Meta ( object ) : <EOL> verbose_name = _ ( "<STR_LIT>" ) <EOL> verbose_name_plural = _ ( "<STR_LIT>" ) <EOL> filter = dd . ForeignKey ( Filter ) <EOL> field = models . CharField ( _ ( "<STR_LIT>" ) , max_length = <NUM_LIT:200> ) <EOL> column = models . IntegerField ( _ ( "<STR_LIT>" ) ) <EOL> help_text = dd . RichTextField ( _ ( "<STR_LIT>" ) , <EOL> blank = True , null = True , format = '<STR_LIT>' ) <EOL> @ dd . chooser ( simple_values = True ) <EOL> def field_choices ( cls , filter ) : <EOL> l = [ ] <EOL> if filter is not None : <EOL> model = filter . content_type . model_class ( ) <EOL> meta = model . _meta <EOL> for f in meta . fields : <EOL> if not getattr ( f , '<STR_LIT>' , False ) : <EOL> l . append ( f . name ) <EOL> l . sort ( ) <EOL> return l <EOL> class Items ( dd . Table ) : <EOL> model = Item <EOL> column_names = "<STR_LIT>" <EOL> class ItemsByFilter ( Items ) : <EOL> master_key = '<STR_LIT>' <EOL> column_names = "<STR_LIT>" <EOL> class Import ( dd . VirtualTable ) : <EOL> column_names = '<STR_LIT>' <EOL> parameters = dict ( <EOL> filter = dd . ForeignKey ( Filter ) , <EOL> data = dd . RichTextField ( _ ( "<STR_LIT>" ) , <EOL> blank = True , null = True , <EOL> format = '<STR_LIT>' ) ) <EOL> @ classmethod <EOL> def get_data_rows ( self , ar ) : <EOL> flt = ar . param_values . filter <EOL> build = Instantiator ( flt . content_type . model_class ( ) ) . build <EOL> for ln in ar . param_values . data . splitlines ( ) : <EOL> ln = ln . strip ( ) <EOL> if ln : <EOL> kw = dict ( ) <EOL> cells = flt . field_sep . split ( ln ) <EOL> for item in flt . item_set . all ( ) : <EOL> if item . column : <EOL> kw [ item . field ] = cells [ item . column - <NUM_LIT:1> ] <EOL> yield build ( ** kw ) <EOL> @ dd . displayfield ( _ ( "<STR_LIT>" ) ) <EOL> def description ( cls , obj , ar ) : <EOL> kw = dict ( ) <EOL> flt = ar . param_values . filter <EOL> for item in flt . item_set . all ( ) : <EOL> kw [ item . field ] = getattr ( obj , item . field ) <EOL> return str ( kw ) <EOL> @ dd . displayfield ( _ ( "<STR_LIT>" ) ) <EOL> def obj2unicode ( cls , obj , ar ) : <EOL> return dd . obj2unicode ( obj ) </s>
|
<s> """<STR_LIT>""" <EOL> from builtins import str <EOL> from builtins import object <EOL> from django . db import models <EOL> from django . conf import settings <EOL> from django . utils import timezone <EOL> from lino . api import dd , rt , _ <EOL> from lino . core . roles import SiteStaff <EOL> from lino . core . gfks import gfk2lookup <EOL> from lino . core . requests import BaseRequest <EOL> from lino . mixins import Created <EOL> from lino . modlib . gfks . mixins import Controllable <EOL> from lino . modlib . users . mixins import UserAuthored , My <EOL> from lino . utils . xmlgen . html import E <EOL> from lino . utils import join_elems <EOL> @ dd . python_2_unicode_compatible <EOL> class Notification ( UserAuthored , Controllable , Created ) : <EOL> """<STR_LIT>""" <EOL> class Meta ( object ) : <EOL> app_label = '<STR_LIT>' <EOL> verbose_name = _ ( "<STR_LIT>" ) <EOL> verbose_name_plural = _ ( "<STR_LIT>" ) <EOL> seen = models . DateTimeField ( _ ( "<STR_LIT>" ) , null = True , editable = False ) <EOL> message = models . TextField ( _ ( "<STR_LIT>" ) , editable = False ) <EOL> def __str__ ( self ) : <EOL> return _ ( "<STR_LIT>" ) . format ( self . owner ) <EOL> @ classmethod <EOL> def notify ( cls , ar , owner , user , message ) : <EOL> """<STR_LIT>""" <EOL> fltkw = gfk2lookup ( cls . owner , owner ) <EOL> qs = cls . objects . filter ( <EOL> user = user , seen__isnull = True , ** fltkw ) <EOL> if not qs . exists ( ) : <EOL> obj = cls ( user = user , owner = owner , message = message ) <EOL> obj . full_clean ( ) <EOL> obj . save ( ) <EOL> obj . send_email ( ar ) <EOL> @ dd . displayfield ( ) <EOL> def overview ( self , ar ) : <EOL> if ar is None : <EOL> return '<STR_LIT>' <EOL> return self . get_overview ( ar ) <EOL> def get_overview ( self , ar ) : <EOL> """<STR_LIT>""" <EOL> context = dict ( <EOL> obj = ar . obj2str ( self . owner ) , <EOL> user = ar . obj2str ( self . user ) ) <EOL> return _ ( self . message ) . format ( ** context ) <EOL> @ dd . action ( ) <EOL> def send_email ( self , ar ) : <EOL> if not self . user . email : <EOL> dd . logger . info ( "<STR_LIT>" , self . user ) <EOL> return <EOL> sar = BaseRequest ( <EOL> user = self . user , renderer = settings . SITE . kernel . text_renderer ) <EOL> tpl = dd . plugins . notifier . email_subject_template <EOL> subject = tpl . format ( obj = self ) <EOL> subject = settings . EMAIL_SUBJECT_PREFIX + subject <EOL> template = rt . get_template ( '<STR_LIT>' ) <EOL> context = dict ( obj = self , E = E , rt = rt , ar = sar ) <EOL> body = template . render ( ** context ) <EOL> sender_email = ar . get_user ( ) . email or settings . SERVER_EMAIL <EOL> sender = "<STR_LIT>" . format ( ar . get_user ( ) , sender_email ) <EOL> rt . send_email ( <EOL> subject , sender , body , [ self . user . email ] ) <EOL> dd . update_field ( Notification , '<STR_LIT:user>' , verbose_name = _ ( "<STR_LIT>" ) ) <EOL> class Notifications ( dd . Table ) : <EOL> """<STR_LIT>""" <EOL> model = '<STR_LIT>' <EOL> column_names = "<STR_LIT>" <EOL> detail_layout = """<STR_LIT>""" <EOL> @ classmethod <EOL> def get_detail_title ( self , ar , obj ) : <EOL> if obj . seen is None and obj . user == ar . get_user ( ) : <EOL> obj . seen = timezone . now ( ) <EOL> obj . save ( ) <EOL> return super ( Notifications , self ) . get_detail_title ( ar , obj ) <EOL> class AllNotifications ( Notifications ) : <EOL> required_roles = dd . required ( SiteStaff ) <EOL> class MyNotifications ( My , Notifications ) : <EOL> required_roles = dd . required ( ) <EOL> def welcome_messages ( ar ) : <EOL> """<STR_LIT>""" <EOL> Notification = rt . modules . notifier . Notification <EOL> qs = Notification . objects . filter ( user = ar . get_user ( ) , seen__isnull = True ) <EOL> if qs . count ( ) > <NUM_LIT:0> : <EOL> chunks = [ <EOL> str ( _ ( "<STR_LIT>" ) ) % qs . count ( ) ] <EOL> chunks += join_elems ( [ <EOL> ar . obj2html ( obj , str ( obj . owner ) ) for obj in qs ] ) <EOL> yield E . span ( * chunks ) <EOL> dd . add_welcome_handler ( welcome_messages ) <EOL> if dd . is_installed ( '<STR_LIT>' ) : <EOL> from lino . modlib . changes . models import ChangesByMaster <EOL> class ChangesByNotification ( ChangesByMaster ) : <EOL> master = '<STR_LIT>' <EOL> @ classmethod <EOL> def get_request_queryset ( cls , ar ) : <EOL> mi = ar . master_instance <EOL> if mi is None : <EOL> return cls . model . objects . none ( ) <EOL> return cls . model . objects . filter ( <EOL> time__gte = mi . created , <EOL> ** gfk2lookup ( cls . model . master , mi . owner ) ) <EOL> else : <EOL> ChangesByNotification = None </s>
|
<s> """<STR_LIT>""" <EOL> from lino . api import ad <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> class Plugin ( ad . Plugin ) : <EOL> "<STR_LIT>" <EOL> verbose_name = _ ( "<STR_LIT>" ) </s>
|
<s> """<STR_LIT>""" <EOL> from lino import ad <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> class Plugin ( ad . Plugin ) : <EOL> "<STR_LIT>" <EOL> verbose_name = _ ( "<STR_LIT>" ) <EOL> needs_plugins = [ '<STR_LIT>' ] <EOL> def setup_config_menu ( self , site , profile , m ) : <EOL> system = m . add_menu ( self . app_label , self . verbose_name ) <EOL> system . add_instance_action ( site . site_config ) </s>
|
<s> from lino . projects . estref . settings import * <EOL> SITE = Site ( globals ( ) , title = Site . verbose_name + "<STR_LIT>" ) </s>
|
<s> """<STR_LIT>""" <EOL> from builtins import str <EOL> from builtins import object <EOL> import logging <EOL> logger = logging . getLogger ( __name__ ) <EOL> from lino . utils . instantiator import make_converter <EOL> from lino . core import constants <EOL> from lino . core . utils import getrqdata <EOL> class BaseChooser ( object ) : <EOL> pass <EOL> class FieldChooser ( BaseChooser ) : <EOL> def __init__ ( self , field ) : <EOL> self . field = field <EOL> class ChoicesChooser ( FieldChooser ) : <EOL> def __init__ ( self , field ) : <EOL> FieldChooser . __init__ ( self , field ) <EOL> self . simple_values = type ( field . choices [ <NUM_LIT:0> ] ) <EOL> class Chooser ( FieldChooser ) : <EOL> """<STR_LIT>""" <EOL> simple_values = False <EOL> instance_values = True <EOL> force_selection = True <EOL> choice_display_method = None <EOL> can_create_choice = False <EOL> def __init__ ( self , model , field , meth ) : <EOL> FieldChooser . __init__ ( self , field ) <EOL> self . model = model <EOL> self . meth = meth <EOL> from lino . core . gfks import is_foreignkey <EOL> if not is_foreignkey ( field ) : <EOL> self . simple_values = getattr ( meth , '<STR_LIT>' , False ) <EOL> self . instance_values = getattr ( meth , '<STR_LIT>' , False ) <EOL> self . force_selection = getattr ( <EOL> meth , '<STR_LIT>' , self . force_selection ) <EOL> self . context_params = meth . context_params <EOL> self . context_values = [ ] <EOL> self . context_fields = [ ] <EOL> for name in self . context_params : <EOL> f = self . get_data_elem ( name ) <EOL> if f is None : <EOL> raise Exception ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( <EOL> name , self . model , field . name ) ) <EOL> self . context_fields . append ( f ) <EOL> self . context_values . append ( name + "<STR_LIT>" ) <EOL> self . converters = [ ] <EOL> for f in self . context_fields : <EOL> cv = make_converter ( f ) <EOL> if cv is not None : <EOL> self . converters . append ( cv ) <EOL> if hasattr ( model , "<STR_LIT>" % field . name ) : <EOL> self . can_create_choice = True <EOL> m = getattr ( model , "<STR_LIT>" % field . name , None ) <EOL> if m is not None : <EOL> self . choice_display_method = m <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT>" % ( <EOL> self . model . __name__ , self . field . name , <EOL> self . context_params ) <EOL> def create_choice ( self , obj , text ) : <EOL> m = getattr ( obj , "<STR_LIT>" % self . field . name ) <EOL> return m ( text ) <EOL> def get_data_elem ( self , name ) : <EOL> """<STR_LIT>""" <EOL> de = self . model . get_data_elem ( name ) <EOL> if de is None : <EOL> return self . model . get_param_elem ( name ) <EOL> return de <EOL> def __call__ ( self , * args , ** kw ) : <EOL> for i , v in enumerate ( args ) : <EOL> kw [ self . context_fields [ i ] ] = v <EOL> return self . get_choices ( ** kw ) <EOL> def get_choices ( self , ** context ) : <EOL> """<STR_LIT>""" <EOL> args = [ ] <EOL> for varname in self . context_params : <EOL> args . append ( context . get ( varname , None ) ) <EOL> return self . meth ( * args ) <EOL> def get_request_choices ( self , request , tbl ) : <EOL> """<STR_LIT>""" <EOL> from django . contrib . contenttypes . models import ContentType <EOL> kw = { } <EOL> if tbl . master_field is not None : <EOL> rqdata = getrqdata ( request ) <EOL> if tbl . master is not None : <EOL> master = tbl . master <EOL> else : <EOL> mt = rqdata . get ( constants . URL_PARAM_MASTER_TYPE ) <EOL> try : <EOL> master = ContentType . objects . get ( pk = mt ) . model_class ( ) <EOL> except ContentType . DoesNotExist : <EOL> master = None <EOL> pk = rqdata . get ( constants . URL_PARAM_MASTER_PK , None ) <EOL> if pk and master : <EOL> try : <EOL> kw [ tbl . master_field . name ] = master . objects . get ( pk = pk ) <EOL> except ValueError : <EOL> raise Exception ( <EOL> "<STR_LIT>" , pk , master . __name__ ) <EOL> except master . DoesNotExist : <EOL> raise Exception ( "<STR_LIT>" % <EOL> ( master . __name__ , pk ) ) <EOL> for k , v in list ( request . GET . items ( ) ) : <EOL> kw [ str ( k ) ] = v <EOL> for cv in self . converters : <EOL> kw = cv . convert ( ** kw ) <EOL> if tbl . known_values : <EOL> kw . update ( tbl . known_values ) <EOL> if False : <EOL> if ar . create_kw : <EOL> kw . update ( ar . create_kw ) <EOL> if ar . known_values : <EOL> kw . update ( ar . known_values ) <EOL> if tbl . master_key : <EOL> kw [ tbl . master_key ] = ar . master_instance <EOL> return self . get_choices ( ** kw ) <EOL> def get_text_for_value ( self , value , obj ) : <EOL> m = getattr ( self . field , '<STR_LIT>' , None ) <EOL> if m is not None : <EOL> return m ( value ) <EOL> m = getattr ( obj , "<STR_LIT>" + self . field . name + "<STR_LIT>" ) <EOL> return m ( value ) <EOL> def uses_simple_values ( holder , fld ) : <EOL> "<STR_LIT>" <EOL> from lino . core . gfks import is_foreignkey <EOL> if is_foreignkey ( fld ) : <EOL> return False <EOL> if holder is not None : <EOL> ch = holder . get_chooser_for_field ( fld . name ) <EOL> if ch is not None : <EOL> return ch . simple_values <EOL> choices = list ( fld . choices ) <EOL> if len ( choices ) == <NUM_LIT:0> : <EOL> return True <EOL> if type ( choices [ <NUM_LIT:0> ] ) in ( list , tuple ) : <EOL> return False <EOL> return True <EOL> def _chooser ( make , ** options ) : <EOL> def chooser_decorator ( fn ) : <EOL> def wrapped ( * args ) : <EOL> return fn ( * args ) <EOL> wrapped . context_params = fn . __code__ . co_varnames [ <EOL> <NUM_LIT:1> : fn . __code__ . co_argcount ] <EOL> for k , v in list ( options . items ( ) ) : <EOL> setattr ( wrapped , k , v ) <EOL> return make ( wrapped ) <EOL> return chooser_decorator <EOL> def chooser ( ** options ) : <EOL> "<STR_LIT>" <EOL> return _chooser ( classmethod , ** options ) <EOL> def noop ( x ) : <EOL> return x <EOL> def action_chooser ( ** options ) : <EOL> return _chooser ( noop , ** options ) </s>
|
<s> """<STR_LIT>""" <EOL> from past . builtins import basestring <EOL> import os <EOL> import sys <EOL> import logging <EOL> from logging . handlers import WatchedFileHandler <EOL> def file_handler ( filename , rotate , ** kw ) : <EOL> kw . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> if sys . platform == '<STR_LIT:win32>' : <EOL> cl = logging . FileHandler <EOL> else : <EOL> cl = WatchedFileHandler <EOL> h = cl ( filename , ** kw ) <EOL> fmt = logging . Formatter ( <EOL> fmt = '<STR_LIT>' , <EOL> datefmt = '<STR_LIT>' <EOL> ) <EOL> h . setFormatter ( fmt ) <EOL> return h <EOL> def configure ( config ) : <EOL> """<STR_LIT>""" <EOL> if getattr ( logging , "<STR_LIT>" , False ) : <EOL> msg = "<STR_LIT>" <EOL> logging . info ( msg ) <EOL> return <EOL> logging . set_up_done = True <EOL> logger_names = config . get ( '<STR_LIT>' , None ) <EOL> if not logger_names : <EOL> return <EOL> djangoLogger = logging . getLogger ( '<STR_LIT>' ) <EOL> linoLogger = logging . getLogger ( '<STR_LIT>' ) <EOL> from django . utils . log import AdminEmailHandler <EOL> logfile = config . get ( '<STR_LIT:filename>' , None ) <EOL> rotate = config . get ( '<STR_LIT>' , True ) <EOL> tty = config . get ( '<STR_LIT>' , True ) <EOL> level = getattr ( logging , config . get ( '<STR_LIT>' , '<STR_LIT>' ) . upper ( ) ) <EOL> if isinstance ( logger_names , basestring ) : <EOL> logger_names = logger_names . split ( ) <EOL> loggers = [ logging . getLogger ( n ) for n in logger_names ] <EOL> for l in loggers : <EOL> l . setLevel ( level ) <EOL> aeh = AdminEmailHandler ( include_html = True ) <EOL> aeh . setLevel ( logging . ERROR ) <EOL> for l in loggers : <EOL> l . addHandler ( aeh ) <EOL> if '<STR_LIT>' not in logger_names : <EOL> djangoLogger . addHandler ( aeh ) <EOL> if tty : <EOL> try : <EOL> if sys . stdout . isatty ( ) : <EOL> h = logging . StreamHandler ( ) <EOL> if logfile is not None : <EOL> h . setLevel ( logging . INFO ) <EOL> fmt = logging . Formatter ( fmt = '<STR_LIT>' ) <EOL> h . setFormatter ( fmt ) <EOL> for l in loggers : <EOL> l . addHandler ( h ) <EOL> except IOError : <EOL> linoLogger . info ( "<STR_LIT>" ) <EOL> if logfile is not None : <EOL> try : <EOL> kw = { } <EOL> for k in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> if k in config : <EOL> kw [ k ] = config [ k ] <EOL> h = file_handler ( logfile , rotate , ** kw ) <EOL> for l in loggers : <EOL> l . addHandler ( h ) <EOL> except IOError as e : <EOL> raise Exception ( "<STR_LIT>" % ( logfile , e ) ) </s>
|
<s> """<STR_LIT>""" <EOL> import xml . etree . ElementTree as etree <EOL> if hasattr ( etree , '<STR_LIT>' ) : <EOL> def CDATA ( text = None ) : <EOL> element = etree . Element ( '<STR_LIT>' ) <EOL> element . text = text <EOL> return element <EOL> _original_serialize_xml = etree . _serialize_xml <EOL> def _serialize_xml ( write , elem , * args , ** kwargs ) : <EOL> if elem . tag == '<STR_LIT>' : <EOL> write ( "<STR_LIT>" % ( <EOL> elem . tag , elem . text ) ) <EOL> return <EOL> return _original_serialize_xml ( write , elem , * args , ** kwargs ) <EOL> etree . _serialize_xml = etree . _serialize [ '<STR_LIT>' ] = _serialize_xml <EOL> register_namespace = etree . register_namespace <EOL> else : <EOL> def register_namespace ( * args , ** kw ) : <EOL> pass <EOL> from xml . etree . ElementTree import * </s>
|
<s> from stdnet import odm <EOL> class Base ( odm . StdModel ) : <EOL> name = odm . SymbolField ( primary_key = True ) <EOL> ccy = odm . SymbolField ( ) <EOL> def __unicode__ ( self ) : <EOL> return self . name <EOL> class Meta : <EOL> abstract = True <EOL> class Instrument ( Base ) : <EOL> type = odm . SymbolField ( ) <EOL> description = odm . CharField ( ) </s>
|
<s> '''<STR_LIT>''' <EOL> import os <EOL> import io <EOL> import socket <EOL> from copy import copy <EOL> from . extensions import RedisExtensionsMixin , redis , BasePipeline <EOL> from . prefixed import PrefixedRedisMixin <EOL> class Redis ( RedisExtensionsMixin , redis . StrictRedis ) : <EOL> @ property <EOL> def encoding ( self ) : <EOL> return self . connection_pool . connection_kwargs . get ( '<STR_LIT>' , '<STR_LIT:utf-8>' ) <EOL> def address ( self ) : <EOL> kw = self . connection_pool . connection_kwargs <EOL> return ( kw [ '<STR_LIT:host>' ] , kw [ '<STR_LIT:port>' ] ) <EOL> def prefixed ( self , prefix ) : <EOL> '''<STR_LIT>''' <EOL> return PrefixedRedis ( self , prefix ) <EOL> def pipeline ( self , transaction = True , shard_hint = None ) : <EOL> return Pipeline ( <EOL> self , <EOL> transaction , <EOL> shard_hint ) <EOL> class PrefixedRedis ( PrefixedRedisMixin , Redis ) : <EOL> pass <EOL> class Pipeline ( BasePipeline , Redis ) : <EOL> def __init__ ( self , client , transaction , shard_hint ) : <EOL> self . client = client <EOL> self . response_callbacks = client . response_callbacks <EOL> self . transaction = transaction <EOL> self . shard_hint = shard_hint <EOL> self . watching = False <EOL> self . connection = None <EOL> self . reset ( ) <EOL> @ property <EOL> def connection_pool ( self ) : <EOL> return self . client . connection_pool <EOL> @ property <EOL> def is_pipeline ( self ) : <EOL> return True </s>
|
<s> import sys <EOL> from collections import * <EOL> if sys . version_info < ( <NUM_LIT:2> , <NUM_LIT:7> ) : <EOL> from . fallbacks . _collections import * </s>
|
<s> from stdnet import odm <EOL> from stdnet . apps . searchengine . models import WordItem <EOL> from stdnet . utils import test <EOL> from examples . models import SimpleModel <EOL> class TestCase ( test . TestWrite ) : <EOL> multipledb = '<STR_LIT>' <EOL> models = ( WordItem , SimpleModel ) <EOL> def testAutoIncrement ( self ) : <EOL> a = odm . autoincrement ( ) <EOL> self . assertEqual ( a . incrby , <NUM_LIT:1> ) <EOL> self . assertEqual ( a . desc , False ) <EOL> self . assertEqual ( str ( a ) , '<STR_LIT>' ) <EOL> a = odm . autoincrement ( <NUM_LIT:3> ) <EOL> self . assertEqual ( a . incrby , <NUM_LIT:3> ) <EOL> self . assertEqual ( a . desc , False ) <EOL> self . assertEqual ( str ( a ) , '<STR_LIT>' ) <EOL> b = - a <EOL> self . assertEqual ( str ( a ) , '<STR_LIT>' ) <EOL> self . assertEqual ( b . desc , True ) <EOL> self . assertEqual ( str ( b ) , '<STR_LIT>' ) <EOL> def testSimple ( self ) : <EOL> session = self . session ( ) <EOL> m = yield session . add ( SimpleModel ( code = '<STR_LIT>' ) ) <EOL> w = yield session . add ( WordItem ( word = '<STR_LIT>' , model_type = SimpleModel , <EOL> object_id = m . id ) ) <EOL> yield self . async . assertEqual ( session . query ( WordItem ) . count ( ) , <NUM_LIT:1> ) <EOL> w = yield session . add ( WordItem ( word = '<STR_LIT>' , model_type = SimpleModel , <EOL> object_id = m . id ) ) <EOL> yield self . async . assertEqual ( session . query ( WordItem ) . count ( ) , <NUM_LIT:1> ) <EOL> self . assertEqual ( w . get_state ( ) . score , <NUM_LIT:2> ) <EOL> w = yield session . add ( WordItem ( word = '<STR_LIT>' , model_type = SimpleModel , <EOL> object_id = m . id ) ) <EOL> yield self . async . assertEqual ( session . query ( WordItem ) . count ( ) , <NUM_LIT:1> ) <EOL> self . assertEqual ( w . get_state ( ) . score , <NUM_LIT:3> ) </s>
|
<s> from . import ranges <EOL> class TestWhere ( ranges . NumericTest ) : <EOL> multipledb = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> def testWhere ( self ) : <EOL> session = self . session ( ) <EOL> qs = session . query ( self . model ) . where ( '<STR_LIT>' ) <EOL> qs = yield qs . all ( ) <EOL> self . assertTrue ( qs ) <EOL> for m in qs : <EOL> self . assertTrue ( m . vega > m . delta ) <EOL> def testConcatenation ( self ) : <EOL> session = self . session ( ) <EOL> qs = session . query ( self . model ) <EOL> qs = qs . filter ( pv__gt = <NUM_LIT:0> ) . where ( '<STR_LIT>' ) <EOL> qs = yield qs . all ( ) <EOL> self . assertTrue ( qs ) <EOL> for m in qs : <EOL> self . assertTrue ( m . pv > <NUM_LIT:0> ) <EOL> self . assertTrue ( m . vega > m . delta ) <EOL> def testLoadOnly ( self ) : <EOL> '''<STR_LIT>''' <EOL> session = self . session ( ) <EOL> qs = session . query ( self . model ) . where ( '<STR_LIT>' , <EOL> load_only = ( '<STR_LIT>' , '<STR_LIT:foo>' , '<STR_LIT>' ) ) <EOL> qs = yield qs . all ( ) <EOL> self . assertTrue ( qs ) <EOL> for m in qs : <EOL> self . assertTrue ( m . vega > m . delta ) </s>
|
<s> def test_docs ( ) : <EOL> from doctest import testfile <EOL> import os <EOL> docdir = '<STR_LIT>' <EOL> total_failures = <NUM_LIT:0> <EOL> total_tests = <NUM_LIT:0> <EOL> for root , dirs , files in os . walk ( docdir ) : <EOL> for fn in files : <EOL> if fn . endswith ( '<STR_LIT>' ) : <EOL> docfile = os . path . join ( root , fn ) <EOL> fail , nt = testfile ( docfile ) <EOL> total_failures += fail <EOL> total_tests += nt <EOL> assert total_failures == <NUM_LIT:0> </s>
|
<s> import DeepFried2 as df <EOL> import numpy as np <EOL> class RMSECriterion ( df . Criterion ) : <EOL> def __init__ ( self , axis = '<STR_LIT:all>' , eps = <NUM_LIT> ) : <EOL> """<STR_LIT>""" <EOL> df . Criterion . __init__ ( self ) <EOL> self . axis = axis <EOL> self . eps = eps <EOL> def symb_forward ( self , symb_input , symb_target ) : <EOL> self . _assert_same_dim ( symb_input , symb_target ) <EOL> axis = self . axis <EOL> if self . axis == '<STR_LIT:all>' : <EOL> axis = np . arange ( <NUM_LIT:1> , symb_input . ndim ) <EOL> return df . T . sqrt ( self . eps + df . T . sum ( ( symb_input - symb_target ) ** <NUM_LIT:2> , axis = axis ) ) <EOL> class MSECriterion ( df . Criterion ) : <EOL> def symb_forward ( self , symb_input , symb_target ) : <EOL> self . _assert_same_dim ( symb_input , symb_target ) <EOL> return ( symb_input - symb_target ) ** <NUM_LIT:2> </s>
|
<s> import DeepFried2 as df <EOL> class Reshape ( df . Module ) : <EOL> def __init__ ( self , * new_shape ) : <EOL> df . Module . __init__ ( self ) <EOL> self . new_shape = new_shape <EOL> def symb_forward ( self , symb_input ) : <EOL> return symb_input . reshape ( self . new_shape ) </s>
|
<s> import sys as _sys <EOL> import os as _os <EOL> import email . utils as _eutils <EOL> try : <EOL> from urllib . request import urlopen as _urlopen <EOL> from urllib . error import URLError as _URLError <EOL> from socket import timeout as _timeout <EOL> except ImportError : <EOL> from urllib2 import urlopen as _urlopen <EOL> from urllib2 import URLError as _URLError <EOL> FileExistsError = OSError <EOL> FileNotFoundError = IOError <EOL> def _httpfilename ( response ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> return response . info ( ) . get_filename ( ) <EOL> except AttributeError : <EOL> import cgi <EOL> _ , params = cgi . parse_header ( response . headers . get ( '<STR_LIT>' , '<STR_LIT>' ) ) <EOL> return params . get ( '<STR_LIT:filename>' , None ) <EOL> def _getheader ( response , header , default = None ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> return response . getheader ( header , default ) <EOL> except AttributeError : <EOL> return response . info ( ) . getheader ( header , default ) <EOL> def download ( url , into = '<STR_LIT>' , saveas = None , desc = None , quiet = False ) : <EOL> """<STR_LIT>""" <EOL> into = _os . path . expanduser ( into ) <EOL> try : <EOL> _os . makedirs ( into ) <EOL> except FileExistsError : <EOL> pass <EOL> try : <EOL> response = _urlopen ( url , timeout = <NUM_LIT:5> ) <EOL> except ( _URLError , _timeout ) : <EOL> saveas = saveas or _os . path . basename ( url ) <EOL> target = _os . path . join ( into , saveas ) <EOL> if not _os . path . isfile ( target ) : <EOL> raise FileNotFoundError ( target ) <EOL> if not quiet : <EOL> print ( "<STR_LIT>" . format ( target ) ) <EOL> return target <EOL> saveas = saveas or _httpfilename ( response ) or _os . path . basename ( url ) <EOL> target = _os . path . join ( into , saveas ) <EOL> leng = int ( _getheader ( response , '<STR_LIT>' , <NUM_LIT:0> ) ) <EOL> if _os . path . isfile ( target ) : <EOL> try : <EOL> with open ( target + '<STR_LIT>' , '<STR_LIT:r>' ) as f : <EOL> etag = f . read ( ) <EOL> if _getheader ( response , '<STR_LIT>' ) == etag : <EOL> return target <EOL> except FileNotFoundError : <EOL> pass <EOL> if _os . path . getsize ( target ) == leng : <EOL> servertime = _eutils . parsedate_tz ( _getheader ( response , '<STR_LIT>' ) ) <EOL> if servertime is None : <EOL> return target <EOL> else : <EOL> if _os . path . getmtime ( target ) >= _eutils . mktime_tz ( servertime ) : <EOL> return target <EOL> if not quiet : <EOL> desc = desc or '<STR_LIT>' . format ( url , target ) <EOL> _sys . stdout . write ( '<STR_LIT>' . format ( desc , <NUM_LIT:0> , leng // <NUM_LIT> , <NUM_LIT:0> ) ) <EOL> _sys . stdout . flush ( ) <EOL> with open ( target , '<STR_LIT>' ) as f : <EOL> while f . tell ( ) < leng : <EOL> f . write ( response . read ( <NUM_LIT> * <NUM_LIT:8> ) ) <EOL> if not quiet : <EOL> _sys . stdout . write ( '<STR_LIT>' . format ( desc , f . tell ( ) // <NUM_LIT> , leng // <NUM_LIT> , float ( f . tell ( ) ) / leng ) ) <EOL> _sys . stdout . flush ( ) <EOL> if not quiet : <EOL> print ( "<STR_LIT>" ) <EOL> etag = _getheader ( response , '<STR_LIT>' ) <EOL> if etag is not None : <EOL> with open ( target + '<STR_LIT>' , '<STR_LIT>' ) as f : <EOL> f . write ( etag ) <EOL> return target </s>
|
<s> from django . core . handlers . base import BaseHandler <EOL> class DummyHandler ( BaseHandler ) : <EOL> """<STR_LIT>""" <EOL> def __call__ ( self , request ) : <EOL> self . load_middleware ( ) <EOL> response = self . get_response ( request ) <EOL> for middleware_method in self . _response_middleware : <EOL> response = middleware_method ( request , response ) <EOL> return response </s>
|
<s> from jinja2 import Environment , DictLoader <EOL> from clay . jinja_includewith import IncludeWith <EOL> env = Environment ( <EOL> loader = DictLoader ( { <EOL> '<STR_LIT:hello>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } ) , <EOL> extensions = [ '<STR_LIT>' , IncludeWith ] <EOL> ) <EOL> def test_set_context ( ) : <EOL> tmpl = env . from_string ( <EOL> '''<STR_LIT>''' <EOL> '''<STR_LIT>''' ) <EOL> expected = '''<STR_LIT>''' <EOL> result = tmpl . render ( ) <EOL> assert result == expected <EOL> def test_set_context_linebreak ( ) : <EOL> tmpl = env . from_string ( '''<STR_LIT>''' ) <EOL> expected = '''<STR_LIT>''' <EOL> result = tmpl . render ( ) <EOL> assert result == expected <EOL> def test_overwrite_context ( ) : <EOL> tmpl = env . from_string ( '''<STR_LIT>''' ) <EOL> expected = '''<STR_LIT>''' <EOL> result = tmpl . render ( what = '<STR_LIT>' ) <EOL> assert result == expected <EOL> def test_multiple_values ( ) : <EOL> tmpl = env . from_string ( '''<STR_LIT>''' ) <EOL> expected = '''<STR_LIT>''' <EOL> result = tmpl . render ( ) <EOL> assert result == expected <EOL> def test_careless_formatting ( ) : <EOL> tmpl = env . from_string ( '''<STR_LIT>''' ) <EOL> expected = '''<STR_LIT>''' <EOL> result = tmpl . render ( ) <EOL> assert result == expected <EOL> def test_text ( ) : <EOL> tmpl = env . from_string ( <EOL> '''<STR_LIT>''' <EOL> '''<STR_LIT>''' ) <EOL> expected = '''<STR_LIT>''' <EOL> result = tmpl . render ( ) <EOL> assert result == expected <EOL> def test_include_current_context ( ) : <EOL> tmpl = env . from_string ( '''<STR_LIT>''' ) <EOL> expected = '''<STR_LIT>''' <EOL> result = tmpl . render ( b = <NUM_LIT:2> ) <EOL> assert result == expected <EOL> def test_unobstrusiveness ( ) : <EOL> tmpl = env . from_string ( '''<STR_LIT>''' ) <EOL> r1 = tmpl . render ( what = '<STR_LIT>' ) <EOL> tmpl = env . from_string ( '''<STR_LIT>''' ) <EOL> r2 = tmpl . render ( what = '<STR_LIT>' ) <EOL> assert r1 == r2 == '<STR_LIT>' </s>
|
<s> """<STR_LIT>""" <EOL> from mailshake import SMTPMailer <EOL> from . common import * <EOL> DEBUG = False <EOL> RELOAD = False <EOL> SERVER_NAME = '<STR_LIT>' <EOL> DEFAULT_SUBDOMAIN = '<STR_LIT>' <EOL> SQLALCHEMY_URI = '<STR_LIT>' <EOL> PAGE_NOT_FOUND = '<STR_LIT>' <EOL> PAGE_ERROR = '<STR_LIT>' <EOL> PAGE_NOT_ALLOWED = '<STR_LIT>' <EOL> MAILER_CLASS = SMTPMailer <EOL> MAILER_SETTINGS = { <EOL> '<STR_LIT:host>' : '<STR_LIT:localhost>' , <EOL> '<STR_LIT:username>' : '<STR_LIT>' , <EOL> '<STR_LIT:password>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : True <EOL> } </s>
|
<s> from __future__ import absolute_import <EOL> import types <EOL> import flask <EOL> def _route_for_method ( self , rule , method , ** options ) : <EOL> def decorator ( f ) : <EOL> self . add_url_rule ( rule , None , f , methods = ( method , ) , ** options ) <EOL> return f <EOL> return decorator <EOL> def _get ( self , rule , ** options ) : <EOL> return _route_for_method ( self , rule , '<STR_LIT:GET>' , ** options ) <EOL> def _post ( self , rule , ** options ) : <EOL> return _route_for_method ( self , rule , '<STR_LIT:POST>' , ** options ) <EOL> def _put ( self , rule , ** options ) : <EOL> return _route_for_method ( self , rule , '<STR_LIT>' , ** options ) <EOL> def _delete ( self , rule , ** options ) : <EOL> return _route_for_method ( self , rule , '<STR_LIT>' , ** options ) <EOL> def add_restful_decorators ( app ) : <EOL> app = app <EOL> app . get = types . MethodType ( _get , app , flask . Flask ) <EOL> app . post = types . MethodType ( _post , app , flask . Flask ) <EOL> app . put = types . MethodType ( _put , app , flask . Flask ) <EOL> app . delete = types . MethodType ( _delete , app , flask . Flask ) </s>
|
<s> import timeit <EOL> normal_py_sec = timeit . timeit ( '<STR_LIT>' , <EOL> number = <NUM_LIT> ) <EOL> naive_np_sec = timeit . timeit ( '<STR_LIT>' , <EOL> setup = "<STR_LIT>" , <EOL> number = <NUM_LIT> ) <EOL> good_np_sec = timeit . timeit ( '<STR_LIT>' , <EOL> setup = "<STR_LIT>" , <EOL> number = <NUM_LIT> ) <EOL> print ( "<STR_LIT>" % normal_py_sec ) <EOL> print ( "<STR_LIT>" % naive_np_sec ) <EOL> print ( "<STR_LIT>" % good_np_sec ) </s>
|
<s> from __future__ import print_function <EOL> import logging <EOL> import gensim <EOL> import numpy as np <EOL> logging . basicConfig ( <EOL> format = '<STR_LIT>' , <EOL> level = logging . INFO ) <EOL> id2word = gensim . corpora . Dictionary . load_from_text ( <EOL> '<STR_LIT>' ) <EOL> mm = gensim . corpora . MmCorpus ( '<STR_LIT>' ) <EOL> model = gensim . models . hdpmodel . HdpModel ( <EOL> corpus = mm , <EOL> id2word = id2word , <EOL> chunksize = <NUM_LIT> ) <EOL> model . save ( '<STR_LIT>' ) <EOL> topics = np . zeros ( ( len ( mm ) , model . num_topics ) ) <EOL> for di , doc in enumerate ( mm ) : <EOL> doc_top = model [ doc ] <EOL> for ti , tv in doc_top : <EOL> topics [ di , ti ] += tv <EOL> np . save ( '<STR_LIT>' , topics ) </s>
|
<s> from collections import namedtuple <EOL> def apriori ( dataset , minsupport , maxsize ) : <EOL> '''<STR_LIT>''' <EOL> from collections import defaultdict <EOL> baskets = defaultdict ( list ) <EOL> pointers = defaultdict ( list ) <EOL> for i , ds in enumerate ( dataset ) : <EOL> for ell in ds : <EOL> pointers [ ell ] . append ( i ) <EOL> baskets [ frozenset ( [ ell ] ) ] . append ( i ) <EOL> new_pointers = dict ( ) <EOL> for k in pointers : <EOL> if len ( pointers [ k ] ) >= minsupport : <EOL> new_pointers [ k ] = frozenset ( pointers [ k ] ) <EOL> pointers = new_pointers <EOL> for k in baskets : <EOL> baskets [ k ] = frozenset ( baskets [ k ] ) <EOL> valid = set ( ) <EOL> for el , c in baskets . items ( ) : <EOL> if len ( c ) >= minsupport : <EOL> valid . update ( el ) <EOL> itemsets = [ frozenset ( [ v ] ) for v in valid ] <EOL> freqsets = [ ] <EOL> for i in range ( maxsize - <NUM_LIT:1> ) : <EOL> print ( "<STR_LIT>" . format ( <EOL> i , len ( itemsets ) ) ) <EOL> newsets = [ ] <EOL> for it in itemsets : <EOL> ccounts = baskets [ it ] <EOL> for v , pv in pointers . items ( ) : <EOL> if v not in it : <EOL> csup = ( ccounts & pv ) <EOL> if len ( csup ) >= minsupport : <EOL> new = frozenset ( it | frozenset ( [ v ] ) ) <EOL> if new not in baskets : <EOL> newsets . append ( new ) <EOL> baskets [ new ] = csup <EOL> freqsets . extend ( itemsets ) <EOL> itemsets = newsets <EOL> if not len ( itemsets ) : <EOL> break <EOL> support = { } <EOL> for k in baskets : <EOL> support [ k ] = float ( len ( baskets [ k ] ) ) <EOL> return freqsets , support <EOL> AssociationRule = namedtuple ( '<STR_LIT>' , [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> def association_rules ( dataset , freqsets , support , minlift ) : <EOL> '''<STR_LIT>''' <EOL> nr_transactions = float ( len ( dataset ) ) <EOL> freqsets = [ f for f in freqsets if len ( f ) > <NUM_LIT:1> ] <EOL> for fset in freqsets : <EOL> for f in fset : <EOL> consequent = frozenset ( [ f ] ) <EOL> antecendent = fset - consequent <EOL> py_x = support [ fset ] / support [ antecendent ] <EOL> base = support [ consequent ] / nr_transactions <EOL> lift = py_x / base <EOL> if lift > minlift : <EOL> yield AssociationRule ( antecendent , consequent , base , py_x , lift ) </s>
|
<s> from sklearn . feature_selection import RFE <EOL> from sklearn . linear_model import LogisticRegression <EOL> from sklearn . datasets import make_classification <EOL> X , y = make_classification ( <EOL> n_samples = <NUM_LIT:100> , n_features = <NUM_LIT:10> , n_informative = <NUM_LIT:3> , random_state = <NUM_LIT:0> ) <EOL> clf = LogisticRegression ( ) <EOL> clf . fit ( X , y ) <EOL> for i in range ( <NUM_LIT:1> , <NUM_LIT:11> ) : <EOL> selector = RFE ( clf , i ) <EOL> selector = selector . fit ( X , y ) <EOL> print ( "<STR_LIT>" % ( i , selector . support_ , selector . ranking_ ) ) </s>
|
<s> from __future__ import division <EOL> import numpy as np <EOL> import mahotas as mh <EOL> from . import convolve , gaussian_filter <EOL> _hsobel_filter = np . array ( [ <EOL> [ - <NUM_LIT:1> , <NUM_LIT:0> , <NUM_LIT:1> ] , <EOL> [ - <NUM_LIT:2> , <NUM_LIT:0> , <NUM_LIT:2> ] , <EOL> [ - <NUM_LIT:1> , <NUM_LIT:0> , <NUM_LIT:1> ] ] ) / <NUM_LIT> <EOL> _vsobel_filter = np . array ( [ <EOL> [ - <NUM_LIT:1> , - <NUM_LIT:2> , - <NUM_LIT:1> ] , <EOL> [ <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ] , <EOL> [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:1> ] ] ) / <NUM_LIT> <EOL> __all__ = [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] <EOL> def sobel ( img , just_filter = False ) : <EOL> '''<STR_LIT>''' <EOL> img = np . array ( img , dtype = np . float ) <EOL> if img . ndim != <NUM_LIT:2> : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> img -= img . min ( ) <EOL> ptp = img . ptp ( ) <EOL> if ptp == <NUM_LIT:0> : <EOL> return img <EOL> img /= ptp <EOL> vfiltered = convolve ( img , _vsobel_filter , mode = '<STR_LIT>' ) <EOL> hfiltered = convolve ( img , _hsobel_filter , mode = '<STR_LIT>' ) <EOL> vfiltered **= <NUM_LIT:2> <EOL> hfiltered **= <NUM_LIT:2> <EOL> filtered = vfiltered <EOL> filtered += hfiltered <EOL> if just_filter : <EOL> return filtered <EOL> thresh = <NUM_LIT:2> * np . sqrt ( filtered . mean ( ) ) <EOL> return mh . regmax ( filtered ) * ( np . sqrt ( filtered ) > thresh ) <EOL> def dog ( img , sigma1 = <NUM_LIT:2> , multiplier = <NUM_LIT> , just_filter = False ) : <EOL> '''<STR_LIT>''' <EOL> img = np . array ( img , dtype = np . float ) <EOL> if img . ndim != <NUM_LIT:2> : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> sigma2 = sigma1 * multiplier <EOL> G1 = gaussian_filter ( img , sigma1 , mode = '<STR_LIT>' ) <EOL> G2 = gaussian_filter ( img , sigma2 , mode = '<STR_LIT>' ) <EOL> DoG = G2 - G1 <EOL> ( m , n ) = img . shape <EOL> if not just_filter : <EOL> e = np . zeros ( ( m , n ) , dtype = bool ) <EOL> else : <EOL> return DoG <EOL> thresh = <NUM_LIT> * np . mean ( abs ( DoG ) ) <EOL> rr = np . arange ( <NUM_LIT:1> , m - <NUM_LIT:2> ) <EOL> cc = np . arange ( <NUM_LIT:1> , n - <NUM_LIT:2> ) <EOL> ( rx , cx ) = np . nonzero ( <EOL> np . logical_and ( np . logical_and ( DoG [ np . ix_ ( rr , cc ) ] < <NUM_LIT:0> , DoG [ np . ix_ ( rr , cc + <NUM_LIT:1> ) ] > <NUM_LIT:0> ) , <EOL> abs ( DoG [ np . ix_ ( rr , cc ) ] - DoG [ np . ix_ ( rr , cc + <NUM_LIT:1> ) ] ) > thresh ) ) <EOL> e [ ( rx , cx ) ] = <NUM_LIT:1> <EOL> ( rx , cx ) = np . nonzero ( <EOL> np . logical_and ( np . logical_and ( DoG [ np . ix_ ( rr , cc - <NUM_LIT:1> ) ] > <NUM_LIT:0> , DoG [ np . ix_ ( rr , cc + <NUM_LIT:1> ) ] < <NUM_LIT:0> ) , <EOL> abs ( DoG [ np . ix_ ( rr , cc - <NUM_LIT:1> ) ] - DoG [ np . ix_ ( rr , cc ) ] ) > thresh ) ) <EOL> e [ ( rx , cx ) ] = <NUM_LIT:1> <EOL> ( rx , cx ) = np . nonzero ( <EOL> np . logical_and ( np . logical_and ( DoG [ np . ix_ ( rr , cc ) ] < <NUM_LIT:0> , DoG [ np . ix_ ( rr + <NUM_LIT:1> , cc ) ] > <NUM_LIT:0> ) , <EOL> abs ( DoG [ np . ix_ ( rr , cc ) ] - DoG [ np . ix_ ( rr + <NUM_LIT:1> , cc ) ] ) > thresh ) ) <EOL> e [ ( rx , cx ) ] = <NUM_LIT:1> <EOL> ( rx , cx ) = np . nonzero ( <EOL> np . logical_and ( np . logical_and ( DoG [ np . ix_ ( rr - <NUM_LIT:1> , cc ) ] > <NUM_LIT:0> , DoG [ np . ix_ ( rr , cc ) ] < <NUM_LIT:0> ) , <EOL> abs ( DoG [ np . ix_ ( rr - <NUM_LIT:1> , cc ) ] - DoG [ np . ix_ ( rr , cc ) ] ) > thresh ) ) <EOL> e [ ( rx , cx ) ] = <NUM_LIT:1> <EOL> ( rz , cz ) = np . nonzero ( DoG [ np . ix_ ( rr , cc ) ] == <NUM_LIT:0> ) <EOL> if rz . size != <NUM_LIT:0> : <EOL> ( rx , cx ) = np . nonzero ( <EOL> np . logical_and ( np . logical_and ( DoG [ np . ix_ ( rz , cz - <NUM_LIT:1> ) ] < <NUM_LIT:0> , DoG [ np . ix_ ( rz , cz + <NUM_LIT:1> ) ] > <NUM_LIT:0> ) , <EOL> abs ( DoG [ np . ix_ ( rz , cz + <NUM_LIT:1> ) ] - DoG [ np . ix_ ( rz , cz - <NUM_LIT:1> ) ] ) > thresh ) ) <EOL> e [ ( rx , cx ) ] = <NUM_LIT:1> <EOL> ( rx , cx ) = np . nonzero ( <EOL> np . logical_and ( np . logical_and ( DoG [ np . ix_ ( rz , cz - <NUM_LIT:1> ) ] > <NUM_LIT:0> , DoG [ np . ix_ ( rz , cz + <NUM_LIT:1> ) ] < <NUM_LIT:0> ) , <EOL> abs ( DoG [ np . ix_ ( rz , cz - <NUM_LIT:1> ) ] - DoG [ np . ix_ ( rz , cz + <NUM_LIT:1> ) ] ) > thresh ) ) <EOL> e [ ( rx , cx ) ] = <NUM_LIT:1> <EOL> ( rx , cx ) = np . nonzero ( <EOL> np . logical_and ( np . logical_and ( DoG [ np . ix_ ( rz - <NUM_LIT:1> , cz ) ] < <NUM_LIT:0> , DoG [ np . ix_ ( rz + <NUM_LIT:1> , cz ) ] > <NUM_LIT:0> ) , <EOL> abs ( DoG [ np . ix_ ( rz + <NUM_LIT:1> , cz ) ] - DoG [ np . ix_ ( rz - <NUM_LIT:1> , cz ) ] ) > thresh ) ) <EOL> e [ ( rx , cx ) ] = <NUM_LIT:1> <EOL> ( rx , cx ) = np . nonzero ( <EOL> np . logical_and ( np . logical_and ( DoG [ np . ix_ ( rz - <NUM_LIT:1> , cz ) ] > <NUM_LIT:0> , DoG [ np . ix_ ( rz + <NUM_LIT:1> , cz ) ] < <NUM_LIT:0> ) , <EOL> abs ( DoG [ np . ix_ ( rz - <NUM_LIT:1> , cz ) ] - DoG [ np . ix_ ( rz + <NUM_LIT:1> , cz ) ] ) > thresh ) ) <EOL> e [ ( rx , cx ) ] = <NUM_LIT:1> <EOL> return e </s>
|
<s> def run ( verbose = False ) : <EOL> import nose <EOL> from os import path <EOL> currentdir = path . dirname ( __file__ ) <EOL> updir = path . join ( currentdir , '<STR_LIT:..>' ) <EOL> argv = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , updir ] <EOL> if verbose : <EOL> argv . append ( '<STR_LIT>' ) <EOL> nose . run ( '<STR_LIT>' , argv = argv ) </s>
|
<s> def test_import ( ) : <EOL> import mahotas </s>
|
<s> from keywordgroup import KeywordGroup <EOL> from util import Util <EOL> class JavaScript ( KeywordGroup ) : <EOL> def execute_javascript ( self , code , * args ) : <EOL> """<STR_LIT>""" <EOL> self . _info ( "<STR_LIT>" % code ) <EOL> return Util . driver . execute_script ( code , * args ) </s>
|
<s> from django . contrib . syndication . feeds import Feed <EOL> from projector . models import Project <EOL> class LatestProjectsFeed ( Feed ) : <EOL> title = "<STR_LIT>" <EOL> link = "<STR_LIT>" <EOL> description = "<STR_LIT>" <EOL> def items ( self ) : <EOL> return Project . objects . order_by ( '<STR_LIT>' ) . filter ( public = True ) [ : <NUM_LIT:5> ] </s>
|
<s> import urlparse <EOL> from django . contrib . auth . models import User , Group <EOL> from django . core . urlresolvers import reverse <EOL> from django . test . client import Client <EOL> from projector . tests . base import ProjectorTestCase <EOL> from projector . models import Project , Membership , Team <EOL> from guardian . shortcuts import assign <EOL> class ProjectorPermissionTests ( ProjectorTestCase ) : <EOL> fixtures = [ '<STR_LIT>' ] <EOL> def setUp ( self ) : <EOL> self . client = Client ( ) <EOL> self . admin = User . objects . get ( username = '<STR_LIT>' ) <EOL> self . admin . _plain_password = '<STR_LIT>' <EOL> self . jack = User . objects . get ( username = '<STR_LIT>' ) <EOL> self . jack . _plain_password = '<STR_LIT>' <EOL> self . joe = User . objects . get ( username = '<STR_LIT>' ) <EOL> self . joe . _plain_password = '<STR_LIT>' <EOL> self . noperms = User . objects . get ( username = '<STR_LIT>' ) <EOL> self . noperms . _plain_password = '<STR_LIT>' <EOL> self . public_project = Project . objects . get ( name = '<STR_LIT>' ) <EOL> self . private_project = Project . objects . get ( name = '<STR_LIT>' ) <EOL> def test_anonymous ( self ) : <EOL> self . client . logout ( ) <EOL> url = self . public_project . get_absolute_url ( ) <EOL> self . _get_response ( url ) <EOL> url = reverse ( '<STR_LIT>' ) <EOL> response = self . _get_response ( url , follow = True ) <EOL> self . assertTrue ( len ( response . redirect_chain ) == <NUM_LIT:1> ) <EOL> passed_url , passed_code = response . redirect_chain [ <NUM_LIT:0> ] <EOL> parsed = urlparse . urlparse ( passed_url ) <EOL> self . assertEqual ( parsed . path , reverse ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( parsed . query , '<STR_LIT>' % url ) <EOL> def test ( self ) : <EOL> for user in ( self . admin , self . noperms , self . joe , self . jack ) : <EOL> client = self . client <EOL> client . login ( username = user . username , password = user . _plain_password ) <EOL> url = self . public_project . get_absolute_url ( ) <EOL> response = client . get ( url ) <EOL> self . assertTrue ( response . status_code == <NUM_LIT:200> , <EOL> "<STR_LIT>" <EOL> % user ) <EOL> client . logout ( ) <EOL> user = self . jack <EOL> client = self . client <EOL> client . login ( username = user . username , password = user . _plain_password ) <EOL> urls = ( <EOL> self . private_project . get_absolute_url ( ) , <EOL> self . private_project . get_edit_url ( ) , <EOL> self . private_project . get_members_url ( ) , <EOL> self . private_project . get_members_add_url ( ) , <EOL> self . private_project . get_teams_url ( ) , <EOL> self . private_project . get_teams_add_url ( ) , <EOL> self . private_project . get_fork_url ( ) , <EOL> self . private_project . get_state_url ( ) , <EOL> self . private_project . get_task_list_url ( ) , <EOL> self . private_project . get_create_task_url ( ) , <EOL> self . private_project . get_milestones_url ( ) , <EOL> self . private_project . get_milestone_add_url ( ) , <EOL> self . private_project . get_components_url ( ) , <EOL> self . private_project . get_component_add_url ( ) , <EOL> self . private_project . get_workflow_url ( ) , <EOL> self . private_project . get_workflow_edit_url ( ) , <EOL> self . private_project . get_workflow_add_status_url ( ) , <EOL> self . private_project . get_browse_repo_url ( ) , <EOL> self . private_project . get_changesets_url ( ) , <EOL> ) <EOL> for url in urls : <EOL> response = self . client . get ( url ) <EOL> self . assertTrue ( response . status_code == <NUM_LIT> , <EOL> "<STR_LIT>" <EOL> % ( user , url , response . status_code ) ) <EOL> new_member = User . objects . create_user ( <EOL> username = '<STR_LIT>' , <EOL> email = '<STR_LIT>' , <EOL> password = '<STR_LIT>' ) <EOL> new_member . _plain_password = '<STR_LIT>' <EOL> Membership . objects . create ( member = new_member , <EOL> project = self . private_project ) <EOL> new_group = Group . objects . create ( name = '<STR_LIT>' ) <EOL> team = Team . objects . create ( group = new_group , <EOL> project = self . private_project ) <EOL> responses = ( <EOL> self . client . get ( <EOL> self . private_project . get_members_edit_url ( new_member . username ) ) , <EOL> self . client . post ( <EOL> self . private_project . get_members_edit_url ( new_member . username ) , <EOL> data = { } ) , <EOL> self . client . get ( <EOL> self . private_project . get_teams_edit_url ( team . group . name ) ) , <EOL> self . client . post ( <EOL> self . private_project . get_teams_edit_url ( team . group . name ) , <EOL> data = { } ) , <EOL> ) <EOL> for response in responses : <EOL> self . assertTrue ( response . status_code == <NUM_LIT> , <EOL> "<STR_LIT>" <EOL> % ( user , response . request [ '<STR_LIT>' ] , <EOL> response . request [ '<STR_LIT>' ] , response . status_code ) ) <EOL> url = reverse ( '<STR_LIT>' ) <EOL> resp = self . _get_response ( url ) <EOL> project_list = resp . context [ '<STR_LIT>' ] <EOL> for_user = Project . objects . for_user ( user ) <EOL> self . assertEqual ( set ( project_list ) , set ( for_user ) , <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % ( project_list , for_user ) ) <EOL> Membership . objects . create ( member = user , project = self . private_project ) <EOL> for url in urls : <EOL> response = self . client . get ( url ) <EOL> self . assertTrue ( response . status_code == <NUM_LIT> , <EOL> "<STR_LIT>" <EOL> % ( user , url , response . status_code ) ) <EOL> responses = ( <EOL> self . client . get ( <EOL> self . private_project . get_members_edit_url ( new_member . username ) ) , <EOL> self . client . post ( <EOL> self . private_project . get_members_edit_url ( new_member . username ) , <EOL> data = { } ) , <EOL> self . client . get ( <EOL> self . private_project . get_teams_edit_url ( team . group . name ) ) , <EOL> self . client . post ( <EOL> self . private_project . get_teams_edit_url ( team . group . name ) , <EOL> data = { } ) , <EOL> ) <EOL> for response in responses : <EOL> self . assertTrue ( response . status_code == <NUM_LIT> , <EOL> "<STR_LIT>" <EOL> % ( user , response . request [ '<STR_LIT>' ] , <EOL> response . request [ '<STR_LIT>' ] , response . status_code ) ) <EOL> assign ( '<STR_LIT>' , user , self . private_project ) <EOL> url = self . private_project . get_absolute_url ( ) <EOL> self . _get_response ( url ) <EOL> urls = ( <EOL> self . private_project . get_components_url ( ) , <EOL> self . private_project . get_milestones_url ( ) , <EOL> self . private_project . get_workflow_url ( ) , <EOL> self . private_project . get_state_url ( ) , <EOL> ) <EOL> for ulr in urls : <EOL> self . _get_response ( url , code = <NUM_LIT:200> ) <EOL> self . client . logout ( ) </s>
|
<s> from django . shortcuts import render_to_response <EOL> from django . http import HttpResponse , HttpResponseRedirect <EOL> from django . utils . translation import string_concat , ugettext as _ <EOL> from django . contrib import messages <EOL> import logging <EOL> try : <EOL> import reportlab <EOL> from reportlab . graphics . shapes import Drawing <EOL> from reportlab . lib import colors <EOL> from reportlab . graphics . charts . piecharts import Pie , Pie3d <EOL> except ImportError : <EOL> reportlab = None <EOL> from projector . models import Task , Status <EOL> def task_reports ( request , template_name = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> return get_actual_status_img ( request ) <EOL> def get_actual_status_img ( request , output_format = '<STR_LIT>' , width = <NUM_LIT> , height = <NUM_LIT> ) : <EOL> if reportlab is None : <EOL> messages . error ( request , _ ( "<STR_LIT>" ) + "<STR_LIT>" + _ ( "<STR_LIT>" ) ) <EOL> try : <EOL> redirect_to = request . META [ '<STR_LIT>' ] <EOL> except KeyError : <EOL> redirect_to = '<STR_LIT:/>' <EOL> return HttpResponseRedirect ( redirect_to ) <EOL> status_list = Status . objects . all ( ) <EOL> drawing = Drawing ( width , height ) <EOL> pie = Pie3d ( ) <EOL> pie . x = <NUM_LIT:100> <EOL> pie . y = <NUM_LIT:100> <EOL> pie . width = width / <NUM_LIT:2> <EOL> pie . height = height / <NUM_LIT:2> <EOL> pie . labels = [ s . name for s in status_list ] <EOL> pie . data = [ s . task_set . count ( ) for s in status_list ] <EOL> pie . slices [ <NUM_LIT:3> ] . fontColor = colors . red <EOL> pie . slices [ <NUM_LIT:0> ] . fillColor = colors . darkcyan <EOL> pie . slices [ <NUM_LIT:1> ] . fillColor = colors . blueviolet <EOL> pie . slices [ <NUM_LIT:2> ] . fillColor = colors . blue <EOL> pie . slices [ <NUM_LIT:3> ] . fillColor = colors . cyan <EOL> pie . slices [ <NUM_LIT:4> ] . fillColor = colors . aquamarine <EOL> pie . slices [ <NUM_LIT:5> ] . fillColor = colors . cadetblue <EOL> pie . slices [ <NUM_LIT:6> ] . fillColor = colors . lightcoral <EOL> drawing . add ( pie ) <EOL> image = drawing . asString ( output_format ) <EOL> response = HttpResponse ( image , mimetype = '<STR_LIT>' % output_format . lower ( ) ) <EOL> return response </s>
|
<s> from __future__ import absolute_import , unicode_literals <EOL> from django . db import connections <EOL> from django . db . utils import DEFAULT_DB_ALIAS <EOL> def _detect_gis_backend ( ) : <EOL> """<STR_LIT>""" <EOL> if '<STR_LIT>' in connections [ DEFAULT_DB_ALIAS ] . __module__ : <EOL> return True <EOL> if '<STR_LIT>' in connections [ DEFAULT_DB_ALIAS ] . __module__ : <EOL> try : <EOL> from django . contrib . gis . geos import GEOSException <EOL> return True <EOL> except ImportError : <EOL> return False <EOL> return False <EOL> gis_backend = _detect_gis_backend ( ) </s>
|
<s> from __future__ import absolute_import , unicode_literals <EOL> from django . test import TestCase <EOL> from django . utils . unittest import skipIf <EOL> import django <EOL> import os <EOL> @ skipIf ( '<STR_LIT>' not in os . environ , '<STR_LIT>' ) <EOL> class VersionSuite ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_django_version ( self ) : <EOL> target = [ int ( i ) for i in os . environ [ '<STR_LIT>' ] . split ( '<STR_LIT:.>' ) ] <EOL> for expected , actual in zip ( target , django . VERSION ) : <EOL> self . assertEqual ( expected , actual ) </s>
|
<s> import itertools <EOL> import os <EOL> import pty <EOL> import select <EOL> import socket <EOL> import sublime <EOL> import subprocess <EOL> import threading <EOL> from . edit import Edit <EOL> from . term import VT100 <EOL> VISUAL_MODES = ( '<STR_LIT>' , '<STR_LIT:v>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> replace = [ <EOL> ( '<STR_LIT:\\>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:">' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:\n>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:\r>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:\t>' , '<STR_LIT>' ) , <EOL> ] <EOL> def encode ( s , t = None ) : <EOL> types = [ <EOL> ( str , '<STR_LIT:string>' ) , <EOL> ( ( int , float ) , '<STR_LIT>' ) , <EOL> ( bool , '<STR_LIT>' ) , <EOL> ] <EOL> if t is None : <EOL> for typ , b in types : <EOL> if isinstance ( s , typ ) : <EOL> t = b <EOL> break <EOL> else : <EOL> return '<STR_LIT>' <EOL> if t == '<STR_LIT:string>' : <EOL> for a , b in replace : <EOL> s = s . replace ( a , b ) <EOL> return '<STR_LIT:">' + s + '<STR_LIT:">' <EOL> elif t == '<STR_LIT>' : <EOL> return str ( s ) <EOL> elif t == '<STR_LIT>' : <EOL> return '<STR_LIT:T>' if s else '<STR_LIT:F>' <EOL> elif t == '<STR_LIT>' : <EOL> if isinstance ( s , ( int , float ) ) or s : <EOL> return str ( s ) <EOL> else : <EOL> return encode ( '<STR_LIT:none>' ) <EOL> def decode ( s , t = None ) : <EOL> if t is None : <EOL> if s . startswith ( '<STR_LIT:">' ) : <EOL> t = '<STR_LIT:string>' <EOL> elif s . replace ( '<STR_LIT:.>' , '<STR_LIT>' , <NUM_LIT:1> ) . isdigit ( ) : <EOL> t = '<STR_LIT>' <EOL> elif s in '<STR_LIT>' : <EOL> t = '<STR_LIT>' <EOL> else : <EOL> return s <EOL> if t == '<STR_LIT:string>' : <EOL> s = s [ <NUM_LIT:1> : - <NUM_LIT:1> ] <EOL> lookup = { r [ <NUM_LIT:1> ] : r [ <NUM_LIT:0> ] for r in replace } <EOL> i = <NUM_LIT:0> <EOL> while i < len ( s ) - <NUM_LIT:1> : <EOL> cur = s [ i : i + <NUM_LIT:2> ] <EOL> if cur in lookup : <EOL> rep = lookup [ cur ] <EOL> s = s [ : i ] + rep + s [ i + <NUM_LIT:2> : ] <EOL> i += len ( rep ) <EOL> continue <EOL> i += <NUM_LIT:1> <EOL> return s <EOL> elif t == '<STR_LIT>' : <EOL> return float ( s ) <EOL> elif t == '<STR_LIT>' : <EOL> return True if s == '<STR_LIT:T>' else False <EOL> else : <EOL> return s <EOL> class VimSocket : <EOL> def __init__ ( self , vim , view , callback = None ) : <EOL> self . vim = vim <EOL> self . view = view <EOL> self . server = socket . socket ( ) <EOL> self . server . bind ( ( '<STR_LIT:localhost>' , <NUM_LIT:0> ) ) <EOL> self . server . listen ( <NUM_LIT:1> ) <EOL> self . client = None <EOL> self . extra = '<STR_LIT>' <EOL> self . port = self . server . getsockname ( ) [ <NUM_LIT:1> ] <EOL> self . serial = itertools . count ( start = <NUM_LIT:2> ) <EOL> self . callbacks = { } <EOL> self . callback = callback <EOL> self . preload = [ ] <EOL> def spawn ( self ) : <EOL> threading . Thread ( target = self . loop ) . start ( ) <EOL> def active ( self ) : <EOL> return self . view . buffer_id ( ) != <NUM_LIT:0> and self . server . fileno ( ) >= <NUM_LIT:0> <EOL> def handle ( self , data ) : <EOL> view = self . view <EOL> data = self . extra + data <EOL> commands = data . split ( '<STR_LIT:\n>' ) <EOL> self . extra = commands . pop ( ) <EOL> edits = [ ] <EOL> for cmd in commands : <EOL> if '<STR_LIT::>' in cmd : <EOL> buf , cmd = cmd . split ( '<STR_LIT::>' , <NUM_LIT:1> ) <EOL> cmd , args = cmd . split ( '<STR_LIT:=>' , <NUM_LIT:1> ) <EOL> if '<STR_LIT:U+0020>' in args : <EOL> seq , args = args . split ( '<STR_LIT:U+0020>' , <NUM_LIT:1> ) <EOL> else : <EOL> seq , args = args , None <EOL> seq = int ( seq ) <EOL> if cmd == '<STR_LIT>' : <EOL> pos , text = args . split ( '<STR_LIT:U+0020>' , <NUM_LIT:1> ) <EOL> text = decode ( text , '<STR_LIT:string>' ) <EOL> pos = decode ( pos ) <EOL> edits . append ( ( '<STR_LIT>' , pos , text ) ) <EOL> elif cmd == '<STR_LIT>' : <EOL> pos , length = args . split ( '<STR_LIT:U+0020>' , <NUM_LIT:1> ) <EOL> pos , length = int ( pos ) , int ( length ) <EOL> if length > <NUM_LIT:0> : <EOL> edits . append ( ( '<STR_LIT>' , sublime . Region ( pos , pos + length ) ) ) <EOL> elif cmd == '<STR_LIT>' : <EOL> view . set_scratch ( True ) <EOL> raise socket . error <EOL> else : <EOL> if '<STR_LIT:U+0020>' in cmd : <EOL> seq , cmd = cmd . split ( '<STR_LIT:U+0020>' , <NUM_LIT:1> ) <EOL> else : <EOL> seq , cmd = cmd , '<STR_LIT>' <EOL> if seq . isdigit ( ) : <EOL> seq = int ( seq ) <EOL> callback = self . callbacks . pop ( seq , None ) <EOL> if callback : <EOL> callback ( cmd ) <EOL> if edits : <EOL> def cursor ( args ) : <EOL> buf , lnum , col , off = [ int ( a ) for a in args . split ( '<STR_LIT:U+0020>' ) ] <EOL> with Edit ( view ) as edit : <EOL> for args in edits : <EOL> edit . step ( * args ) <EOL> edit . reselect ( off ) <EOL> self . callback ( self . vim ) <EOL> self . get_cursor ( cursor ) <EOL> def send ( self , data ) : <EOL> if not self . client : <EOL> self . preload . append ( data ) <EOL> return <EOL> try : <EOL> data = ( data + '<STR_LIT:\r\n>' ) . encode ( '<STR_LIT:utf8>' ) <EOL> self . client . send ( data ) <EOL> except socket . error : <EOL> self . close ( ) <EOL> def close ( self , disconnect = False ) : <EOL> self . view . close ( ) <EOL> if self . client : <EOL> if disconnect : <EOL> self . send ( '<STR_LIT>' ) <EOL> self . client . close ( ) <EOL> def loop ( self ) : <EOL> sockets = [ self . server ] <EOL> try : <EOL> while self . active ( ) : <EOL> try : <EOL> ready , _ , _ = select . select ( sockets , [ ] , [ ] , <NUM_LIT:0.1> ) <EOL> except ValueError : <EOL> raise socket . error <EOL> if not self . client : <EOL> if self . server in ready : <EOL> print ( '<STR_LIT>' ) <EOL> self . client , addr = self . server . accept ( ) <EOL> sockets = [ self . client ] <EOL> self . cmd ( '<STR_LIT:1>' , '<STR_LIT>' ) <EOL> for line in self . preload : <EOL> self . send ( line ) <EOL> else : <EOL> continue <EOL> elif self . client in ready : <EOL> data = self . client . recv ( <NUM_LIT> ) . decode ( '<STR_LIT:utf8>' ) <EOL> if '<STR_LIT>' in data and not '<STR_LIT>' in data : <EOL> more , _ , _ = select . select ( [ self . client ] , [ ] , [ ] , <NUM_LIT:1.0> / <NUM_LIT> ) <EOL> if more : <EOL> data += self . client . recv ( <NUM_LIT> ) . decode ( '<STR_LIT:utf8>' ) <EOL> if data : <EOL> self . handle ( data ) <EOL> else : <EOL> break <EOL> except socket . error : <EOL> pass <EOL> finally : <EOL> self . close ( disconnect = True ) <EOL> def cmd ( self , buf , name , * args , ** kwargs ) : <EOL> seq = kwargs . get ( '<STR_LIT>' , <NUM_LIT:1> ) <EOL> sep = kwargs . get ( '<STR_LIT>' , '<STR_LIT:!>' ) <EOL> cmd = '<STR_LIT>' . format ( buf , name , sep , seq ) <EOL> if args is not None : <EOL> cmd += '<STR_LIT:U+0020>' + '<STR_LIT:U+0020>' . join ( encode ( a ) for a in args ) <EOL> self . send ( cmd ) <EOL> def func ( self , * args , ** kwargs ) : <EOL> return self . cmd ( * args , sep = '<STR_LIT:/>' , ** kwargs ) <EOL> def add_callback ( self , callback ) : <EOL> if not callback : <EOL> return None <EOL> serial = next ( self . serial ) <EOL> self . callbacks [ serial ] = callback <EOL> return serial <EOL> def get_cursor ( self , callback ) : <EOL> serial = self . add_callback ( callback ) <EOL> self . func ( '<STR_LIT:1>' , '<STR_LIT>' , seq = serial ) <EOL> def set_cursor ( self , offset , callback = None ) : <EOL> serial = self . add_callback ( callback ) <EOL> self . cmd ( '<STR_LIT:1>' , '<STR_LIT>' , offset , seq = serial ) <EOL> def insert ( self , offset , text ) : <EOL> self . func ( '<STR_LIT:1>' , '<STR_LIT>' , offset , str ( text or '<STR_LIT>' ) ) <EOL> def init_done ( self ) : <EOL> self . cmd ( '<STR_LIT:1>' , '<STR_LIT>' ) <EOL> def set_path ( self , path ) : <EOL> self . cmd ( '<STR_LIT:1>' , '<STR_LIT>' , path ) <EOL> class Vim : <EOL> DEFAULT_CMD = ( '<STR_LIT>' , ) <EOL> @ property <EOL> def vimrc ( self ) : <EOL> return ( <EOL> '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' . format ( self . rows , self . cols ) , <EOL> '<STR_LIT>' , '''<STR_LIT>''' , <EOL> '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , <EOL> ) <EOL> def __init__ ( self , view , rows = <NUM_LIT> , cols = <NUM_LIT> , monitor = None , cmd = None , update = None , modify = None ) : <EOL> self . view = view <EOL> self . monitor = monitor <EOL> self . rows = rows <EOL> self . cols = cols <EOL> self . cmd = cmd or self . DEFAULT_CMD <EOL> self . update_callback = update <EOL> self . modify_callback = modify <EOL> self . proc = None <EOL> self . input = None <EOL> self . output = None <EOL> self . row = self . col = <NUM_LIT:0> <EOL> self . mode = '<STR_LIT:n>' <EOL> self . modified = False <EOL> self . visual = ( <NUM_LIT:0> , <NUM_LIT:0> ) <EOL> self . visual_selected = False <EOL> self . panel = None <EOL> self . tty = None <EOL> self . __serve ( ) <EOL> self . __spawn ( ) <EOL> def __spawn ( self ) : <EOL> master , slave = pty . openpty ( ) <EOL> devnul = open ( os . devnull , '<STR_LIT:r>' ) <EOL> cmd = self . cmd + ( '<STR_LIT>' . format ( self . port ) , ) + self . vimrc <EOL> self . proc = subprocess . Popen ( <EOL> cmd , stdin = slave , stdout = slave , <EOL> stderr = devnul , close_fds = True ) <EOL> self . output = os . fdopen ( master , '<STR_LIT:rb>' ) <EOL> self . input = os . fdopen ( master , '<STR_LIT:wb>' ) <EOL> def pump ( ) : <EOL> self . tty = v = VT100 ( self . cols , self . rows , callback = self . _update ) <EOL> while True : <EOL> b = self . output . read ( <NUM_LIT:1> ) <EOL> if not b : <EOL> break <EOL> v . append ( b ) <EOL> threading . Thread ( target = pump ) . start ( ) <EOL> def __serve ( self ) : <EOL> self . socket = VimSocket ( self , self . view , callback = self . modify_callback ) <EOL> self . port = self . socket . port <EOL> self . socket . spawn ( ) <EOL> def _update ( self , v , dirty , moved ) : <EOL> data = v . dump ( ) <EOL> self . status , self . cmdline = [ <EOL> s . strip ( ) for s in data . rsplit ( '<STR_LIT:\n>' ) [ - <NUM_LIT:3> : - <NUM_LIT:1> ] <EOL> ] <EOL> try : <EOL> if self . status . count ( '<STR_LIT:+>' ) >= <NUM_LIT:2> : <EOL> pos , rest = self . status . split ( '<STR_LIT:U+002C>' , <NUM_LIT:1> ) <EOL> row , col = pos . split ( '<STR_LIT:+>' , <NUM_LIT:1> ) <EOL> self . row , self . col = int ( row ) , int ( col ) <EOL> self . mode , vs , rest = rest . split ( '<STR_LIT:U+002C>' , <NUM_LIT:2> ) <EOL> a , b = vs . split ( '<STR_LIT:+>' , <NUM_LIT:1> ) <EOL> self . modified = ( rest == '<STR_LIT:+>' ) <EOL> self . visual = ( int ( a ) , int ( b ) ) <EOL> except ValueError : <EOL> pass <EOL> if self . monitor : <EOL> with Edit ( self . monitor ) as edit : <EOL> if dirty : <EOL> edit . erase ( sublime . Region ( <NUM_LIT:0> , self . monitor . size ( ) ) ) <EOL> edit . insert ( <NUM_LIT:0> , data ) <EOL> edit . reselect ( <EOL> lambda view : view . text_point ( v . row - <NUM_LIT:1> , v . col - <NUM_LIT:1> ) ) <EOL> def update_cursor ( view , edit ) : <EOL> row , col = ( self . row - <NUM_LIT:1> , self . col + <NUM_LIT:1> ) <EOL> if v . row == self . rows and v . col > <NUM_LIT:0> : <EOL> char = v . buf [ v . row - <NUM_LIT:1> ] [ <NUM_LIT:0> ] <EOL> if char in '<STR_LIT>' : <EOL> row , col = ( v . row - <NUM_LIT:1> , v . col - <NUM_LIT:1> ) <EOL> pos = view . text_point ( row , col ) <EOL> sel = sublime . Region ( pos , pos ) <EOL> view . add_regions ( <EOL> '<STR_LIT>' , [ sel ] , '<STR_LIT>' , <EOL> '<STR_LIT>' , sublime . DRAW_EMPTY , <EOL> ) <EOL> if moved : <EOL> edit . callback ( update_cursor ) <EOL> if self . update_callback : <EOL> self . update_callback ( self , dirty , moved ) <EOL> def send ( self , b ) : <EOL> if self . input : <EOL> self . input . write ( b . encode ( '<STR_LIT:utf8>' ) ) <EOL> self . input . flush ( ) <EOL> def press ( self , * keys ) : <EOL> for key in keys : <EOL> b = VT100 . map ( key ) <EOL> self . send ( b ) <EOL> def type ( self , text ) : <EOL> self . press ( * list ( text ) ) <EOL> def close ( self ) : <EOL> print ( '<STR_LIT>' ) <EOL> self . view . close ( ) <EOL> if self . panel : <EOL> self . panel . close ( ) <EOL> if self . monitor : <EOL> self . monitor . close ( ) <EOL> self . proc . kill ( ) <EOL> self . socket . close ( ) <EOL> def update_cursor ( self , * args , ** kwargs ) : <EOL> def callback ( args ) : <EOL> buf , lnum , col , off = [ int ( a ) for a in args . split ( '<STR_LIT:U+0020>' ) ] <EOL> with Edit ( self . view ) as edit : <EOL> edit . reselect ( off ) <EOL> self . socket . get_cursor ( callback ) <EOL> def get_cursor ( self , callback ) : <EOL> self . socket . get_cursor ( callback ) <EOL> def set_cursor ( self , offset , callback = None ) : <EOL> self . socket . set_cursor ( offset , callback = callback ) <EOL> def insert ( self , offset , text ) : <EOL> self . socket . insert ( offset , text ) <EOL> def init_done ( self ) : <EOL> self . socket . init_done ( ) <EOL> def set_path ( self , path ) : <EOL> self . socket . set_path ( path ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> import time <EOL> v = Vim ( ) <EOL> time . sleep ( <NUM_LIT:3> ) <EOL> v . send ( '<STR_LIT:i>' ) <EOL> while True : <EOL> v . send ( '<STR_LIT>' ) <EOL> time . sleep ( <NUM_LIT:1> ) </s>
|
<s> import xml . dom . minidom as minidom <EOL> from xml . sax . saxutils import escape , unescape , quoteattr <EOL> import os , re , codecs <EOL> class Parser : <EOL> topicRe = re . compile ( r'''<STR_LIT>''' ) <EOL> entityRe = re . compile ( r'<STR_LIT>' ) <EOL> def replaceAll ( self , string , regex , group = None , callback = None ) : <EOL> match = regex . search ( string ) <EOL> while match : <EOL> start , end = match . start ( group ) , match . end ( group ) <EOL> middle = string [ start : end ] <EOL> if callback : <EOL> middle = callback ( middle , match ) <EOL> else : <EOL> middle = '<STR_LIT>' <EOL> string = string [ : start ] + middle + string [ end : ] <EOL> match = regex . search ( string ) <EOL> return string <EOL> def findTopics ( self , xml ) : <EOL> topics = { } <EOL> matches = self . topicRe . finditer ( xml ) <EOL> for match in matches : <EOL> name , topic = match . group ( '<STR_LIT:name>' ) , match . group ( '<STR_LIT>' ) <EOL> topics [ name ] = topic <EOL> xml = self . replaceAll ( xml , self . topicRe , group = '<STR_LIT>' ) <EOL> return xml , topics <EOL> def resolveEntity ( self , ref , match ) : <EOL> entity = match . group ( '<STR_LIT>' ) <EOL> replacement = unescape ( ref ) <EOL> if replacement == ref : <EOL> replacement = '<STR_LIT>' <EOL> if not replacement : <EOL> if entity . startswith ( '<STR_LIT:#>' ) : <EOL> entity = entity [ <NUM_LIT:1> : ] <EOL> if entity . isdigit ( ) : <EOL> entity = int ( entity ) <EOL> if entity < <NUM_LIT> : <EOL> replacement = chr ( entity ) <EOL> return replacement <EOL> def resolveEntities ( self , string ) : <EOL> string = self . replaceAll ( string , self . entityRe , group = <NUM_LIT:0> , callback = self . resolveEntity ) <EOL> return string <EOL> def _parse ( self , string ) : <EOL> xml , topics = self . findTopics ( string ) <EOL> for chan in topics : <EOL> topics [ chan ] = self . resolveEntities ( topics [ chan ] ) <EOL> chans = { } <EOL> settings = minidom . parseString ( xml ) <EOL> channels = settings . getElementsByTagName ( '<STR_LIT>' ) <EOL> for channel in channels : <EOL> chanops = [ ] <EOL> ops = channel . getElementsByTagName ( '<STR_LIT>' ) <EOL> for op in ops : <EOL> chanops . append ( str ( op . getAttribute ( '<STR_LIT:name>' ) ) ) <EOL> owner = str ( channel . getAttribute ( '<STR_LIT>' ) ) or None <EOL> name = str ( channel . getAttribute ( '<STR_LIT:name>' ) ) <EOL> topic = None <EOL> if name in topics : <EOL> topic = topics [ name ] . decode ( '<STR_LIT:utf-8>' ) . encode ( '<STR_LIT>' ) <EOL> chan = { '<STR_LIT>' : str ( owner ) , '<STR_LIT:key>' : str ( channel . getAttribute ( '<STR_LIT:key>' ) ) or None , '<STR_LIT>' : topic or '<STR_LIT>' , '<STR_LIT>' : ( str ( channel . getAttribute ( '<STR_LIT>' ) ) == '<STR_LIT:yes>' ) , '<STR_LIT>' : chanops } <EOL> if chan [ '<STR_LIT:key>' ] == '<STR_LIT:*>' : chan [ '<STR_LIT:key>' ] = None <EOL> chans [ name ] = chan <EOL> return chans <EOL> def parse ( self , filename ) : <EOL> f = open ( filename , '<STR_LIT:r>' ) <EOL> data = f . read ( ) <EOL> f . close ( ) <EOL> return self . parseString ( data ) <EOL> def parseString ( self , string ) : <EOL> return self . _parse ( string ) <EOL> class Writer : <EOL> def dump ( self , channels , clientFromID ) : <EOL> f = codecs . open ( '<STR_LIT>' , '<STR_LIT:w>' , '<STR_LIT:utf-8>' ) <EOL> f . write ( '<STR_LIT>' ) <EOL> for channel in channels . values ( ) : <EOL> owner = clientFromID ( channel . owner ) <EOL> if owner : <EOL> topic = channel . topic <EOL> if topic and topic [ '<STR_LIT:text>' ] : topic = topic [ '<STR_LIT:text>' ] . decode ( '<STR_LIT>' ) <EOL> else : topic = '<STR_LIT:*>' <EOL> f . write ( '<STR_LIT>' % ( ( '<STR_LIT:yes>' if channel . antispam else '<STR_LIT>' ) , channel . chan , owner . username , escape ( quoteattr ( topic ) ) , escape ( quoteattr ( channel . key or '<STR_LIT:*>' ) ) ) ) <EOL> for admin in channel . admins : <EOL> admin = clientFromID ( admin ) <EOL> if admin : <EOL> f . write ( '<STR_LIT>' % admin . username ) <EOL> f . write ( '<STR_LIT>' ) <EOL> f . write ( '<STR_LIT>' ) <EOL> f . close ( ) <EOL> if os . path . exists ( '<STR_LIT>' ) and os . path . exists ( '<STR_LIT>' ) : <EOL> os . remove ( '<STR_LIT>' ) <EOL> os . rename ( '<STR_LIT>' , '<STR_LIT>' ) </s>
|
<s> from __future__ import absolute_import , unicode_literals <EOL> from functools import wraps <EOL> from mongorest . decorators import serializable <EOL> from mongorest . testcase import TestCase <EOL> class TestSerializable ( TestCase ) : <EOL> def setUp ( self ) : <EOL> @ serializable <EOL> def test ( * args , ** kwargs ) : <EOL> return { } <EOL> self . func = test <EOL> def test_serializable_creates_list_of_decorators_if_it_is_the_first ( self ) : <EOL> @ serializable <EOL> def test ( * args , ** kwargs ) : <EOL> return { } <EOL> self . assertIn ( '<STR_LIT>' , test . decorators ) <EOL> def test_serializable_appends_to_the_list_of_decorators_if_it_is_not_the_first ( self ) : <EOL> def test_decorator ( wrapped ) : <EOL> @ wraps ( wrapped ) <EOL> def wrapper ( * args , ** kwargs ) : <EOL> return wrapped ( * args , ** kwargs ) <EOL> if hasattr ( wrapped , '<STR_LIT>' ) : <EOL> wrapper . decorators = wrapped . decorators <EOL> wrapper . decorators . append ( '<STR_LIT>' ) <EOL> else : <EOL> wrapper . decorators = [ '<STR_LIT>' ] <EOL> return wrapper <EOL> @ serializable <EOL> @ test_decorator <EOL> def test ( * args , ** kwargs ) : <EOL> return { } <EOL> self . assertIn ( '<STR_LIT>' , test . decorators ) <EOL> def test_serializable_serializes_result_if_keyword_serialize_is_true ( self ) : <EOL> self . assertEqual ( self . func ( serialize = True ) , '<STR_LIT:{}>' ) <EOL> def test_serializable_does_not_serialize_if_keyword_serialize_is_false ( self ) : <EOL> self . assertEqual ( self . func ( serialize = False ) , { } ) <EOL> def test_serializable_does_not_serialize_if_keyword_serialize_is_not_passed ( self ) : <EOL> self . assertEqual ( self . func ( ) , { } ) </s>
|
<s> from __future__ import absolute_import , unicode_literals <EOL> MIDDLEWARES = [ '<STR_LIT>' ] <EOL> SESSION_STORE = '<STR_LIT>' <EOL> AUTH_COLLECTION = '<STR_LIT>' </s>
|
<s> from __future__ import absolute_import , unicode_literals <EOL> from mongorest . testcase import TestCase <EOL> from mongorest . wrappers import Response <EOL> class TestResponse ( TestCase ) : <EOL> def test_json_returns_serialized_data ( self ) : <EOL> self . assertEqual ( <EOL> Response ( response = '<STR_LIT>' ) . json , <EOL> { '<STR_LIT:1>' : <NUM_LIT:2> , '<STR_LIT:test>' : [ <NUM_LIT:1> , '<STR_LIT:2>' , None ] } <EOL> ) <EOL> def test_json_returns_empty_dict_if_no_data ( self ) : <EOL> self . assertEqual ( Response ( ) . json , { } ) </s>
|
<s> import os <EOL> import logging <EOL> from flask import send_from_directory <EOL> from werkzeug . exceptions import NotFound <EOL> from confidant import app <EOL> from confidant import authnz <EOL> @ app . route ( '<STR_LIT:/>' ) <EOL> @ authnz . require_auth <EOL> def index ( ) : <EOL> return app . send_static_file ( '<STR_LIT>' ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> def healthcheck ( ) : <EOL> return '<STR_LIT>' , <NUM_LIT:200> <EOL> @ app . route ( '<STR_LIT>' ) <EOL> def favicon ( ) : <EOL> return app . send_static_file ( '<STR_LIT>' ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> def not_found ( ) : <EOL> return app . send_static_file ( '<STR_LIT>' ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> def robots ( ) : <EOL> return app . send_static_file ( '<STR_LIT>' ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> def components ( path ) : <EOL> return app . send_static_file ( os . path . join ( '<STR_LIT>' , path ) ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> @ authnz . require_auth <EOL> def modules ( path ) : <EOL> return app . send_static_file ( os . path . join ( '<STR_LIT>' , path ) ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> def static_proxy ( path ) : <EOL> return app . send_static_file ( os . path . join ( '<STR_LIT>' , path ) ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> def scripts ( path ) : <EOL> return app . send_static_file ( os . path . join ( '<STR_LIT>' , path ) ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> def fonts ( path ) : <EOL> return app . send_static_file ( os . path . join ( '<STR_LIT>' , path ) ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> @ authnz . require_auth <EOL> def custom_modules ( path ) : <EOL> if not app . config [ '<STR_LIT>' ] : <EOL> return '<STR_LIT>' , <NUM_LIT:200> <EOL> try : <EOL> return send_from_directory ( <EOL> os . path . join ( app . config [ '<STR_LIT>' ] , '<STR_LIT>' ) , <EOL> path <EOL> ) <EOL> except NotFound : <EOL> logging . warning ( <EOL> '<STR_LIT>' . format ( path ) <EOL> ) <EOL> return '<STR_LIT>' , <NUM_LIT:200> <EOL> @ app . route ( '<STR_LIT>' ) <EOL> @ authnz . require_auth <EOL> def custom_styles ( path ) : <EOL> if not app . config [ '<STR_LIT>' ] : <EOL> return '<STR_LIT>' , <NUM_LIT> <EOL> return send_from_directory ( <EOL> os . path . join ( app . config [ '<STR_LIT>' ] , '<STR_LIT>' ) , <EOL> path <EOL> ) <EOL> @ app . route ( '<STR_LIT>' ) <EOL> @ authnz . require_auth <EOL> def custom_images ( path ) : <EOL> if not app . config [ '<STR_LIT>' ] : <EOL> return '<STR_LIT>' , <NUM_LIT> <EOL> return send_from_directory ( <EOL> os . path . join ( app . config [ '<STR_LIT>' ] , '<STR_LIT>' ) , <EOL> path <EOL> ) </s>
|
<s> """<STR_LIT>""" <EOL> copyright = """<STR_LIT>""" <EOL> from cmd import Cmd as _Cmd <EOL> from pprint import pprint as _pprint <EOL> import json as _json <EOL> try : <EOL> from moves import MovesClient <EOL> except ImportError : <EOL> import sys <EOL> from os . path import join , normpath <EOL> sys . path . insert ( <NUM_LIT:0> , normpath ( join ( sys . path [ <NUM_LIT:0> ] , '<STR_LIT:..>' ) ) ) <EOL> from moves import MovesClient <EOL> def _parse_line ( f ) : <EOL> import itertools <EOL> from functools import wraps <EOL> def partition ( pred , iterable , <EOL> filter = itertools . ifilter , <EOL> filterfalse = itertools . ifilterfalse , <EOL> tee = itertools . tee ) : <EOL> '<STR_LIT>' <EOL> t1 , t2 = tee ( iterable ) <EOL> return filterfalse ( pred , t1 ) , filter ( pred , t2 ) <EOL> @ wraps ( f ) <EOL> def wrapper ( self , line ) : <EOL> args , kwds = partition ( <EOL> lambda s : '<STR_LIT:=>' in s , <EOL> line . split ( ) ) <EOL> kwds = dict ( item . split ( '<STR_LIT:=>' ) for item in kwds ) <EOL> return f ( self , * args , ** kwds ) <EOL> return wrapper <EOL> class MovesCmd ( _Cmd ) : <EOL> cache_file = '<STR_LIT>' <EOL> def default ( self , line ) : <EOL> '''<STR_LIT>''' <EOL> print ` argv ` <EOL> def do_quit ( self , line ) : <EOL> '''<STR_LIT>''' <EOL> return True <EOL> def do_copyright ( self , line ) : <EOL> '''<STR_LIT>''' <EOL> print copyright <EOL> def do_client_id ( self , line ) : <EOL> '''<STR_LIT>''' <EOL> if line : <EOL> self . mc . client_id = line <EOL> elif self . mc . client_id : <EOL> print '<STR_LIT>' , self . mc . client_id <EOL> else : <EOL> print '<STR_LIT>' <EOL> def do_client_secret ( self , line ) : <EOL> '''<STR_LIT>''' <EOL> if line : <EOL> self . mc . client_secret = line <EOL> elif self . mc . client_secret : <EOL> print '<STR_LIT>' , self . mc . client_secret <EOL> else : <EOL> print '<STR_LIT>' <EOL> def do_access_token ( self , line ) : <EOL> '''<STR_LIT>''' <EOL> from urlparse import urlparse , parse_qs <EOL> mc = self . mc <EOL> if line : <EOL> parts = urlparse ( line ) <EOL> code = parse_qs ( parts . query ) [ '<STR_LIT:code>' ] [ <NUM_LIT:0> ] <EOL> mc . access_token = mc . get_oauth_token ( code ) <EOL> mc . access_token = line <EOL> elif mc . access_token : <EOL> print '<STR_LIT>' , mc . access_token <EOL> else : <EOL> print '<STR_LIT>' <EOL> print '<STR_LIT>' <EOL> print '<STR_LIT:U+0020>' , mc . build_oauth_url ( ) <EOL> print '<STR_LIT>' <EOL> print '<STR_LIT>' <EOL> def do_load ( self , filename ) : <EOL> '''<STR_LIT>''' <EOL> if not filename : <EOL> filename = self . cache_file <EOL> with open ( filename , '<STR_LIT:rb>' ) as fp : <EOL> self . mc . __dict__ . update ( _json . load ( fp ) ) <EOL> def do_save ( self , filename ) : <EOL> '''<STR_LIT>''' <EOL> if not filename : <EOL> filename = self . cache_file <EOL> with open ( filename , '<STR_LIT:wb>' ) as fp : <EOL> _json . dump ( self . mc . __dict__ , fp ) <EOL> @ _parse_line <EOL> def do_get ( self , * path , ** params ) : <EOL> '''<STR_LIT>''' <EOL> _pprint ( self . mc . get ( '<STR_LIT:/>' . join ( path ) , ** params ) ) <EOL> @ _parse_line <EOL> def do_post ( self , * path , ** params ) : <EOL> '''<STR_LIT>''' <EOL> _pprint ( self . mc . post ( '<STR_LIT:/>' . join ( path ) , ** params ) ) <EOL> def do_tokeninfo ( self , line ) : <EOL> '''<STR_LIT>''' <EOL> _pprint ( self . mc . tokeninfo ( ) ) <EOL> def do_examples ( self , line ) : <EOL> '''<STR_LIT>''' <EOL> print '''<STR_LIT>''' <EOL> def onecmd ( self , line ) : <EOL> try : <EOL> return _Cmd . onecmd ( self , line ) <EOL> except Exception as error : <EOL> print "<STR_LIT>" % ( type ( error ) . __name__ , error ) <EOL> def preloop ( self ) : <EOL> self . mc = MovesClient ( ) <EOL> def main ( argv ) : <EOL> MovesCmd ( ) . cmdloop ( ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> import sys <EOL> main ( sys . argv ) </s>
|
<s> import pprint <EOL> from planetlab import session <EOL> import sys <EOL> def usage ( ) : <EOL> return """<STR_LIT>""" <EOL> def main ( ) : <EOL> from optparse import OptionParser <EOL> parser = OptionParser ( usage = usage ( ) ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , action = "<STR_LIT:store_true>" , <EOL> default = False , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , action = "<STR_LIT:store_true>" , <EOL> default = False , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT:url>" , <EOL> default = session . API_URL , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> default = session . PLC_CONFIG , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , metavar = "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> default = None , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , metavar = "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> default = None , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , metavar = "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> default = None , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> action = "<STR_LIT:store_true>" , <EOL> default = False , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> action = "<STR_LIT:store_true>" , <EOL> default = False , <EOL> help = ( "<STR_LIT>" ) ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> action = "<STR_LIT:store_true>" , <EOL> default = False , <EOL> help = ( "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" ) ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> action = "<STR_LIT:store_true>" , <EOL> default = False , <EOL> help = ( "<STR_LIT>" ) ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , action = "<STR_LIT:store_true>" , <EOL> dest = "<STR_LIT>" , <EOL> default = False , <EOL> help = ( "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" ) ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> action = "<STR_LIT:store_true>" , <EOL> default = False , <EOL> help = ( "<STR_LIT>" ) ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> default = False , <EOL> action = "<STR_LIT:store_true>" , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , action = "<STR_LIT:store_true>" , <EOL> dest = "<STR_LIT>" , <EOL> default = False , <EOL> help = ( "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" ) ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> action = "<STR_LIT:store_true>" , <EOL> default = False , <EOL> help = ( "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" ) ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , metavar = "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> default = "<STR_LIT>" , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , metavar = "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> default = "<STR_LIT>" , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , metavar = "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> default = "<STR_LIT>" , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_option ( "<STR_LIT>" , "<STR_LIT>" , metavar = "<STR_LIT>" , dest = "<STR_LIT>" , <EOL> default = "<STR_LIT>" , <EOL> help = "<STR_LIT>" ) <EOL> ( options , args ) = parser . parse_args ( ) <EOL> if len ( sys . argv ) == <NUM_LIT:1> : <EOL> parser . print_help ( ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> if options . allsteps : <EOL> options . addwhitelist = True <EOL> options . addsliceips = True <EOL> options . addinterfaces = True <EOL> options . addnodes = True <EOL> options . addusers = True <EOL> site_list = getattr ( __import__ ( options . sitesname ) , options . sitelist ) <EOL> slice_list = getattr ( __import__ ( options . slicesname ) , options . slicelist ) <EOL> print "<STR_LIT>" <EOL> session . setup_global_session ( options . url , options . debug , options . verbose , <EOL> options . plcconfig ) <EOL> print "<STR_LIT>" <EOL> for sslice in slice_list : <EOL> for site in site_list : <EOL> for host in site [ '<STR_LIT>' ] : <EOL> h = site [ '<STR_LIT>' ] [ host ] <EOL> sslice . add_node_address ( h ) <EOL> if options . syncsite is not None and options . syncslice is None : <EOL> print "<STR_LIT>" <EOL> for site in site_list : <EOL> if ( options . syncsite == "<STR_LIT:all>" or <EOL> options . syncsite == site [ '<STR_LIT:name>' ] ) : <EOL> print "<STR_LIT>" , site [ '<STR_LIT:name>' ] <EOL> site . sync ( options . ondest , <EOL> options . addusers , <EOL> options . addnodes , <EOL> options . addinterfaces , <EOL> options . getbootimages , <EOL> options . createusers ) <EOL> elif options . syncslice is not None and options . syncsite is None : <EOL> print options . syncslice <EOL> for sslice in slice_list : <EOL> if ( options . syncslice == "<STR_LIT:all>" or <EOL> options . syncslice == sslice [ '<STR_LIT:name>' ] ) : <EOL> print "<STR_LIT>" , sslice [ '<STR_LIT:name>' ] <EOL> sslice . sync ( options . ondest , <EOL> options . addwhitelist , <EOL> options . addsliceips , <EOL> options . addusers , <EOL> options . createslice ) <EOL> else : <EOL> print usage ( ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> try : <EOL> main ( ) <EOL> except KeyboardInterrupt : <EOL> pass </s>
|
<s> import subprocess <EOL> from migen import * <EOL> from migen . fhdl . verilog import convert <EOL> class ParentModule ( Module ) : <EOL> def __init__ ( self ) : <EOL> self . inputs = [ Signal ( x + <NUM_LIT:1> , name = "<STR_LIT>" . format ( x ) ) for x in range ( <NUM_LIT:4> ) ] <EOL> self . trans = [ Signal ( x + <NUM_LIT:1> ) for x in range ( <NUM_LIT:4> ) ] <EOL> self . outputs = [ Signal ( x + <NUM_LIT:1> , name = "<STR_LIT>" . format ( x ) ) for x in range ( <NUM_LIT:4> ) ] <EOL> self . io = set ( self . inputs ) | set ( self . outputs ) <EOL> i = Instance ( "<STR_LIT>" , <EOL> i_master_clk = ClockSignal ( ) , <EOL> i_master_rst = ResetSignal ( ) , <EOL> i_input0 = self . inputs [ <NUM_LIT:0> ] , <EOL> i_input1 = self . inputs [ <NUM_LIT:1> ] , <EOL> i_input2 = self . inputs [ <NUM_LIT:2> ] , <EOL> i_input3 = self . inputs [ <NUM_LIT:3> ] , <EOL> o_output0 = self . trans [ <NUM_LIT:0> ] , <EOL> o_output1 = self . trans [ <NUM_LIT:1> ] , <EOL> o_output2 = self . trans [ <NUM_LIT:2> ] , <EOL> o_output3 = self . trans [ <NUM_LIT:3> ] <EOL> ) <EOL> j = Instance ( "<STR_LIT>" , <EOL> i_master_clk = ClockSignal ( ) , <EOL> i_master_rst = ResetSignal ( ) , <EOL> i_input0 = self . trans [ <NUM_LIT:0> ] , <EOL> i_input1 = self . trans [ <NUM_LIT:1> ] , <EOL> i_input2 = self . trans [ <NUM_LIT:2> ] , <EOL> i_input3 = self . trans [ <NUM_LIT:3> ] , <EOL> o_output0 = self . outputs [ <NUM_LIT:0> ] , <EOL> o_output1 = self . outputs [ <NUM_LIT:1> ] , <EOL> o_output2 = self . outputs [ <NUM_LIT:2> ] , <EOL> o_output3 = self . outputs [ <NUM_LIT:3> ] <EOL> ) <EOL> self . specials += i , j <EOL> class ChildModule ( Module ) : <EOL> def __init__ ( self ) : <EOL> self . inputs = [ Signal ( x + <NUM_LIT:1> , name_override = "<STR_LIT>" . format ( x ) ) for x in range ( <NUM_LIT:4> ) ] <EOL> self . outputs = [ Signal ( x + <NUM_LIT:1> , name_override = "<STR_LIT>" . format ( x ) ) for x in range ( <NUM_LIT:4> ) ] <EOL> self . io = set ( ) <EOL> for x in range ( <NUM_LIT:4> ) : <EOL> self . sync . master += self . outputs [ x ] . eq ( self . inputs [ x ] ) <EOL> self . io = self . io . union ( self . inputs ) <EOL> self . io = self . io . union ( self . outputs ) <EOL> def test_instance_module ( ) : <EOL> sub = ChildModule ( ) <EOL> convert ( sub , sub . io , name = "<STR_LIT>" ) . write ( "<STR_LIT>" ) <EOL> im = ParentModule ( ) <EOL> convert ( im , im . io , name = "<STR_LIT>" ) . write ( "<STR_LIT>" ) <EOL> subprocess . check_call ( [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:all>" , <EOL> "<STR_LIT>" , "<STR_LIT>" ] ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> test_instance_module ( ) </s>
|
<s> from migen . build . generic_platform import * <EOL> from migen . build . xilinx import XilinxPlatform <EOL> _ios = [ <EOL> ( "<STR_LIT>" , <NUM_LIT:0> , Pins ( "<STR_LIT>" ) , IOStandard ( "<STR_LIT>" ) ) , <EOL> ( "<STR_LIT>" , <NUM_LIT:0> , Pins ( "<STR_LIT>" ) , IOStandard ( "<STR_LIT>" ) , Drive ( "<STR_LIT>" ) ) , <EOL> ( "<STR_LIT>" , <NUM_LIT:0> , Pins ( "<STR_LIT>" ) , IOStandard ( "<STR_LIT>" ) , Drive ( "<STR_LIT>" ) ) , <EOL> ( "<STR_LIT>" , <NUM_LIT:0> , <EOL> Subsignal ( "<STR_LIT>" , Pins ( "<STR_LIT>" ) , IOStandard ( "<STR_LIT>" ) , Drive ( "<STR_LIT>" ) ) , <EOL> Subsignal ( "<STR_LIT>" , Pins ( "<STR_LIT>" ) , IOStandard ( "<STR_LIT>" ) ) , <EOL> Subsignal ( "<STR_LIT>" , Pins ( "<STR_LIT>" ) , IOStandard ( "<STR_LIT>" ) ) , <EOL> Subsignal ( "<STR_LIT>" , Pins ( "<STR_LIT>" ) , IOStandard ( "<STR_LIT>" ) ) , <EOL> Subsignal ( "<STR_LIT:data>" , <EOL> Pins ( "<STR_LIT>" ) , <EOL> IOStandard ( "<STR_LIT>" ) , Drive ( "<STR_LIT>" ) ) , <EOL> Subsignal ( "<STR_LIT>" , <EOL> Pins ( "<STR_LIT>" ) , <EOL> IOStandard ( "<STR_LIT>" ) ) <EOL> ) <EOL> ] <EOL> _connectors = [ <EOL> ( "<STR_LIT>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT:None>" , <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> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT:None>" , <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> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <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> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <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> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" , <EOL> "<STR_LIT:None>" ) <EOL> ] <EOL> class Platform ( XilinxPlatform ) : <EOL> default_clk_name = "<STR_LIT>" <EOL> default_clk_period = <NUM_LIT:10> <EOL> def __init__ ( self ) : <EOL> XilinxPlatform . __init__ ( self , "<STR_LIT>" , _ios , _connectors ) </s>
|
<s> import os <EOL> import subprocess <EOL> import sys <EOL> from migen . fhdl . structure import _Fragment <EOL> from migen . build . generic_platform import * <EOL> from migen . build import tools <EOL> from migen . build . xilinx import common <EOL> def _format_constraint ( c ) : <EOL> if isinstance ( c , Pins ) : <EOL> return "<STR_LIT>" + c . identifiers [ <NUM_LIT:0> ] <EOL> elif isinstance ( c , IOStandard ) : <EOL> return "<STR_LIT>" + c . name <EOL> elif isinstance ( c , Drive ) : <EOL> return "<STR_LIT>" + str ( c . strength ) <EOL> elif isinstance ( c , Misc ) : <EOL> return c . misc <EOL> def _format_ucf ( signame , pin , others , resname ) : <EOL> fmt_c = [ ] <EOL> for c in [ Pins ( pin ) ] + others : <EOL> fc = _format_constraint ( c ) <EOL> if fc is not None : <EOL> fmt_c . append ( fc ) <EOL> fmt_r = resname [ <NUM_LIT:0> ] + "<STR_LIT::>" + str ( resname [ <NUM_LIT:1> ] ) <EOL> if resname [ <NUM_LIT:2> ] is not None : <EOL> fmt_r += "<STR_LIT:.>" + resname [ <NUM_LIT:2> ] <EOL> return "<STR_LIT>" + signame + "<STR_LIT>" + "<STR_LIT>" . join ( fmt_c ) + "<STR_LIT>" + fmt_r + "<STR_LIT:\n>" <EOL> def _build_ucf ( named_sc , named_pc ) : <EOL> r = "<STR_LIT>" <EOL> for sig , pins , others , resname in named_sc : <EOL> if len ( pins ) > <NUM_LIT:1> : <EOL> for i , p in enumerate ( pins ) : <EOL> r += _format_ucf ( sig + "<STR_LIT:(>" + str ( i ) + "<STR_LIT:)>" , p , others , resname ) <EOL> else : <EOL> r += _format_ucf ( sig , pins [ <NUM_LIT:0> ] , others , resname ) <EOL> if named_pc : <EOL> r += "<STR_LIT:\n>" + "<STR_LIT>" . join ( named_pc ) <EOL> return r <EOL> def _build_xst_files ( device , sources , vincpaths , build_name , xst_opt ) : <EOL> prj_contents = "<STR_LIT>" <EOL> for filename , language , library in sources : <EOL> prj_contents += language + "<STR_LIT:U+0020>" + library + "<STR_LIT:U+0020>" + filename + "<STR_LIT:\n>" <EOL> tools . write_to_file ( build_name + "<STR_LIT>" , prj_contents ) <EOL> xst_contents = """<STR_LIT>""" . format ( build_name = build_name , xst_opt = xst_opt , device = device ) <EOL> for path in vincpaths : <EOL> xst_contents += "<STR_LIT>" + path + "<STR_LIT:\n>" <EOL> tools . write_to_file ( build_name + "<STR_LIT>" , xst_contents ) <EOL> def _run_yosys ( device , sources , vincpaths , build_name ) : <EOL> ys_contents = "<STR_LIT>" <EOL> incflags = "<STR_LIT>" <EOL> for path in vincpaths : <EOL> incflags += "<STR_LIT>" + path <EOL> for filename , language , library in sources : <EOL> ys_contents += "<STR_LIT>" . format ( language , incflags , filename ) <EOL> ys_contents += """<STR_LIT>""" . format ( build_name = build_name ) <EOL> ys_name = build_name + "<STR_LIT>" <EOL> tools . write_to_file ( ys_name , ys_contents ) <EOL> r = subprocess . call ( [ "<STR_LIT>" , ys_name ] ) <EOL> if r != <NUM_LIT:0> : <EOL> raise OSError ( "<STR_LIT>" ) <EOL> def _run_ise ( build_name , ise_path , source , mode , ngdbuild_opt , <EOL> bitgen_opt , ise_commands , map_opt , par_opt , ver = None ) : <EOL> if sys . platform == "<STR_LIT:win32>" or sys . platform == "<STR_LIT>" : <EOL> source_cmd = "<STR_LIT>" <EOL> script_ext = "<STR_LIT>" <EOL> shell = [ "<STR_LIT>" , "<STR_LIT>" ] <EOL> build_script_contents = "<STR_LIT>" <EOL> fail_stmt = "<STR_LIT>" <EOL> else : <EOL> source_cmd = "<STR_LIT>" <EOL> script_ext = "<STR_LIT>" <EOL> shell = [ "<STR_LIT>" ] <EOL> build_script_contents = "<STR_LIT>" <EOL> fail_stmt = "<STR_LIT>" <EOL> if source : <EOL> settings = common . settings ( ise_path , ver , "<STR_LIT>" ) <EOL> build_script_contents += source_cmd + settings + "<STR_LIT:\n>" <EOL> if mode == "<STR_LIT>" : <EOL> ext = "<STR_LIT>" <EOL> else : <EOL> ext = "<STR_LIT>" <EOL> build_script_contents += """<STR_LIT>""" <EOL> build_script_contents += """<STR_LIT>""" <EOL> build_script_contents = build_script_contents . format ( build_name = build_name , <EOL> ngdbuild_opt = ngdbuild_opt , bitgen_opt = bitgen_opt , ext = ext , <EOL> par_opt = par_opt , map_opt = map_opt , fail_stmt = fail_stmt ) <EOL> build_script_contents += ise_commands . format ( build_name = build_name ) <EOL> build_script_file = "<STR_LIT>" + build_name + script_ext <EOL> tools . write_to_file ( build_script_file , build_script_contents , force_unix = False ) <EOL> command = shell + [ build_script_file ] <EOL> r = subprocess . call ( command ) <EOL> if r != <NUM_LIT:0> : <EOL> raise OSError ( "<STR_LIT>" ) <EOL> class XilinxISEToolchain : <EOL> def __init__ ( self ) : <EOL> self . xst_opt = """<STR_LIT>""" <EOL> self . map_opt = "<STR_LIT>" <EOL> self . par_opt = "<STR_LIT>" <EOL> self . ngdbuild_opt = "<STR_LIT>" <EOL> self . bitgen_opt = "<STR_LIT>" <EOL> self . ise_commands = "<STR_LIT>" <EOL> def build ( self , platform , fragment , build_dir = "<STR_LIT>" , build_name = "<STR_LIT>" , <EOL> toolchain_path = None , source = True , run = True , mode = "<STR_LIT>" ) : <EOL> if not isinstance ( fragment , _Fragment ) : <EOL> fragment = fragment . get_fragment ( ) <EOL> if toolchain_path is None : <EOL> if sys . platform == "<STR_LIT:win32>" : <EOL> toolchain_path = "<STR_LIT>" <EOL> elif sys . platform == "<STR_LIT>" : <EOL> toolchain_path = "<STR_LIT>" <EOL> else : <EOL> toolchain_path = "<STR_LIT>" <EOL> platform . finalize ( fragment ) <EOL> ngdbuild_opt = self . ngdbuild_opt <EOL> vns = None <EOL> tools . mkdir_noerror ( build_dir ) <EOL> cwd = os . getcwd ( ) <EOL> os . chdir ( build_dir ) <EOL> try : <EOL> if mode == "<STR_LIT>" or mode == "<STR_LIT>" : <EOL> v_output = platform . get_verilog ( fragment ) <EOL> vns = v_output . ns <EOL> named_sc , named_pc = platform . resolve_signals ( vns ) <EOL> v_file = build_name + "<STR_LIT>" <EOL> v_output . write ( v_file ) <EOL> sources = platform . sources | { ( v_file , "<STR_LIT>" , "<STR_LIT>" ) } <EOL> if mode == "<STR_LIT>" : <EOL> _build_xst_files ( platform . device , sources , platform . verilog_include_paths , build_name , self . xst_opt ) <EOL> isemode = "<STR_LIT>" <EOL> else : <EOL> _run_yosys ( platform . device , sources , platform . verilog_include_paths , build_name ) <EOL> isemode = "<STR_LIT>" <EOL> ngdbuild_opt += "<STR_LIT>" + platform . device <EOL> if mode == "<STR_LIT>" : <EOL> from mist import synthesize <EOL> synthesize ( fragment , platform . constraint_manager . get_io_signals ( ) ) <EOL> if mode == "<STR_LIT>" or mode == "<STR_LIT>" : <EOL> e_output = platform . get_edif ( fragment ) <EOL> vns = e_output . ns <EOL> named_sc , named_pc = platform . resolve_signals ( vns ) <EOL> e_file = build_name + "<STR_LIT>" <EOL> e_output . write ( e_file ) <EOL> isemode = "<STR_LIT>" <EOL> tools . write_to_file ( build_name + "<STR_LIT>" , _build_ucf ( named_sc , named_pc ) ) <EOL> if run : <EOL> _run_ise ( build_name , toolchain_path , source , isemode , <EOL> ngdbuild_opt , self . bitgen_opt , self . ise_commands , <EOL> self . map_opt , self . par_opt ) <EOL> finally : <EOL> os . chdir ( cwd ) <EOL> return vns <EOL> def add_period_constraint ( self , platform , clk , period ) : <EOL> platform . add_platform_command ( <EOL> """<STR_LIT>""" + str ( period ) + """<STR_LIT>""" , <EOL> clk = clk , <EOL> ) <EOL> def add_false_path_constraint ( self , platform , from_ , to ) : <EOL> platform . add_platform_command ( <EOL> """<STR_LIT>""" , <EOL> from_ = from_ , <EOL> to = to , <EOL> ) </s>
|
<s> from migen . sim . core import Simulator , run_simulation , passive </s>
|
<s> from __future__ import unicode_literals <EOL> from django . db import migrations , models <EOL> class Migration ( migrations . Migration ) : <EOL> dependencies = [ <EOL> ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ] <EOL> operations = [ <EOL> migrations . AddField ( <EOL> model_name = '<STR_LIT>' , <EOL> name = '<STR_LIT>' , <EOL> field = models . CharField ( default = b'<STR_LIT>' , max_length = <NUM_LIT:255> ) , <EOL> ) , <EOL> ] </s>
|
<s> """<STR_LIT>""" <EOL> from operator import attrgetter <EOL> from django . conf import settings <EOL> from . views import get_user_active_repositories <EOL> def base ( request ) : <EOL> """<STR_LIT>""" <EOL> return { <EOL> "<STR_LIT>" : settings . BUILDSERVICE_APP_NAME , <EOL> "<STR_LIT>" : sorted ( <EOL> get_user_active_repositories ( request . user ) , <EOL> key = attrgetter ( '<STR_LIT:name>' ) <EOL> ) <EOL> } </s>
|
<s> import logging ; log = logging . getLogger ( __name__ ) <EOL> from . import BaseAuthenticatedEndpointTestCase , BaseUserlessEndpointTestCase <EOL> class VenuesEndpointTestCase ( BaseAuthenticatedEndpointTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_pages ( self ) : <EOL> response = self . api . pages ( self . default_userid ) <EOL> assert '<STR_LIT:user>' in response <EOL> def test_venues ( self ) : <EOL> response = self . api . pages . venues ( self . default_pageid ) <EOL> assert '<STR_LIT>' in response <EOL> class VenuesUserlessEndpointTestCase ( BaseUserlessEndpointTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_pages ( self ) : <EOL> response = self . api . pages ( self . default_userid ) <EOL> assert '<STR_LIT:user>' in response <EOL> def test_venues ( self ) : <EOL> response = self . api . pages . venues ( self . default_pageid ) <EOL> assert '<STR_LIT>' in response </s>
|
<s> from iepy . data . models import Relation , EntityKind <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> person = EntityKind . objects . get_or_create ( name = "<STR_LIT>" ) [ <NUM_LIT:0> ] <EOL> date = EntityKind . objects . get_or_create ( name = "<STR_LIT>" ) [ <NUM_LIT:0> ] <EOL> Relation . objects . get_or_create ( name = "<STR_LIT>" , left_entity_kind = person , right_entity_kind = date ) </s>
|
<s> import itertools <EOL> import os <EOL> import os . path <EOL> import logging <EOL> from nltk . tag . stanford import NERTagger <EOL> import wget <EOL> from iepy . preprocess . ner . base import BaseNERRunner <EOL> from iepy . utils import DIRS , unzip_file <EOL> logger = logging . getLogger ( __name__ ) <EOL> stanford_ner_name = '<STR_LIT>' <EOL> download_url_base = '<STR_LIT>' <EOL> class NonTokenizingNERTagger ( NERTagger ) : <EOL> @ property <EOL> def _cmd ( self ) : <EOL> old = super ( NonTokenizingNERTagger , self ) . _cmd <EOL> old = old + [ "<STR_LIT>" , "<STR_LIT>" ] <EOL> return old <EOL> class NERRunner ( BaseNERRunner ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , ner , override = False ) : <EOL> super ( NERRunner , self ) . __init__ ( override = override ) <EOL> self . ner = ner <EOL> def run_ner ( self , doc ) : <EOL> entities = [ ] <EOL> ner_sentences = self . ner ( doc . get_sentences ( ) ) <EOL> ner_kinds = ( k for s in ner_sentences for ( _ , k ) in s ) <EOL> z = itertools . chain ( <EOL> enumerate ( zip ( doc . tokens , ner_kinds ) ) , <EOL> [ ( len ( doc . tokens ) , ( None , '<STR_LIT>' ) ) ] <EOL> ) <EOL> last_kind = '<STR_LIT:O>' <EOL> offset = <NUM_LIT:0> <EOL> for i , ( token , kind ) in z : <EOL> if kind != last_kind : <EOL> if last_kind != '<STR_LIT:O>' : <EOL> name = '<STR_LIT:U+0020>' . join ( doc . tokens [ offset : i ] ) <EOL> entities . append ( <EOL> self . build_occurrence ( name , last_kind . lower ( ) , name , offset , i ) <EOL> ) <EOL> offset = i <EOL> last_kind = kind <EOL> try : <EOL> next ( ner_kinds ) <EOL> assert False , "<STR_LIT>" <EOL> except StopIteration : <EOL> pass <EOL> return entities <EOL> class StanfordNERRunner ( NERRunner ) : <EOL> def __init__ ( self , override = False ) : <EOL> ner_path = os . path . join ( DIRS . user_data_dir , stanford_ner_name ) <EOL> if not os . path . exists ( ner_path ) : <EOL> raise LookupError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> ner = NonTokenizingNERTagger ( <EOL> os . path . join ( ner_path , '<STR_LIT>' , '<STR_LIT>' ) , <EOL> os . path . join ( ner_path , '<STR_LIT>' ) , <EOL> encoding = '<STR_LIT:utf8>' ) <EOL> super ( StanfordNERRunner , self ) . __init__ ( ner . tag_sents , override ) <EOL> def download ( ) : <EOL> logger . info ( "<STR_LIT>" ) <EOL> try : <EOL> StanfordNERRunner ( ) <EOL> except LookupError : <EOL> if not os . path . exists ( DIRS . user_data_dir ) : <EOL> os . mkdir ( DIRS . user_data_dir ) <EOL> os . chdir ( DIRS . user_data_dir ) <EOL> package_filename = '<STR_LIT>' . format ( stanford_ner_name ) <EOL> zip_path = os . path . join ( DIRS . user_data_dir , package_filename ) <EOL> wget . download ( download_url_base + package_filename ) <EOL> unzip_file ( zip_path , DIRS . user_data_dir ) <EOL> else : <EOL> logger . info ( "<STR_LIT>" ) </s>
|
<s> from __future__ import unicode_literals <EOL> from django . db import models , migrations <EOL> def create_separated_evidence_labels ( apps , schema_editor ) : <EOL> EvidenceCandidate = apps . get_model ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> EvidenceLabel = apps . get_model ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> for ev in EvidenceCandidate . objects . all ( ) : <EOL> EvidenceLabel . objects . create ( evidence_candidate = ev , <EOL> judge = ev . judge , <EOL> label = ev . label , <EOL> modification_date = ev . modification_date , <EOL> labeled_by_machine = False <EOL> ) <EOL> class Migration ( migrations . Migration ) : <EOL> dependencies = [ <EOL> ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ] <EOL> operations = [ <EOL> migrations . RunPython ( create_separated_evidence_labels ) , <EOL> ] </s>
|
<s> import iepy <EOL> iepy . setup ( _safe_mode = True ) </s>
|
<s> """<STR_LIT>""" <EOL> from quepy . dsl import FixedType , HasKeyword , FixedRelation , FixedDataRelation <EOL> HasKeyword . relation = "<STR_LIT>" <EOL> HasKeyword . language = "<STR_LIT>" <EOL> class IsPerson ( FixedType ) : <EOL> fixedtype = "<STR_LIT>" <EOL> class IsPlace ( FixedType ) : <EOL> fixedtype = "<STR_LIT>" <EOL> class IsCountry ( FixedType ) : <EOL> fixedtype = "<STR_LIT>" <EOL> class IsPopulatedPlace ( FixedType ) : <EOL> fixedtype = "<STR_LIT>" <EOL> class IsBand ( FixedType ) : <EOL> fixedtype = "<STR_LIT>" <EOL> class IsAlbum ( FixedType ) : <EOL> fixedtype = "<STR_LIT>" <EOL> class IsTvShow ( FixedType ) : <EOL> fixedtype = "<STR_LIT>" <EOL> class IsMovie ( FixedType ) : <EOL> fixedtype = "<STR_LIT>" <EOL> class HasShowName ( FixedDataRelation ) : <EOL> relation = "<STR_LIT>" <EOL> language = "<STR_LIT>" <EOL> class HasName ( FixedDataRelation ) : <EOL> relation = "<STR_LIT>" <EOL> language = "<STR_LIT>" <EOL> class DefinitionOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class LabelOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class UTCof ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class PresidentOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class IncumbentOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class CapitalOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class LanguageOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class PopulationOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class IsMemberOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class ActiveYears ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class MusicGenreOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class ProducedBy ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> class BirthDateOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class BirthPlaceOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class ReleaseDateOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class StarsIn ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class NumberOfEpisodesIn ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class ShowNameOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class HasActor ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> class CreatorOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class NameOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class DirectedBy ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> class DirectorOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class DurationOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class HasAuthor ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> class AuthorOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True <EOL> class IsBook ( FixedType ) : <EOL> fixedtype = "<STR_LIT>" <EOL> class LocationOf ( FixedRelation ) : <EOL> relation = "<STR_LIT>" <EOL> reverse = True </s>
|
<s> import refo <EOL> import logging <EOL> from refo import Predicate , Literal , Star , Any , Group <EOL> from quepy . encodingpolicy import encoding_flexible_conversion <EOL> _EOL = None <EOL> logger = logging . getLogger ( "<STR_LIT>" ) <EOL> class BadSemantic ( Exception ) : <EOL> """<STR_LIT>""" <EOL> class WordList ( list ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , words ) : <EOL> super ( WordList , self ) . __init__ ( self ) <EOL> self . extend ( words ) <EOL> @ property <EOL> def tokens ( self ) : <EOL> return "<STR_LIT:U+0020>" . join ( [ x . token for x in self ] ) <EOL> @ property <EOL> def lemmas ( self ) : <EOL> return "<STR_LIT:U+0020>" . join ( [ x . lemma for x in self ] ) <EOL> class Match ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , match , words , i = None , j = None ) : <EOL> assert isinstance ( i , type ( j ) ) <EOL> self . _match = match <EOL> self . _words = words <EOL> self . _i = i <EOL> self . _j = j <EOL> self . _particles = { particle . name : particle for particle in match <EOL> if isinstance ( particle , Particle ) } <EOL> @ property <EOL> def words ( self ) : <EOL> i , j = self . _match . span ( ) <EOL> if self . _i is not None : <EOL> i , j = self . _i , self . _j <EOL> return WordList ( self . _words [ i : j ] ) <EOL> def __getattr__ ( self , attr ) : <EOL> if attr in self . _particles : <EOL> particle = self . _particles [ attr ] <EOL> i , j = self . _match [ particle ] <EOL> self . _check_valid_indexes ( i , j , attr ) <EOL> match = Match ( self . _match , self . _words , i , j ) <EOL> return particle . interpret ( match ) <EOL> try : <EOL> i , j = self . _match [ attr ] <EOL> except KeyError : <EOL> message = "<STR_LIT>" <EOL> raise AttributeError ( message . format ( self . __class__ . __name__ , attr ) ) <EOL> self . _check_valid_indexes ( i , j , attr ) <EOL> return WordList ( self . _words [ i : j ] ) <EOL> def _check_valid_indexes ( self , i , j , attr ) : <EOL> if self . _i is None : <EOL> return <EOL> if i < self . _i or self . _j <= j : <EOL> message = "<STR_LIT>" <EOL> raise AttributeError ( message . format ( self . __class__ . __name__ , attr ) ) <EOL> class QuestionTemplate ( object ) : <EOL> """<STR_LIT>""" <EOL> regex = Star ( Any ( ) ) <EOL> weight = <NUM_LIT:1> <EOL> def interpret ( self , match ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( ) <EOL> def get_interpretation ( self , words ) : <EOL> rulename = self . __class__ . __name__ <EOL> logger . debug ( "<STR_LIT>" . format ( rulename ) ) <EOL> match = refo . match ( self . regex + Literal ( _EOL ) , words + [ _EOL ] ) <EOL> if not match : <EOL> logger . debug ( "<STR_LIT>" ) <EOL> return None , None <EOL> try : <EOL> match = Match ( match , words ) <EOL> result = self . interpret ( match ) <EOL> except BadSemantic as error : <EOL> logger . debug ( str ( error ) ) <EOL> return None , None <EOL> try : <EOL> expression , userdata = result <EOL> except TypeError : <EOL> expression , userdata = result , None <EOL> expression . rule_used = rulename <EOL> return expression , userdata <EOL> class Pos ( Predicate ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , tag ) : <EOL> tag = encoding_flexible_conversion ( tag ) <EOL> self . tag = tag <EOL> super ( Pos , self ) . __init__ ( self . _predicate ) <EOL> self . arg = tag <EOL> def _predicate ( self , word ) : <EOL> return word != _EOL and self . _check ( word ) <EOL> def _check ( self , word ) : <EOL> return word . pos == self . tag <EOL> class Lemma ( Pos ) : <EOL> """<STR_LIT>""" <EOL> def _check ( self , word ) : <EOL> return word . lemma == self . tag <EOL> class Token ( Pos ) : <EOL> """<STR_LIT>""" <EOL> def _check ( self , word ) : <EOL> return word . token == self . tag <EOL> class Particle ( Group ) : <EOL> regex = None <EOL> def __init__ ( self , name = None ) : <EOL> if self . regex is None : <EOL> message = "<STR_LIT>" <EOL> raise NotImplementedError ( message . format ( self . __class__ . __name__ ) ) <EOL> if name is None : <EOL> name = self . __class__ . __name__ . lower ( ) <EOL> self . name = name <EOL> super ( Particle , self ) . __init__ ( self . regex , self ) <EOL> def interpret ( self , match ) : <EOL> message = "<STR_LIT>" <EOL> raise NotImplementedError ( message . format ( self . __class__ . __name__ ) ) <EOL> def __str__ ( self ) : <EOL> return repr ( self ) <EOL> def __repr__ ( self ) : <EOL> cname = self . __class__ . __name__ <EOL> if cname . lower ( ) == self . name : <EOL> return "<STR_LIT>" . format ( cname ) <EOL> else : <EOL> return "<STR_LIT>" . format ( cname , self . name ) <EOL> def _predicate_sum_from_string ( string , predicate ) : <EOL> assert issubclass ( predicate , Predicate ) <EOL> string = encoding_flexible_conversion ( string ) <EOL> words = string . split ( ) <EOL> result = None <EOL> for word in words : <EOL> if result is None : <EOL> result = predicate ( word ) <EOL> else : <EOL> result += predicate ( word ) <EOL> return result <EOL> def Lemmas ( string ) : <EOL> """<STR_LIT>""" <EOL> return _predicate_sum_from_string ( string , Lemma ) <EOL> def Tokens ( string ) : <EOL> """<STR_LIT>""" <EOL> return _predicate_sum_from_string ( string , Token ) <EOL> def Poss ( string ) : <EOL> """<STR_LIT>""" <EOL> return _predicate_sum_from_string ( string , Pos ) </s>
|
<s> import glob <EOL> import os <EOL> import platform <EOL> import subprocess <EOL> import sys <EOL> from setuptools import Command , Extension , setup <EOL> from setuptools . command . test import test as TestCommand <EOL> def define_extensions ( cythonize = False ) : <EOL> compile_args = [ '<STR_LIT>' , <EOL> '<STR_LIT>' ] <EOL> if '<STR_LIT>' not in sys . version . lower ( ) : <EOL> compile_args . append ( '<STR_LIT>' ) <EOL> if cythonize : <EOL> glove_cython = "<STR_LIT>" <EOL> glove_metrics = "<STR_LIT>" <EOL> glove_corpus = "<STR_LIT>" <EOL> else : <EOL> glove_cython = "<STR_LIT>" <EOL> glove_metrics = "<STR_LIT>" <EOL> glove_corpus = "<STR_LIT>" <EOL> return [ Extension ( "<STR_LIT>" , [ glove_cython ] , <EOL> extra_link_args = [ "<STR_LIT>" ] , <EOL> extra_compile_args = compile_args ) , <EOL> Extension ( "<STR_LIT>" , <EOL> [ glove_metrics ] , <EOL> extra_link_args = [ "<STR_LIT>" ] , <EOL> extra_compile_args = compile_args ) , <EOL> Extension ( "<STR_LIT>" , [ glove_corpus ] , <EOL> language = '<STR_LIT>' , <EOL> libraries = [ "<STR_LIT>" ] , <EOL> extra_link_args = compile_args , <EOL> extra_compile_args = compile_args ) ] <EOL> def set_gcc ( ) : <EOL> """<STR_LIT>""" <EOL> patterns = [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] <EOL> if '<STR_LIT>' in platform . platform ( ) . lower ( ) : <EOL> gcc_binaries = [ ] <EOL> for pattern in patterns : <EOL> gcc_binaries += glob . glob ( pattern ) <EOL> gcc_binaries . sort ( ) <EOL> if gcc_binaries : <EOL> _ , gcc = os . path . split ( gcc_binaries [ - <NUM_LIT:1> ] ) <EOL> os . environ [ "<STR_LIT>" ] = gcc <EOL> else : <EOL> raise Exception ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> class Cythonize ( Command ) : <EOL> """<STR_LIT>""" <EOL> user_options = [ ] <EOL> def initialize_options ( self ) : <EOL> pass <EOL> def finalize_options ( self ) : <EOL> pass <EOL> def run ( self ) : <EOL> import Cython <EOL> from Cython . Build import cythonize <EOL> cythonize ( define_extensions ( cythonize = True ) ) <EOL> class Clean ( Command ) : <EOL> """<STR_LIT>""" <EOL> user_options = [ ] <EOL> def initialize_options ( self ) : <EOL> pass <EOL> def finalize_options ( self ) : <EOL> pass <EOL> def run ( self ) : <EOL> pth = os . path . dirname ( os . path . abspath ( __file__ ) ) <EOL> subprocess . call ( [ '<STR_LIT>' , '<STR_LIT>' , os . path . join ( pth , '<STR_LIT>' ) ] ) <EOL> subprocess . call ( [ '<STR_LIT>' , '<STR_LIT>' , os . path . join ( pth , '<STR_LIT>' ) ] ) <EOL> subprocess . call ( [ '<STR_LIT>' , pth , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:f>' , '<STR_LIT>' ] ) <EOL> subprocess . call ( [ '<STR_LIT>' , os . path . join ( pth , '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> subprocess . call ( [ '<STR_LIT>' , os . path . join ( pth , '<STR_LIT>' , '<STR_LIT>' ) ] ) <EOL> class PyTest ( TestCommand ) : <EOL> user_options = [ ( '<STR_LIT>' , '<STR_LIT:a>' , "<STR_LIT>" ) ] <EOL> def initialize_options ( self ) : <EOL> TestCommand . initialize_options ( self ) <EOL> self . pytest_args = [ '<STR_LIT>' ] <EOL> def finalize_options ( self ) : <EOL> TestCommand . finalize_options ( self ) <EOL> self . test_args = [ ] <EOL> self . test_suite = True <EOL> def run_tests ( self ) : <EOL> import pytest <EOL> errno = pytest . main ( self . pytest_args ) <EOL> sys . exit ( errno ) <EOL> setup ( <EOL> name = '<STR_LIT>' , <EOL> version = '<STR_LIT>' , <EOL> description = ( '<STR_LIT>' <EOL> '<STR_LIT>' ) , <EOL> long_description = '<STR_LIT>' , <EOL> packages = [ "<STR_LIT>" ] , <EOL> install_requires = [ '<STR_LIT>' , '<STR_LIT>' ] , <EOL> tests_require = [ '<STR_LIT>' ] , <EOL> cmdclass = { '<STR_LIT:test>' : PyTest , '<STR_LIT>' : Cythonize , '<STR_LIT>' : Clean } , <EOL> author = '<STR_LIT>' , <EOL> url = '<STR_LIT>' , <EOL> download_url = '<STR_LIT>' , <EOL> license = '<STR_LIT>' , <EOL> classifiers = [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] , <EOL> ext_modules = define_extensions ( ) <EOL> ) </s>
|
<s> from django . conf import settings <EOL> from django . core . urlresolvers import reverse <EOL> from django . test import TestCase <EOL> from registration . forms import RegistrationForm <EOL> from registration . users import UserModel <EOL> class SimpleBackendViewTests ( TestCase ) : <EOL> urls = '<STR_LIT>' <EOL> def test_allow ( self ) : <EOL> """<STR_LIT>""" <EOL> old_allowed = getattr ( settings , '<STR_LIT>' , True ) <EOL> settings . REGISTRATION_OPEN = True <EOL> resp = self . client . get ( reverse ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( <NUM_LIT:200> , resp . status_code ) <EOL> settings . REGISTRATION_OPEN = False <EOL> resp = self . client . get ( reverse ( '<STR_LIT>' ) ) <EOL> self . assertRedirects ( resp , reverse ( '<STR_LIT>' ) ) <EOL> resp = self . client . post ( reverse ( '<STR_LIT>' ) , <EOL> data = { '<STR_LIT:username>' : '<STR_LIT>' , <EOL> '<STR_LIT:email>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> self . assertRedirects ( resp , reverse ( '<STR_LIT>' ) ) <EOL> settings . REGISTRATION_OPEN = old_allowed <EOL> def test_registration_get ( self ) : <EOL> """<STR_LIT>""" <EOL> resp = self . client . get ( reverse ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( <NUM_LIT:200> , resp . status_code ) <EOL> self . assertTemplateUsed ( resp , <EOL> '<STR_LIT>' ) <EOL> self . failUnless ( isinstance ( resp . context [ '<STR_LIT>' ] , <EOL> RegistrationForm ) ) <EOL> def test_registration ( self ) : <EOL> """<STR_LIT>""" <EOL> resp = self . client . post ( reverse ( '<STR_LIT>' ) , <EOL> data = { '<STR_LIT:username>' : '<STR_LIT>' , <EOL> '<STR_LIT:email>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> new_user = UserModel ( ) . objects . get ( username = '<STR_LIT>' ) <EOL> self . assertEqual ( <NUM_LIT> , resp . status_code ) <EOL> self . failUnless ( reverse ( '<STR_LIT>' ) in resp [ '<STR_LIT>' ] ) <EOL> self . failUnless ( new_user . check_password ( '<STR_LIT>' ) ) <EOL> self . assertEqual ( new_user . email , '<STR_LIT>' ) <EOL> self . failUnless ( new_user . is_active ) <EOL> resp = self . client . get ( reverse ( '<STR_LIT>' ) ) <EOL> self . failUnless ( resp . context [ '<STR_LIT:user>' ] . is_authenticated ( ) ) <EOL> def test_registration_failure ( self ) : <EOL> """<STR_LIT>""" <EOL> resp = self . client . post ( reverse ( '<STR_LIT>' ) , <EOL> data = { '<STR_LIT:username>' : '<STR_LIT>' , <EOL> '<STR_LIT:email>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> self . assertEqual ( <NUM_LIT:200> , resp . status_code ) <EOL> self . failIf ( resp . context [ '<STR_LIT>' ] . is_valid ( ) ) </s>
|
<s> DEBUG = True <EOL> TEMPLATE_DEBUG = DEBUG <EOL> ADMINS = ( <EOL> ) <EOL> MANAGERS = ADMINS <EOL> DATABASES = { <EOL> '<STR_LIT:default>' : { <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> } <EOL> TIME_ZONE = '<STR_LIT>' <EOL> LANGUAGE_CODE = '<STR_LIT>' <EOL> SITE_ID = <NUM_LIT:1> <EOL> USE_I18N = True <EOL> USE_L10N = True <EOL> MEDIA_ROOT = '<STR_LIT>' <EOL> MEDIA_URL = '<STR_LIT>' <EOL> STATIC_ROOT = '<STR_LIT>' <EOL> STATIC_URL = '<STR_LIT>' <EOL> ADMIN_MEDIA_PREFIX = '<STR_LIT>' <EOL> STATICFILES_DIRS = ( <EOL> ) <EOL> STATICFILES_FINDERS = ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ) <EOL> SECRET_KEY = '<STR_LIT>' <EOL> TEMPLATE_LOADERS = ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ) <EOL> MIDDLEWARE_CLASSES = ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ) <EOL> ROOT_URLCONF = '<STR_LIT>' <EOL> TEMPLATE_DIRS = ( <EOL> ) <EOL> INSTALLED_APPS = ( <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> LOGGING = { <EOL> '<STR_LIT:version>' : <NUM_LIT:1> , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT:class>' : '<STR_LIT>' <EOL> } <EOL> } , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : True , <EOL> } , <EOL> } <EOL> } </s>
|
<s> from __future__ import absolute_import <EOL> import readline <EOL> import glob <EOL> import getpass <EOL> import json <EOL> import os <EOL> from . import util <EOL> def module_exists ( module_name ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> __import__ ( module_name ) <EOL> except ImportError : <EOL> return False <EOL> else : <EOL> return True <EOL> default_config = { <EOL> '<STR_LIT>' : { <EOL> "<STR_LIT:default>" : os . path . expanduser ( "<STR_LIT>" ) <EOL> } , <EOL> '<STR_LIT>' : os . getenv ( '<STR_LIT>' ) or os . getenv ( '<STR_LIT>' ) or "<STR_LIT>" , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : <NUM_LIT:9> , <EOL> '<STR_LIT>' : <NUM_LIT:0> , <EOL> '<STR_LIT>' : "<STR_LIT>" , <EOL> '<STR_LIT>' : '<STR_LIT:@>' , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> } <EOL> def upgrade_config ( config , config_path = os . path . expanduser ( "<STR_LIT>" ) ) : <EOL> """<STR_LIT>""" <EOL> missing_keys = set ( default_config ) . difference ( config ) <EOL> if missing_keys : <EOL> for key in missing_keys : <EOL> config [ key ] = default_config [ key ] <EOL> with open ( config_path , '<STR_LIT:w>' ) as f : <EOL> json . dump ( config , f , indent = <NUM_LIT:2> ) <EOL> print ( "<STR_LIT>" ) <EOL> def save_config ( config = default_config , config_path = os . path . expanduser ( "<STR_LIT>" ) ) : <EOL> with open ( config_path , '<STR_LIT:w>' ) as f : <EOL> json . dump ( config , f , indent = <NUM_LIT:2> ) <EOL> def install_jrnl ( config_path = '<STR_LIT>' ) : <EOL> def autocomplete ( text , state ) : <EOL> expansions = glob . glob ( os . path . expanduser ( os . path . expandvars ( text ) ) + '<STR_LIT:*>' ) <EOL> expansions = [ e + "<STR_LIT:/>" if os . path . isdir ( e ) else e for e in expansions ] <EOL> expansions . append ( None ) <EOL> return expansions [ state ] <EOL> readline . set_completer_delims ( '<STR_LIT>' ) <EOL> readline . parse_and_bind ( "<STR_LIT>" ) <EOL> readline . set_completer ( autocomplete ) <EOL> path_query = '<STR_LIT>' <EOL> journal_path = util . py23_input ( path_query ) . strip ( ) or os . path . expanduser ( '<STR_LIT>' ) <EOL> default_config [ '<STR_LIT>' ] [ '<STR_LIT:default>' ] = os . path . expanduser ( os . path . expandvars ( journal_path ) ) <EOL> if module_exists ( "<STR_LIT>" ) : <EOL> password = getpass . getpass ( "<STR_LIT>" ) <EOL> if password : <EOL> default_config [ '<STR_LIT>' ] = True <EOL> if util . yesno ( "<STR_LIT>" , default = True ) : <EOL> util . set_keychain ( "<STR_LIT:default>" , password ) <EOL> else : <EOL> util . set_keychain ( "<STR_LIT:default>" , None ) <EOL> print ( "<STR_LIT>" ) <EOL> else : <EOL> password = None <EOL> print ( "<STR_LIT>" ) <EOL> path = os . path . split ( default_config [ '<STR_LIT>' ] [ '<STR_LIT:default>' ] ) [ <NUM_LIT:0> ] <EOL> try : <EOL> os . makedirs ( path ) <EOL> except OSError : <EOL> pass <EOL> if not os . path . isdir ( path ) : <EOL> open ( default_config [ '<STR_LIT>' ] [ '<STR_LIT:default>' ] , '<STR_LIT:a>' ) . close ( ) <EOL> with open ( config_path , '<STR_LIT:w>' ) as f : <EOL> json . dump ( default_config , f , indent = <NUM_LIT:2> ) <EOL> config = default_config <EOL> if password : <EOL> config [ '<STR_LIT:password>' ] = password <EOL> return config </s>
|
<s> from django . contrib . auth . models import User <EOL> from django . contrib . contenttypes . models import ContentType <EOL> from django . core . urlresolvers import reverse <EOL> from django . db import IntegrityError , models <EOL> from django . forms . models import inlineformset_factory <EOL> from django . test import TestCase <EOL> from data_exports . templatetags import getter_tags as ttags <EOL> from data_exports . models import Format , Export , Column <EOL> from data_exports . forms import ColumnForm , ColumnFormSet , get_choices <EOL> from inspect_model import InspectModel <EOL> from data_exports . compat import text_type <EOL> class ExportTest ( TestCase ) : <EOL> def setUp ( self ) : <EOL> ct = ContentType . objects . get ( app_label = '<STR_LIT>' , model = '<STR_LIT>' ) <EOL> self . empty_export = Export . objects . create ( name = '<STR_LIT>' , <EOL> slug = '<STR_LIT>' , <EOL> model = ct ) <EOL> self . im = InspectModel ( Export ) <EOL> self . export = Export . objects . create ( name = '<STR_LIT>' , <EOL> slug = '<STR_LIT>' , <EOL> model = ct ) <EOL> for f in self . im . items : <EOL> Column . objects . create ( export = self . export , <EOL> column = f , <EOL> order = <NUM_LIT:0> ) <EOL> user = User . objects . create_user ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> user . is_superuser = True <EOL> user . save ( ) <EOL> def test_slug ( self ) : <EOL> """<STR_LIT>""" <EOL> with self . assertRaises ( IntegrityError ) : <EOL> Export . objects . create ( name = '<STR_LIT:foo>' , <EOL> slug = self . empty_export . slug , <EOL> model = self . empty_export . model ) <EOL> def test_column_choices ( self ) : <EOL> """<STR_LIT>""" <EOL> class OneToOneToExport ( models . Model ) : <EOL> """<STR_LIT>""" <EOL> name = models . CharField ( max_length = <NUM_LIT:50> ) <EOL> o2o = models . OneToOneField ( Export ) <EOL> self . empty_export . _meta . _fill_related_objects_cache ( ) <EOL> self . empty_export . _meta . init_name_map ( ) <EOL> ColumnInlineFormSet = inlineformset_factory ( Export , <EOL> Column , <EOL> form = ColumnForm , <EOL> formset = ColumnFormSet ) <EOL> formset = ColumnInlineFormSet ( instance = self . empty_export ) <EOL> form = formset . forms [ <NUM_LIT:0> ] <EOL> self . assertTrue ( hasattr ( form . fields [ '<STR_LIT>' ] , '<STR_LIT>' ) ) <EOL> choices = form . fields [ '<STR_LIT>' ] . choices <EOL> self . assertTrue ( all ( [ ( i , i ) in choices for i in self . im . items ] ) ) <EOL> im_format = [ '<STR_LIT>' % i <EOL> for i in InspectModel ( Format ) . items ] <EOL> self . assertTrue ( all ( [ ( i , i ) in choices for i in im_format ] ) ) <EOL> im_ct = [ '<STR_LIT>' % i for i in InspectModel ( ContentType ) . items ] <EOL> self . assertTrue ( all ( [ ( i , i ) in choices for i in im_ct ] ) ) <EOL> im_o2o = [ '<STR_LIT>' % i <EOL> for i in InspectModel ( OneToOneToExport ) . items ] <EOL> self . assertTrue ( all ( [ ( i , i ) in choices for i in im_o2o ] ) ) <EOL> del self . empty_export . _meta . _name_map [ '<STR_LIT>' ] <EOL> def test_export_without_format ( self ) : <EOL> """<STR_LIT>""" <EOL> self . client . login ( username = '<STR_LIT>' , password = '<STR_LIT>' ) <EOL> resp = self . client . get ( reverse ( '<STR_LIT>' , <EOL> kwargs = { '<STR_LIT>' : self . empty_export . slug } ) ) <EOL> self . assertContains ( resp , '<STR_LIT>' ) <EOL> resp = self . client . get ( reverse ( '<STR_LIT>' , <EOL> kwargs = { '<STR_LIT>' : self . export . slug } ) ) <EOL> self . assertNotContains ( resp , '<STR_LIT>' ) <EOL> for c in self . export . column_set . all ( ) : <EOL> self . assertContains ( resp , c . label if c . label else c ) <EOL> def test_export_with_format ( self ) : <EOL> """<STR_LIT>""" <EOL> csv_format = Format . objects . create ( <EOL> name = '<STR_LIT>' , <EOL> file_ext = '<STR_LIT>' , <EOL> mime = '<STR_LIT>' , <EOL> template = '<STR_LIT>' ) <EOL> self . client . login ( username = '<STR_LIT>' , password = '<STR_LIT>' ) <EOL> self . export . export_format = csv_format <EOL> self . export . save ( ) <EOL> resp = self . client . get ( reverse ( '<STR_LIT>' , <EOL> kwargs = { '<STR_LIT>' : self . export . slug } ) ) <EOL> self . assertEqual ( resp [ '<STR_LIT:Content-Type>' ] , self . export . export_format . mime ) <EOL> self . assertEqual ( resp [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' % ( <EOL> self . export . slug , <EOL> self . export . export_format . file_ext ) ) <EOL> def test_export_templatetag ( self ) : <EOL> """<STR_LIT>""" <EOL> self . assertEqual ( ttags . getattribute ( self . export , '<STR_LIT>' ) , <EOL> getattr ( self . export , '<STR_LIT>' ) ) <EOL> d = { '<STR_LIT:foo>' : '<STR_LIT:bar>' } <EOL> self . assertEqual ( ttags . getvalue ( d , '<STR_LIT:foo>' ) , d . get ( '<STR_LIT:foo>' ) ) <EOL> column_list = ttags . nice_display ( self . export . column_set ) . split ( '<STR_LIT:U+002CU+0020>' ) <EOL> for c in self . export . column_set . all ( ) : <EOL> self . assertTrue ( text_type ( c ) in column_list ) <EOL> for c , name in get_choices ( Export ) : <EOL> e = ttags . getattribute ( self . export , c ) <EOL> ttags . nice_display ( e ) <EOL> class AdminTest ( TestCase ) : <EOL> def setUp ( self ) : <EOL> user = User . objects . create_user ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> user . is_staff = True <EOL> user . is_superuser = True <EOL> user . save ( ) <EOL> def test_create_export ( self ) : <EOL> self . client . login ( username = '<STR_LIT>' , password = '<STR_LIT>' ) <EOL> ct = ContentType . objects . get ( app_label = '<STR_LIT>' , model = '<STR_LIT>' ) <EOL> resp = self . client . post ( reverse ( '<STR_LIT>' ) , { <EOL> '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : ct . pk , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> self . assertRedirects ( resp , <EOL> reverse ( '<STR_LIT>' , <EOL> args = [ <NUM_LIT:1> ] ) ) <EOL> resp = self . client . get ( reverse ( '<STR_LIT>' , <EOL> args = [ <NUM_LIT:1> ] ) ) <EOL> self . assertContains ( resp , '<STR_LIT>' ) <EOL> self . assertNotContains ( resp , '<STR_LIT>' ) </s>
|
<s> """<STR_LIT>""" <EOL> from __future__ import print_function <EOL> import gc <EOL> import sys <EOL> __all__ = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> def get_all ( type_obj , include_subtypes = True ) : <EOL> """<STR_LIT>""" <EOL> if not isinstance ( type_obj , type ) : <EOL> raise TypeError ( '<STR_LIT>' % type_obj ) <EOL> try : <EOL> type_is_tracked = gc . is_tracked ( type_obj ) <EOL> except AttributeError : <EOL> type_is_tracked = False <EOL> if type_is_tracked : <EOL> to_check = gc . get_referrers ( type_obj ) <EOL> else : <EOL> to_check = gc . get_objects ( ) <EOL> if include_subtypes : <EOL> ret = [ x for x in to_check if isinstance ( x , type_obj ) ] <EOL> else : <EOL> ret = [ x for x in to_check if type ( x ) is type_obj ] <EOL> return ret <EOL> _IS_PYPY = '<STR_LIT>' in sys . builtin_module_names <EOL> if _IS_PYPY : <EOL> del get_all <EOL> class GCToggler ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , postcollect = False ) : <EOL> self . postcollect = postcollect <EOL> def __enter__ ( self ) : <EOL> gc . disable ( ) <EOL> def __exit__ ( self , exc_type , exc_val , exc_tb ) : <EOL> gc . enable ( ) <EOL> if self . postcollect : <EOL> gc . collect ( ) <EOL> toggle_gc = GCToggler ( ) <EOL> """<STR_LIT>""" <EOL> toggle_gc_postcollect = GCToggler ( postcollect = True ) <EOL> """<STR_LIT>""" </s>
|
<s> import pytest <EOL> from boltons . dictutils import OMD <EOL> from boltons . iterutils import ( first , <EOL> remap , <EOL> default_enter , <EOL> default_exit , <EOL> get_path ) <EOL> from boltons . namedutils import namedtuple <EOL> isbool = lambda x : isinstance ( x , bool ) <EOL> isint = lambda x : isinstance ( x , int ) <EOL> odd = lambda x : isint ( x ) and x % <NUM_LIT:2> != <NUM_LIT:0> <EOL> even = lambda x : isint ( x ) and x % <NUM_LIT:2> == <NUM_LIT:0> <EOL> is_meaning_of_life = lambda x : x == <NUM_LIT> <EOL> class TestFirst ( object ) : <EOL> def test_empty_iterables ( self ) : <EOL> """<STR_LIT>""" <EOL> s = set ( ) <EOL> l = [ ] <EOL> assert first ( s ) is None <EOL> assert first ( l ) is None <EOL> def test_default_value ( self ) : <EOL> """<STR_LIT>""" <EOL> s = set ( ) <EOL> l = [ ] <EOL> assert first ( s , default = <NUM_LIT> ) == <NUM_LIT> <EOL> assert first ( l , default = <NUM_LIT> ) == <NUM_LIT> <EOL> l = [ <NUM_LIT:0> , False , [ ] ] <EOL> assert first ( l , default = <NUM_LIT> ) == <NUM_LIT> <EOL> def test_selection ( self ) : <EOL> """<STR_LIT>""" <EOL> l = [ ( ) , <NUM_LIT:0> , False , <NUM_LIT:3> , [ ] ] <EOL> assert first ( l , default = <NUM_LIT> ) == <NUM_LIT:3> <EOL> assert first ( l , key = isint ) == <NUM_LIT:0> <EOL> assert first ( l , key = isbool ) is False <EOL> assert first ( l , key = odd ) == <NUM_LIT:3> <EOL> assert first ( l , key = even ) == <NUM_LIT:0> <EOL> assert first ( l , key = is_meaning_of_life ) is None <EOL> class TestRemap ( object ) : <EOL> def test_basic_clone ( self ) : <EOL> orig = { "<STR_LIT:a>" : "<STR_LIT:b>" , "<STR_LIT:c>" : [ <NUM_LIT:1> , <NUM_LIT:2> ] } <EOL> assert orig == remap ( orig ) <EOL> orig2 = [ { <NUM_LIT:1> : <NUM_LIT:2> } , { "<STR_LIT:a>" : "<STR_LIT:b>" , "<STR_LIT:c>" : [ <NUM_LIT:1> , <NUM_LIT:2> , { "<STR_LIT>" : "<STR_LIT>" } ] } ] <EOL> assert orig2 == remap ( orig2 ) <EOL> def test_empty ( self ) : <EOL> assert [ ] == remap ( [ ] ) <EOL> assert { } == remap ( { } ) <EOL> assert set ( ) == remap ( set ( ) ) <EOL> def test_unremappable ( self ) : <EOL> obj = object ( ) <EOL> with pytest . raises ( TypeError ) : <EOL> remap ( obj ) <EOL> def test_basic_upper ( self ) : <EOL> orig = { '<STR_LIT:a>' : <NUM_LIT:1> , '<STR_LIT:b>' : object ( ) , '<STR_LIT:c>' : { '<STR_LIT:d>' : set ( ) } } <EOL> remapped = remap ( orig , lambda p , k , v : ( k . upper ( ) , v ) ) <EOL> assert orig [ '<STR_LIT:a>' ] == remapped [ '<STR_LIT:A>' ] <EOL> assert orig [ '<STR_LIT:b>' ] == remapped [ '<STR_LIT:B>' ] <EOL> assert orig [ '<STR_LIT:c>' ] [ '<STR_LIT:d>' ] == remapped [ '<STR_LIT:C>' ] [ '<STR_LIT:D>' ] <EOL> def test_item_drop ( self ) : <EOL> orig = [ <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> , <NUM_LIT:5> , <NUM_LIT:6> , <NUM_LIT:7> , <NUM_LIT:8> , <NUM_LIT:9> ] <EOL> even_items = remap ( orig , lambda p , k , v : not ( v % <NUM_LIT:2> ) ) <EOL> assert even_items == [ <NUM_LIT:0> , <NUM_LIT:2> , <NUM_LIT:4> , <NUM_LIT:6> , <NUM_LIT:8> ] <EOL> def test_noncallables ( self ) : <EOL> with pytest . raises ( TypeError ) : <EOL> remap ( [ ] , visit = '<STR_LIT:test>' ) <EOL> with pytest . raises ( TypeError ) : <EOL> remap ( [ ] , enter = '<STR_LIT:test>' ) <EOL> with pytest . raises ( TypeError ) : <EOL> remap ( [ ] , exit = '<STR_LIT:test>' ) <EOL> def test_sub_selfref ( self ) : <EOL> coll = [ <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] <EOL> sub = [ ] <EOL> sub . append ( sub ) <EOL> coll . append ( sub ) <EOL> with pytest . raises ( RuntimeError ) : <EOL> assert coll == remap ( coll ) <EOL> def test_root_selfref ( self ) : <EOL> selfref = [ <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ] <EOL> selfref . append ( selfref ) <EOL> with pytest . raises ( RuntimeError ) : <EOL> assert selfref == remap ( selfref ) <EOL> selfref2 = { } <EOL> selfref2 [ '<STR_LIT>' ] = selfref2 <EOL> with pytest . raises ( RuntimeError ) : <EOL> assert selfref2 == remap ( selfref2 ) <EOL> def test_duperef ( self ) : <EOL> val = [ '<STR_LIT:hello>' ] <EOL> duperef = [ val , val ] <EOL> remapped = remap ( duperef ) <EOL> assert remapped [ <NUM_LIT:0> ] is remapped [ <NUM_LIT:1> ] <EOL> assert remapped [ <NUM_LIT:0> ] is not duperef [ <NUM_LIT:0> ] <EOL> def test_namedtuple ( self ) : <EOL> """<STR_LIT>""" <EOL> Point = namedtuple ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> point_map = { '<STR_LIT>' : [ Point ( <NUM_LIT:0> , <NUM_LIT:0> ) ] } <EOL> with pytest . raises ( TypeError ) : <EOL> remapped = remap ( point_map ) <EOL> assert isinstance ( remapped [ '<STR_LIT>' ] [ <NUM_LIT:0> ] , Point ) <EOL> def test_path ( self ) : <EOL> path_map = { } <EOL> target_str = '<STR_LIT:test>' <EOL> orig = [ [ [ target_str ] ] ] <EOL> ref_path = ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) <EOL> def visit ( path , key , value ) : <EOL> if value is target_str : <EOL> path_map [ '<STR_LIT>' ] = path + ( key , ) <EOL> return key , value <EOL> remapped = remap ( orig , visit = visit ) <EOL> assert remapped == orig <EOL> assert path_map [ '<STR_LIT>' ] == ref_path <EOL> target_obj = object ( ) <EOL> orig = { '<STR_LIT:a>' : { '<STR_LIT:b>' : { '<STR_LIT:c>' : { '<STR_LIT:d>' : [ '<STR_LIT:e>' , target_obj , '<STR_LIT:f>' ] } } } } <EOL> ref_path = ( '<STR_LIT:a>' , '<STR_LIT:b>' , '<STR_LIT:c>' , '<STR_LIT:d>' , <NUM_LIT:1> ) <EOL> def enter ( path , key , value ) : <EOL> if value is target_obj : <EOL> path_map [ '<STR_LIT>' ] = path + ( key , ) <EOL> return default_enter ( path , key , value ) <EOL> remapped = remap ( orig , enter = enter ) <EOL> assert remapped == orig <EOL> assert path_map [ '<STR_LIT>' ] == ref_path <EOL> target_set = frozenset ( [ <NUM_LIT:1> , <NUM_LIT:7> , <NUM_LIT:3> , <NUM_LIT:8> ] ) <EOL> orig = [ <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:2> , [ <NUM_LIT:3> , <NUM_LIT:4> , [ <NUM_LIT:5> , target_set ] ] ] <EOL> ref_path = ( <NUM_LIT:3> , <NUM_LIT:2> , <NUM_LIT:1> ) <EOL> def exit ( path , key , old_parent , new_parent , new_items ) : <EOL> if old_parent is target_set : <EOL> path_map [ '<STR_LIT>' ] = path + ( key , ) <EOL> return default_exit ( path , key , old_parent , new_parent , new_items ) <EOL> remapped = remap ( orig , exit = exit ) <EOL> assert remapped == orig <EOL> assert path_map [ '<STR_LIT>' ] == ref_path <EOL> def test_reraise_visit ( self ) : <EOL> root = { '<STR_LIT:A>' : '<STR_LIT:b>' , <NUM_LIT:1> : <NUM_LIT:2> } <EOL> key_to_lower = lambda p , k , v : ( k . lower ( ) , v ) <EOL> with pytest . raises ( AttributeError ) : <EOL> remap ( root , key_to_lower ) <EOL> remapped = remap ( root , key_to_lower , reraise_visit = False ) <EOL> assert remapped [ '<STR_LIT:a>' ] == '<STR_LIT:b>' <EOL> assert remapped [ <NUM_LIT:1> ] == <NUM_LIT:2> <EOL> def test_drop_nones ( self ) : <EOL> orig = { '<STR_LIT:a>' : <NUM_LIT:1> , '<STR_LIT:b>' : None , '<STR_LIT:c>' : [ <NUM_LIT:3> , None , <NUM_LIT:4> , None ] } <EOL> ref = { '<STR_LIT:a>' : <NUM_LIT:1> , '<STR_LIT:c>' : [ <NUM_LIT:3> , <NUM_LIT:4> ] } <EOL> drop_none = lambda p , k , v : v is not None <EOL> remapped = remap ( orig , visit = drop_none ) <EOL> assert remapped == ref <EOL> orig = [ None ] * <NUM_LIT:100> <EOL> remapped = remap ( orig , drop_none ) <EOL> assert not remapped <EOL> def test_dict_to_omd ( self ) : <EOL> def enter ( path , key , value ) : <EOL> if isinstance ( value , dict ) : <EOL> return OMD ( ) , sorted ( value . items ( ) ) <EOL> return default_enter ( path , key , value ) <EOL> orig = [ { '<STR_LIT:title>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : { <NUM_LIT:1> : <NUM_LIT:1> , <NUM_LIT:2> : <NUM_LIT:3> , <NUM_LIT:3> : <NUM_LIT:5> , <NUM_LIT:4> : <NUM_LIT:6> , <NUM_LIT:5> : <NUM_LIT:3> } } , <EOL> { '<STR_LIT:title>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : { <NUM_LIT:1> : <NUM_LIT:3> , <NUM_LIT:2> : <NUM_LIT:2> , <NUM_LIT:3> : <NUM_LIT:8> , <NUM_LIT:4> : <NUM_LIT:12> , <NUM_LIT:5> : <NUM_LIT:15> } } ] <EOL> remapped = remap ( orig , enter = enter ) <EOL> assert remapped == orig <EOL> assert isinstance ( remapped [ <NUM_LIT:0> ] , OMD ) <EOL> assert isinstance ( remapped [ <NUM_LIT:0> ] [ '<STR_LIT>' ] , OMD ) <EOL> assert isinstance ( remapped [ <NUM_LIT:1> ] , OMD ) <EOL> assert isinstance ( remapped [ <NUM_LIT:1> ] [ '<STR_LIT>' ] , OMD ) <EOL> def test_sort_all_lists ( self ) : <EOL> def exit ( path , key , old_parent , new_parent , new_items ) : <EOL> ret = default_exit ( path , key , old_parent , new_parent , new_items ) <EOL> if isinstance ( ret , list ) : <EOL> ret . sort ( ) <EOL> return ret <EOL> orig = [ [ [ <NUM_LIT:7> , <NUM_LIT:0> , <NUM_LIT:7> ] , <EOL> [ <NUM_LIT:7> , <NUM_LIT:2> , <NUM_LIT:7> ] , <EOL> [ <NUM_LIT:7> , <NUM_LIT:7> , <NUM_LIT:7> ] , <EOL> [ <NUM_LIT:7> , <NUM_LIT:3> , <NUM_LIT:7> ] ] , <EOL> [ [ <NUM_LIT:3> , <NUM_LIT:8> , <NUM_LIT:0> ] , <EOL> [ <NUM_LIT:3> , <NUM_LIT:2> , <NUM_LIT:0> ] , <EOL> [ <NUM_LIT:3> , <NUM_LIT:1> , <NUM_LIT:9> ] , <EOL> [ <NUM_LIT:3> , <NUM_LIT:5> , <NUM_LIT:0> ] ] ] <EOL> ref = [ [ [ <NUM_LIT:0> , <NUM_LIT:2> , <NUM_LIT:3> ] , <EOL> [ <NUM_LIT:0> , <NUM_LIT:3> , <NUM_LIT:5> ] , <EOL> [ <NUM_LIT:0> , <NUM_LIT:3> , <NUM_LIT:8> ] , <EOL> [ <NUM_LIT:1> , <NUM_LIT:3> , <NUM_LIT:9> ] ] , <EOL> [ [ <NUM_LIT:0> , <NUM_LIT:7> , <NUM_LIT:7> ] , <EOL> [ <NUM_LIT:2> , <NUM_LIT:7> , <NUM_LIT:7> ] , <EOL> [ <NUM_LIT:3> , <NUM_LIT:7> , <NUM_LIT:7> ] , <EOL> [ <NUM_LIT:7> , <NUM_LIT:7> , <NUM_LIT:7> ] ] ] <EOL> remapped = remap ( orig , exit = exit ) <EOL> assert remapped == ref <EOL> def test_collector_pattern ( self ) : <EOL> all_interests = set ( ) <EOL> def enter ( path , key , value ) : <EOL> try : <EOL> all_interests . update ( value [ '<STR_LIT>' ] ) <EOL> except : <EOL> pass <EOL> return default_enter ( path , key , value ) <EOL> orig = [ { '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ { '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] } ] } , <EOL> { '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ { '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] } ] } ] <EOL> ref = set ( [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> remap ( orig , enter = enter ) <EOL> assert all_interests == ref <EOL> def test_add_length ( self ) : <EOL> def exit ( path , key , old_parent , new_parent , new_items ) : <EOL> ret = default_exit ( path , key , old_parent , new_parent , new_items ) <EOL> try : <EOL> ret [ '<STR_LIT>' ] = len ( ret [ '<STR_LIT>' ] ) <EOL> except : <EOL> pass <EOL> return ret <EOL> orig = { '<STR_LIT>' : <EOL> { '<STR_LIT>' : { '<STR_LIT>' : <NUM_LIT:10> , <EOL> '<STR_LIT>' : "<STR_LIT>" } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : "<STR_LIT>" } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : None , <EOL> '<STR_LIT>' : "<STR_LIT>" } } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : <NUM_LIT:6> , <EOL> '<STR_LIT>' : "<STR_LIT>" } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : None , <EOL> '<STR_LIT>' : "<STR_LIT>" } } <EOL> remapped = remap ( orig , exit = exit ) <EOL> assert ( remapped [ '<STR_LIT>' ] [ '<STR_LIT>' ] [ '<STR_LIT>' ] <EOL> < remapped [ '<STR_LIT>' ] [ '<STR_LIT>' ] [ '<STR_LIT>' ] ) <EOL> def test_prepop ( self ) : <EOL> """<STR_LIT>""" <EOL> base_obj = { '<STR_LIT:name>' : None , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT:id>' : <NUM_LIT:1> } <EOL> def enter ( path , key , value ) : <EOL> new_parent , new_items = default_enter ( path , key , value ) <EOL> try : <EOL> new_parent . update ( base_obj ) <EOL> base_obj [ '<STR_LIT:id>' ] += <NUM_LIT:1> <EOL> except : <EOL> pass <EOL> return new_parent , new_items <EOL> orig = [ { '<STR_LIT:name>' : '<STR_LIT>' , '<STR_LIT>' : <NUM_LIT:1> } , <EOL> { '<STR_LIT:name>' : '<STR_LIT>' , '<STR_LIT>' : <NUM_LIT:2> } , <EOL> { '<STR_LIT:name>' : '<STR_LIT>' } ] <EOL> ref = [ { '<STR_LIT:name>' : '<STR_LIT>' , '<STR_LIT>' : <NUM_LIT:1> , '<STR_LIT:id>' : <NUM_LIT:1> } , <EOL> { '<STR_LIT:name>' : '<STR_LIT>' , '<STR_LIT>' : <NUM_LIT:2> , '<STR_LIT:id>' : <NUM_LIT:2> } , <EOL> { '<STR_LIT:name>' : '<STR_LIT>' , '<STR_LIT>' : None , '<STR_LIT:id>' : <NUM_LIT:3> } ] <EOL> remapped = remap ( orig , enter = enter ) <EOL> assert remapped == ref <EOL> class TestGetPath ( object ) : <EOL> def test_depth_one ( self ) : <EOL> root = [ '<STR_LIT:test>' ] <EOL> assert get_path ( root , ( <NUM_LIT:0> , ) ) == '<STR_LIT:test>' <EOL> assert get_path ( root , '<STR_LIT:0>' ) == '<STR_LIT:test>' <EOL> root = { '<STR_LIT:key>' : '<STR_LIT:value>' } <EOL> assert get_path ( root , ( '<STR_LIT:key>' , ) ) == '<STR_LIT:value>' <EOL> assert get_path ( root , '<STR_LIT:key>' ) == '<STR_LIT:value>' <EOL> def test_depth_two ( self ) : <EOL> root = { '<STR_LIT:key>' : [ '<STR_LIT:test>' ] } <EOL> assert get_path ( root , ( '<STR_LIT:key>' , <NUM_LIT:0> ) ) == '<STR_LIT:test>' <EOL> assert get_path ( root , '<STR_LIT>' ) == '<STR_LIT:test>' <EOL> def test_backoff_basic ( ) : <EOL> from boltons . iterutils import backoff <EOL> assert backoff ( <NUM_LIT:1> , <NUM_LIT:16> ) == [ <NUM_LIT:1.0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> assert backoff ( <NUM_LIT:1> , <NUM_LIT:1> ) == [ <NUM_LIT:1.0> ] <EOL> assert backoff ( <NUM_LIT:2> , <NUM_LIT:15> ) == [ <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> def test_backoff_repeat ( ) : <EOL> from boltons . iterutils import backoff_iter <EOL> fives = [ ] <EOL> for val in backoff_iter ( <NUM_LIT:5> , <NUM_LIT:5> , count = '<STR_LIT>' ) : <EOL> fives . append ( val ) <EOL> if len ( fives ) >= <NUM_LIT:1000> : <EOL> break <EOL> assert fives == [ <NUM_LIT:5> ] * <NUM_LIT:1000> <EOL> def test_backoff_zero_start ( ) : <EOL> from boltons . iterutils import backoff <EOL> assert backoff ( <NUM_LIT:0> , <NUM_LIT:16> ) == [ <NUM_LIT:0.0> , <NUM_LIT:1.0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> assert backoff ( <NUM_LIT:0> , <NUM_LIT:15> ) == [ <NUM_LIT:0.0> , <NUM_LIT:1.0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> slow_backoff = [ round ( x , <NUM_LIT:2> ) for x in backoff ( <NUM_LIT:0> , <NUM_LIT> , factor = <NUM_LIT> ) ] <EOL> assert slow_backoff == [ <NUM_LIT:0.0> , <NUM_LIT:1.0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> def test_backoff_validation ( ) : <EOL> from boltons . iterutils import backoff <EOL> with pytest . raises ( ValueError ) : <EOL> backoff ( <NUM_LIT:8> , <NUM_LIT:2> ) <EOL> with pytest . raises ( ValueError ) : <EOL> backoff ( <NUM_LIT:1> , <NUM_LIT:0> ) <EOL> with pytest . raises ( ValueError ) : <EOL> backoff ( - <NUM_LIT:1> , <NUM_LIT:10> ) <EOL> with pytest . raises ( ValueError ) : <EOL> backoff ( <NUM_LIT:2> , <NUM_LIT:8> , factor = <NUM_LIT:0> ) <EOL> with pytest . raises ( ValueError ) : <EOL> backoff ( <NUM_LIT:2> , <NUM_LIT:8> , jitter = <NUM_LIT:20> ) <EOL> def test_backoff_jitter ( ) : <EOL> from boltons . iterutils import backoff <EOL> start , stop = <NUM_LIT:1> , <NUM_LIT> <EOL> unjittered = backoff ( start , stop ) <EOL> jittered = backoff ( start , stop , jitter = True ) <EOL> assert len ( unjittered ) == len ( jittered ) <EOL> assert [ u >= j for u , j in zip ( unjittered , jittered ) ] <EOL> neg_jittered = backoff ( start , stop , jitter = - <NUM_LIT> ) <EOL> assert len ( unjittered ) == len ( neg_jittered ) <EOL> assert [ u <= j for u , j in zip ( unjittered , neg_jittered ) ] <EOL> o_jittered = backoff ( start , stop , jitter = - <NUM_LIT:0.0> ) <EOL> assert len ( unjittered ) == len ( o_jittered ) <EOL> assert [ u == j for u , j in zip ( unjittered , o_jittered ) ] <EOL> nonconst_jittered = backoff ( stop , stop , count = <NUM_LIT:5> , jitter = True ) <EOL> assert len ( nonconst_jittered ) == <NUM_LIT:5> <EOL> assert len ( set ( nonconst_jittered ) ) == <NUM_LIT:5> </s>
|
<s> import itertools <EOL> from collections import defaultdict <EOL> from werkzeug . utils import cached_property <EOL> from werkzeug . wrappers import BaseResponse <EOL> from . . sinter import make_chain , get_arg_names , _VERBOSE <EOL> class Middleware ( object ) : <EOL> unique = True <EOL> reorderable = True <EOL> provides = ( ) <EOL> endpoint_provides = ( ) <EOL> render_provides = ( ) <EOL> request = None <EOL> endpoint = None <EOL> render = None <EOL> @ property <EOL> def name ( self ) : <EOL> return self . __class__ . __name__ <EOL> def __eq__ ( self , other ) : <EOL> return type ( self ) == type ( other ) <EOL> def __ne__ ( self , other ) : <EOL> return type ( self ) != type ( other ) <EOL> @ cached_property <EOL> def requires ( self ) : <EOL> reqs = [ ] <EOL> for func_name in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> func = getattr ( self , func_name , None ) <EOL> if func : <EOL> reqs . extend ( get_arg_names ( func , True ) ) <EOL> unique_reqs = set ( reqs ) <EOL> unique_reqs . discard ( '<STR_LIT>' ) <EOL> return list ( unique_reqs ) <EOL> @ cached_property <EOL> def arguments ( self ) : <EOL> args = [ ] <EOL> for func_name in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> func = getattr ( self , func_name , None ) <EOL> if func : <EOL> args . extend ( get_arg_names ( func ) ) <EOL> return set ( args ) <EOL> def check_middleware ( mw ) : <EOL> for f_name in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> func = getattr ( mw , f_name , None ) <EOL> if not func : <EOL> continue <EOL> if not callable ( func ) : <EOL> raise TypeError ( '<STR_LIT>' <EOL> % ( mw . name , f_name ) ) <EOL> if not get_arg_names ( func ) [ <NUM_LIT:0> ] == '<STR_LIT>' : <EOL> raise TypeError ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> % ( mw . name , f_name ) ) <EOL> def check_middlewares ( middlewares , args_dict = None ) : <EOL> args_dict = args_dict or { } <EOL> provided_by = defaultdict ( list ) <EOL> for source , arg_list in args_dict . items ( ) : <EOL> for arg_name in arg_list : <EOL> provided_by [ arg_name ] . append ( source ) <EOL> for mw in middlewares : <EOL> check_middleware ( mw ) <EOL> for arg in mw . provides : <EOL> provided_by [ arg ] . append ( mw ) <EOL> for arg in mw . endpoint_provides : <EOL> provided_by [ arg ] . append ( mw ) <EOL> for arg in mw . render_provides : <EOL> provided_by [ arg ] . append ( mw ) <EOL> conflicts = [ ( n , tuple ( ps ) ) for ( n , ps ) in <EOL> provided_by . items ( ) if len ( ps ) > <NUM_LIT:1> ] <EOL> if conflicts : <EOL> raise NameError ( '<STR_LIT>' % conflicts ) <EOL> return True <EOL> def merge_middlewares ( old , new ) : <EOL> old = list ( old ) <EOL> merged = list ( new ) <EOL> for mw in old : <EOL> if mw . unique and mw in merged : <EOL> if mw . reorderable : <EOL> continue <EOL> else : <EOL> raise ValueError ( '<STR_LIT>' <EOL> '<STR_LIT>' % mw . name ) <EOL> merged . append ( mw ) <EOL> return merged <EOL> class DummyMiddleware ( Middleware ) : <EOL> def __init__ ( self , verbose = False ) : <EOL> self . verbose = verbose <EOL> def request ( self , next , request ) : <EOL> name = '<STR_LIT>' % ( self . __class__ . __name__ , id ( self ) ) <EOL> if self . verbose : <EOL> print name , '<STR_LIT>' , id ( request ) <EOL> try : <EOL> ret = next ( ) <EOL> except Exception as e : <EOL> if self . verbose : <EOL> print name , '<STR_LIT>' , repr ( e ) <EOL> raise <EOL> if self . verbose : <EOL> print name , '<STR_LIT>' , repr ( ret ) <EOL> return ret <EOL> def make_middleware_chain ( middlewares , endpoint , render , preprovided ) : <EOL> """<STR_LIT>""" <EOL> _next_exc_msg = "<STR_LIT>" <EOL> if '<STR_LIT>' in get_arg_names ( endpoint ) : <EOL> raise NameError ( _next_exc_msg % endpoint ) <EOL> if '<STR_LIT>' in get_arg_names ( render ) : <EOL> raise NameError ( _next_exc_msg % render ) <EOL> req_avail = set ( preprovided ) - set ( [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> req_sigs = [ ( mw . request , mw . provides ) <EOL> for mw in middlewares if mw . request ] <EOL> req_funcs , req_provides = zip ( * req_sigs ) or ( ( ) , ( ) ) <EOL> req_all_provides = set ( itertools . chain . from_iterable ( req_provides ) ) <EOL> ep_avail = req_avail | req_all_provides <EOL> ep_sigs = [ ( mw . endpoint , mw . endpoint_provides ) <EOL> for mw in middlewares if mw . endpoint ] <EOL> ep_funcs , ep_provides = zip ( * ep_sigs ) or ( ( ) , ( ) ) <EOL> ep_chain , ep_args , ep_unres = make_chain ( ep_funcs , <EOL> ep_provides , <EOL> endpoint , <EOL> ep_avail ) <EOL> if ep_unres : <EOL> raise NameError ( "<STR_LIT>" <EOL> % list ( ep_unres ) ) <EOL> rn_avail = ep_avail | set ( [ '<STR_LIT>' ] ) <EOL> rn_sigs = [ ( mw . render , mw . render_provides ) <EOL> for mw in middlewares if mw . render ] <EOL> rn_funcs , rn_provides = zip ( * rn_sigs ) or ( ( ) , ( ) ) <EOL> rn_chain , rn_args , rn_unres = make_chain ( rn_funcs , <EOL> rn_provides , <EOL> render , <EOL> rn_avail ) <EOL> if rn_unres : <EOL> raise NameError ( "<STR_LIT>" <EOL> % list ( rn_unres ) ) <EOL> req_args = ( ep_args | rn_args ) - set ( [ '<STR_LIT>' ] ) <EOL> req_func = _create_request_inner ( ep_chain , <EOL> rn_chain , <EOL> req_args , <EOL> ep_args , <EOL> rn_args ) <EOL> req_chain , req_chain_args , req_unres = make_chain ( req_funcs , <EOL> req_provides , <EOL> req_func , <EOL> req_avail ) <EOL> if req_unres : <EOL> raise NameError ( "<STR_LIT>" <EOL> % list ( req_unres ) ) <EOL> return req_chain <EOL> _REQ_INNER_TMPL = '''<STR_LIT>''' <EOL> def _named_arg_str ( args ) : <EOL> return '<STR_LIT:U+002CU+0020>' . join ( [ a + '<STR_LIT:=>' + a for a in args ] ) <EOL> def _create_request_inner ( endpoint , render , all_args , <EOL> endpoint_args , render_args , <EOL> verbose = _VERBOSE ) : <EOL> all_args_str = '<STR_LIT:U+002C>' . join ( all_args ) <EOL> ep_args_str = _named_arg_str ( endpoint_args ) <EOL> rn_args_str = _named_arg_str ( render_args ) <EOL> code_str = _REQ_INNER_TMPL . format ( all_args = all_args_str , <EOL> endpoint_args = ep_args_str , <EOL> render_args = rn_args_str ) <EOL> if verbose : <EOL> print code_str <EOL> d = { '<STR_LIT>' : endpoint , '<STR_LIT>' : render , '<STR_LIT>' : BaseResponse } <EOL> exec compile ( code_str , '<STR_LIT>' , '<STR_LIT>' ) in d <EOL> return d [ '<STR_LIT>' ] </s>
|
<s> from __future__ import unicode_literals <EOL> import os <EOL> from nose . tools import eq_ , ok_ <EOL> from werkzeug . test import Client <EOL> from werkzeug . wrappers import BaseResponse <EOL> from clastic import Application <EOL> from clastic . render import ( JSONRender , <EOL> JSONPRender , <EOL> render_basic , <EOL> BasicRender , <EOL> Table , <EOL> TabularRender ) <EOL> from common import ( hello_world_str , <EOL> hello_world_html , <EOL> hello_world_ctx , <EOL> complex_context ) <EOL> import json <EOL> _CUR_DIR = os . path . dirname ( __file__ ) <EOL> def test_json_render ( render_json = None ) : <EOL> if render_json is None : <EOL> render_json = JSONRender ( dev_mode = True ) <EOL> app = Application ( [ ( '<STR_LIT:/>' , hello_world_ctx , render_json ) , <EOL> ( '<STR_LIT>' , hello_world_ctx , render_json ) , <EOL> ( '<STR_LIT>' , complex_context , render_json ) ] ) <EOL> yield ok_ , callable ( app . routes [ <NUM_LIT:0> ] . _execute ) <EOL> yield ok_ , callable ( app . routes [ <NUM_LIT:0> ] . _render ) <EOL> c = Client ( app , BaseResponse ) <EOL> resp = c . get ( '<STR_LIT:/>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> resp_data = json . loads ( resp . data ) <EOL> yield eq_ , resp_data [ '<STR_LIT:name>' ] , '<STR_LIT>' <EOL> resp = c . get ( '<STR_LIT>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> resp_data = json . loads ( resp . data ) <EOL> yield eq_ , resp_data [ '<STR_LIT:name>' ] , '<STR_LIT>' <EOL> resp = c . get ( '<STR_LIT>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> resp_data = json . loads ( resp . data ) <EOL> yield eq_ , resp_data [ '<STR_LIT:name>' ] , '<STR_LIT>' <EOL> yield ok_ , resp_data [ '<STR_LIT:date>' ] <EOL> yield ok_ , len ( resp_data ) > <NUM_LIT:4> <EOL> def test_jsonp_render ( render_json = None ) : <EOL> if render_json is None : <EOL> render_json = JSONPRender ( qp_name = '<STR_LIT>' , dev_mode = True ) <EOL> app = Application ( [ ( '<STR_LIT:/>' , hello_world_ctx , render_json ) , <EOL> ( '<STR_LIT>' , hello_world_ctx , render_json ) , <EOL> ( '<STR_LIT>' , complex_context , render_json ) ] ) <EOL> c = Client ( app , BaseResponse ) <EOL> resp = c . get ( '<STR_LIT>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> yield ok_ , resp . data . startswith ( '<STR_LIT>' ) <EOL> yield ok_ , '<STR_LIT>' in resp . data <EOL> resp = c . get ( '<STR_LIT>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> yield ok_ , resp . data . startswith ( '<STR_LIT>' ) <EOL> yield ok_ , '<STR_LIT>' in resp . data <EOL> def test_default_render ( ) : <EOL> app = Application ( [ ( '<STR_LIT:/>' , hello_world_ctx , render_basic ) , <EOL> ( '<STR_LIT>' , hello_world_ctx , render_basic ) , <EOL> ( '<STR_LIT>' , hello_world_str , render_basic ) , <EOL> ( '<STR_LIT>' , hello_world_html , render_basic ) , <EOL> ( '<STR_LIT>' , complex_context , render_basic ) ] ) <EOL> yield ok_ , callable ( app . routes [ <NUM_LIT:0> ] . _execute ) <EOL> yield ok_ , callable ( app . routes [ <NUM_LIT:0> ] . _render ) <EOL> c = Client ( app , BaseResponse ) <EOL> resp = c . get ( '<STR_LIT:/>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> resp_data = json . loads ( resp . data ) <EOL> yield eq_ , resp_data [ '<STR_LIT:name>' ] , '<STR_LIT>' <EOL> resp = c . get ( '<STR_LIT>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> resp_data = json . loads ( resp . data ) <EOL> yield eq_ , resp_data [ '<STR_LIT:name>' ] , '<STR_LIT>' <EOL> resp = c . get ( '<STR_LIT>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> resp_data = json . loads ( resp . data ) <EOL> yield eq_ , resp_data [ '<STR_LIT:name>' ] , '<STR_LIT>' <EOL> yield ok_ , resp_data [ '<STR_LIT:date>' ] <EOL> yield ok_ , len ( resp_data ) > <NUM_LIT:4> <EOL> resp = c . get ( '<STR_LIT>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> yield eq_ , resp . data , '<STR_LIT>' <EOL> resp = c . get ( '<STR_LIT>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> yield ok_ , '<STR_LIT>' in resp . headers [ '<STR_LIT:Content-Type>' ] <EOL> def test_custom_table_render ( ) : <EOL> class BoldHTMLTable ( Table ) : <EOL> def get_cell_html ( self , value ) : <EOL> std_html = super ( BoldHTMLTable , self ) . get_cell_html ( value ) <EOL> return '<STR_LIT>' + std_html + '<STR_LIT>' <EOL> custom_tr = TabularRender ( table_type = BoldHTMLTable ) <EOL> custom_render = BasicRender ( tabular_render = custom_tr ) <EOL> app = Application ( [ ( '<STR_LIT:/>' , hello_world_ctx , custom_render ) ] ) <EOL> c = Client ( app , BaseResponse ) <EOL> resp = c . get ( '<STR_LIT>' ) <EOL> yield eq_ , resp . status_code , <NUM_LIT:200> <EOL> assert '<STR_LIT>' in resp . data </s>
|
<s> """<STR_LIT>""" <EOL> import difflib <EOL> def suggest ( word , cutoff = <NUM_LIT> ) : <EOL> """<STR_LIT>""" <EOL> if word in LOOKUP_TABLE : <EOL> return LOOKUP_TABLE [ word ] <EOL> guess = difflib . get_close_matches ( word , MOST_COMMON_DOMAINS , n = <NUM_LIT:1> , cutoff = cutoff ) <EOL> if guess and len ( guess ) > <NUM_LIT:0> : <EOL> return guess [ <NUM_LIT:0> ] <EOL> return word <EOL> MOST_COMMON_DOMAINS = [ <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> '<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> '<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> '<STR_LIT>' <EOL> ] <EOL> LOOKUP_TABLE = { <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' , <EOL> u'<STR_LIT>' : u'<STR_LIT>' <EOL> } </s>
|
<s> """<STR_LIT>""" <EOL> import urllib <EOL> import regex as re <EOL> from flanker . mime . message . headers import encodedword <EOL> from flanker . mime . message import charsets <EOL> from collections import deque <EOL> from itertools import groupby <EOL> def decode ( header ) : <EOL> """<STR_LIT>""" <EOL> value , rest = split ( encodedword . unfold ( header ) ) <EOL> if value is None : <EOL> return None , { } <EOL> elif value : <EOL> return value , decode_parameters ( rest ) <EOL> def is_parametrized ( name , value ) : <EOL> return name in ( "<STR_LIT:Content-Type>" , "<STR_LIT>" , <EOL> "<STR_LIT>" ) <EOL> def fix_content_type ( value , default = None ) : <EOL> """<STR_LIT>""" <EOL> if not value : <EOL> return default or ( '<STR_LIT:text>' , '<STR_LIT>' ) <EOL> values = value . lower ( ) . split ( "<STR_LIT:/>" ) <EOL> if len ( values ) >= <NUM_LIT:2> : <EOL> return values [ : <NUM_LIT:2> ] <EOL> elif len ( values ) == <NUM_LIT:1> : <EOL> if values [ <NUM_LIT:0> ] == '<STR_LIT:text>' : <EOL> return '<STR_LIT:text>' , '<STR_LIT>' <EOL> elif values [ <NUM_LIT:0> ] == '<STR_LIT:html>' : <EOL> return '<STR_LIT:text>' , '<STR_LIT:html>' <EOL> return '<STR_LIT>' , '<STR_LIT>' <EOL> def split ( header ) : <EOL> """<STR_LIT>""" <EOL> match = headerValue . match ( header ) <EOL> if not match : <EOL> return ( None , None ) <EOL> return match . group ( <NUM_LIT:1> ) . lower ( ) , header [ match . end ( ) : ] <EOL> def decode_parameters ( string ) : <EOL> """<STR_LIT>""" <EOL> parameters = collect_parameters ( string ) <EOL> groups = { } <EOL> for k , parts in groupby ( parameters , get_key ) : <EOL> groups [ k ] = concatenate ( list ( parts ) ) <EOL> return groups <EOL> def collect_parameters ( rest ) : <EOL> """<STR_LIT>""" <EOL> parameters = deque ( ) <EOL> p , rest = match_parameter ( rest ) <EOL> while p : <EOL> parameters . append ( p ) <EOL> p , rest = match_parameter ( rest ) <EOL> return parameters <EOL> def concatenate ( parts ) : <EOL> """<STR_LIT>""" <EOL> part = parts [ <NUM_LIT:0> ] <EOL> if is_old_style ( part ) : <EOL> return encodedword . mime_to_unicode ( get_value ( part ) ) <EOL> else : <EOL> return u"<STR_LIT>" . join ( <EOL> decode_new_style ( p ) for p in partition ( parts ) ) <EOL> def match_parameter ( rest ) : <EOL> for match in ( match_old , match_new ) : <EOL> p , rest = match ( rest ) <EOL> if p : <EOL> return p , rest <EOL> return ( None , rest ) <EOL> def match_old ( rest ) : <EOL> match = oldStyleParameter . match ( rest ) <EOL> if match : <EOL> name = match . group ( '<STR_LIT:name>' ) <EOL> value = match . group ( '<STR_LIT:value>' ) <EOL> return parameter ( '<STR_LIT>' , name , value ) , rest [ match . end ( ) : ] <EOL> else : <EOL> return None , rest <EOL> def match_new ( rest ) : <EOL> match = newStyleParameter . match ( rest ) <EOL> if match : <EOL> name = parse_parameter_name ( match . group ( '<STR_LIT:name>' ) ) <EOL> value = match . group ( '<STR_LIT:value>' ) <EOL> return parameter ( '<STR_LIT>' , name , value ) , rest [ match . end ( ) : ] <EOL> else : <EOL> return ( None , rest ) <EOL> def reverse ( string ) : <EOL> """<STR_LIT>""" <EOL> return string [ : : - <NUM_LIT:1> ] <EOL> def parse_parameter_name ( key ) : <EOL> """<STR_LIT>""" <EOL> m = reverseContinuation . match ( reverse ( key ) ) <EOL> key = reverse ( m . group ( '<STR_LIT:key>' ) ) <EOL> part = reverse ( m . group ( '<STR_LIT>' ) ) if m . group ( '<STR_LIT>' ) else None <EOL> encoded = m . group ( '<STR_LIT>' ) <EOL> return ( key , part , encoded ) <EOL> def decode_new_style ( parameter ) : <EOL> """<STR_LIT>""" <EOL> if is_quoted ( parameter ) : <EOL> return unquote ( parameter ) <EOL> if is_encoded ( parameter ) : <EOL> return decode_charset ( parameter ) <EOL> return get_value ( parameter ) <EOL> def partition ( parts ) : <EOL> """<STR_LIT>""" <EOL> encoded = deque ( ) <EOL> for part in parts : <EOL> if is_encoded ( part ) : <EOL> encoded . append ( part ) <EOL> continue <EOL> if encoded : <EOL> yield join_parameters ( encoded ) <EOL> encoded = deque ( ) <EOL> yield part <EOL> if encoded : <EOL> yield join_parameters ( encoded ) <EOL> def decode_charset ( parameter ) : <EOL> """<STR_LIT>""" <EOL> v = get_value ( parameter ) <EOL> parts = v . split ( "<STR_LIT:'>" , <NUM_LIT:2> ) <EOL> if len ( parts ) != <NUM_LIT:3> : <EOL> return v <EOL> charset , language , val = parts <EOL> val = urllib . unquote ( val ) <EOL> return charsets . convert_to_unicode ( charset , val ) <EOL> def unquote ( parameter ) : <EOL> """<STR_LIT>""" <EOL> return get_value ( parameter ) . strip ( '<STR_LIT:">' ) <EOL> def parameter ( ptype , key , value ) : <EOL> """<STR_LIT>""" <EOL> return ( ptype , key , value ) <EOL> def is_quoted ( part ) : <EOL> return get_value ( part ) [ <NUM_LIT:0> ] == '<STR_LIT:">' <EOL> def is_new_style ( parameter ) : <EOL> return parameter [ <NUM_LIT:0> ] == '<STR_LIT>' <EOL> def is_old_style ( parameter ) : <EOL> return parameter [ <NUM_LIT:0> ] == '<STR_LIT>' <EOL> def is_encoded ( part ) : <EOL> return part [ <NUM_LIT:1> ] [ <NUM_LIT:2> ] == '<STR_LIT:*>' <EOL> def get_key ( parameter ) : <EOL> if is_old_style ( parameter ) : <EOL> return parameter [ <NUM_LIT:1> ] . lower ( ) <EOL> else : <EOL> return parameter [ <NUM_LIT:1> ] [ <NUM_LIT:0> ] . lower ( ) <EOL> def get_value ( parameter ) : <EOL> return parameter [ <NUM_LIT:2> ] <EOL> def join_parameters ( parts ) : <EOL> joined = "<STR_LIT>" . join ( get_value ( p ) for p in parts ) <EOL> for p in parts : <EOL> return parameter ( p [ <NUM_LIT:0> ] , p [ <NUM_LIT:1> ] , joined ) <EOL> headerValue = re . compile ( r"""<STR_LIT>""" , re . IGNORECASE | re . VERBOSE ) <EOL> oldStyleParameter = re . compile ( r"""<STR_LIT>""" , re . IGNORECASE | re . VERBOSE ) <EOL> newStyleParameter = re . compile ( r"""<STR_LIT>""" , re . IGNORECASE | re . VERBOSE ) <EOL> reverseContinuation = re . compile ( <EOL> "<STR_LIT>" ) </s>
|
<s> from __future__ import unicode_literals <EOL> from django . db import migrations , models <EOL> class Migration ( migrations . Migration ) : <EOL> dependencies = [ <EOL> ] <EOL> operations = [ <EOL> migrations . CreateModel ( <EOL> name = '<STR_LIT>' , <EOL> fields = [ <EOL> ( '<STR_LIT:id>' , models . AutoField ( verbose_name = '<STR_LIT>' , serialize = False , auto_created = True , primary_key = True ) ) , <EOL> ( '<STR_LIT>' , models . CharField ( max_length = <NUM_LIT:100> ) ) , <EOL> ( '<STR_LIT>' , models . CharField ( max_length = <NUM_LIT:100> ) ) , <EOL> ( '<STR_LIT>' , models . CharField ( max_length = <NUM_LIT:32> ) ) , <EOL> ] , <EOL> ) , <EOL> ] </s>
|
<s> from video import app <EOL> import os <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> port = int ( os . environ . get ( "<STR_LIT>" , <NUM_LIT> ) ) <EOL> if port == <NUM_LIT> : <EOL> app . debug = True <EOL> app . run ( host = '<STR_LIT>' , port = port ) </s>
|
<s> import itertools <EOL> try : <EOL> from django . contrib . admin . utils import NestedObjects <EOL> except ImportError : <EOL> from django . contrib . admin . util import NestedObjects <EOL> from django . db import router <EOL> HARD_DELETE = <NUM_LIT:0> <EOL> SOFT_DELETE = <NUM_LIT:1> <EOL> SOFT_DELETE_CASCADE = <NUM_LIT:2> <EOL> HARD_DELETE_NOCASCADE = <NUM_LIT:3> <EOL> NO_DELETE = <NUM_LIT:4> <EOL> DELETED_INVISIBLE = <NUM_LIT:10> <EOL> DELETED_VISIBLE_BY_PK = <NUM_LIT:11> <EOL> def related_objects ( obj ) : <EOL> """<STR_LIT>""" <EOL> collector = NestedObjects ( using = router . db_for_write ( obj ) ) <EOL> collector . collect ( [ obj ] ) <EOL> def flatten ( elem ) : <EOL> if isinstance ( elem , list ) : <EOL> return itertools . chain . from_iterable ( map ( flatten , elem ) ) <EOL> elif obj != elem : <EOL> return ( elem , ) <EOL> return ( ) <EOL> return flatten ( collector . nested ( ) ) </s>
|
<s> '''<STR_LIT>''' <EOL> import logging <EOL> from mc_states import saltapi <EOL> from mc_states . grains . makina_grains import _is_lxc <EOL> _errmsg = saltapi . _errmsg <EOL> __name = '<STR_LIT>' <EOL> log = logging . getLogger ( __name__ ) <EOL> VT = '<STR_LIT>' <EOL> PREFIX = '<STR_LIT>' . format ( VT ) <EOL> def vt ( ) : <EOL> return __salt__ [ '<STR_LIT>' ] ( VT ) <EOL> def is_lxc ( ) : <EOL> """<STR_LIT>""" <EOL> return _is_lxc ( ) <EOL> def vt_default_settings ( cloudSettings , imgSettings ) : <EOL> '''<STR_LIT>''' <EOL> _s = __salt__ <EOL> clone_from = imgSettings [ '<STR_LIT>' ] [ '<STR_LIT:default>' ] <EOL> backing = '<STR_LIT>' <EOL> if _s [ '<STR_LIT>' ] ( ) : <EOL> backing = '<STR_LIT>' <EOL> vmSettings = _s [ '<STR_LIT>' ] ( <EOL> _s [ '<STR_LIT>' ] ( cloudSettings , imgSettings ) , { <EOL> '<STR_LIT>' : VT , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : { '<STR_LIT>' : clone_from , '<STR_LIT>' : backing } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : { '<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>' : None , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : [ <EOL> ] , <EOL> '<STR_LIT>' : [ <EOL> ] , <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT>' : [ ] <EOL> } , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : { '<STR_LIT>' : <NUM_LIT> } , <EOL> '<STR_LIT>' : { } , <EOL> '<STR_LIT>' : { } , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT:source>' : <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' } , <EOL> '<STR_LIT>' : { } , <EOL> '<STR_LIT>' : { } , <EOL> '<STR_LIT>' : { } , <EOL> '<STR_LIT>' : { } , <EOL> '<STR_LIT>' : { <EOL> "<STR_LIT>" : "<STR_LIT>" , <EOL> "<STR_LIT>" : False , <EOL> '<STR_LIT:source>' : ( <EOL> '<STR_LIT>' <EOL> ) <EOL> } , <EOL> } } ) <EOL> return vmSettings <EOL> def vt_extpillar ( target , data , * args , ** kw ) : <EOL> '''<STR_LIT>''' <EOL> return data <EOL> def vm_extpillar ( vm , data , * args , ** kw ) : <EOL> '''<STR_LIT>''' <EOL> backing = data [ '<STR_LIT>' ] . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> data [ '<STR_LIT>' ] [ '<STR_LIT>' ] [ '<STR_LIT>' ] = data [ '<STR_LIT>' ] <EOL> if data [ '<STR_LIT>' ] . get ( '<STR_LIT>' ) is not None : <EOL> data . pop ( '<STR_LIT:image>' , None ) <EOL> if not data . get ( '<STR_LIT>' ) : <EOL> data [ '<STR_LIT>' ] = [ ] <EOL> shm = True <EOL> for i in data [ '<STR_LIT>' ] : <EOL> if '<STR_LIT>' in i : <EOL> shm = False <EOL> if shm : <EOL> data [ '<STR_LIT>' ] . append ( '<STR_LIT>' ) <EOL> if ( '<STR_LIT>' in backing ) or ( '<STR_LIT>' in backing ) : <EOL> for k in [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:size>' ] : <EOL> if k in data : <EOL> data . pop ( k , None ) <EOL> return data </s>
|
<s> '''<STR_LIT>''' <EOL> import msgpack <EOL> import os <EOL> import copy <EOL> import json <EOL> import hashlib <EOL> import logging <EOL> import time <EOL> import traceback <EOL> import yaml <EOL> from salt . utils import yamldumper <EOL> from salt . renderers . yaml import get_yaml_loader <EOL> from salt . exceptions import SaltException <EOL> from salt . utils . odict import OrderedDict <EOL> from mc_states . api import _GLOBAL_KINDS <EOL> from mc_states . api import _SUB_REGISTRIES <EOL> import mc_states . api <EOL> import mc_states . saltapi <EOL> from mc_states . saltapi import NoRegistryLoaderFound <EOL> six = mc_states . api . six <EOL> _REGISTRY = { } <EOL> _default_activation_status = object ( ) <EOL> _LOCAL_REG_CACHE = { } <EOL> NOT_SHARED = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' ] <EOL> log = logging . getLogger ( __name__ ) <EOL> DEFAULT_SUF = '<STR_LIT>' <EOL> DEFAULT_LOCAL_REG_NAME = '<STR_LIT>' . format ( DEFAULT_SUF ) <EOL> RKEY = '<STR_LIT>' <EOL> REGISTRY_FORMATS = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> _default = object ( ) <EOL> def get_registry_formats ( ) : <EOL> return copy . deepcopy ( REGISTRY_FORMATS ) <EOL> def is_item_active ( registry_name , <EOL> item , <EOL> default_status = False , <EOL> grains_pref = None , <EOL> force = False ) : <EOL> '''<STR_LIT>''' <EOL> if not grains_pref : <EOL> grains_pref = '<STR_LIT>' . format ( registry_name ) <EOL> local_reg = get_local_registry ( registry_name ) <EOL> for config_entry in [ <EOL> grains_pref + "<STR_LIT>" + item , <EOL> grains_pref + "<STR_LIT:.>" + item <EOL> ] : <EOL> if force : <EOL> val = default_status <EOL> else : <EOL> val = __salt__ [ '<STR_LIT>' ] ( config_entry , <EOL> _default , <EOL> local_registry = local_reg ) <EOL> if val is not _default : <EOL> break <EOL> if val is _default : <EOL> val = default_status <EOL> return val <EOL> def load_kind_registries ( kind ) : <EOL> if kind not in _REGISTRY : <EOL> _REGISTRY [ kind ] = { } <EOL> for registry in _SUB_REGISTRIES : <EOL> if registry in _REGISTRY [ kind ] : <EOL> continue <EOL> try : <EOL> _REGISTRY [ kind ] [ registry ] = __salt__ [ <EOL> '<STR_LIT>' . format ( kind , registry ) ] ( ) <EOL> except KeyError : <EOL> trace = traceback . format_exc ( ) <EOL> raise mc_states . saltapi . NoRegistryLoaderFound ( <EOL> '<STR_LIT>' . format ( kind , registry , trace ) ) <EOL> return _REGISTRY [ kind ] <EOL> def load_registries ( ) : <EOL> for kind in _GLOBAL_KINDS : <EOL> load_kind_registries ( kind ) <EOL> return sorted ( [ a for a in _REGISTRY ] ) <EOL> def kinds ( ) : <EOL> return [ a for a in _GLOBAL_KINDS ] <EOL> def metadata ( kind , grain = None , state = None , bases = None ) : <EOL> if bases is None : <EOL> bases = [ ] <EOL> return { '<STR_LIT>' : kind , '<STR_LIT>' : bases } <EOL> def is_active ( registry , name ) : <EOL> '''<STR_LIT>''' <EOL> try : <EOL> return name in registry [ '<STR_LIT>' ] <EOL> except : <EOL> return False <EOL> def get_registry_paths ( name , registry_format = '<STR_LIT>' ) : <EOL> locs = __salt__ [ '<STR_LIT>' ] ( ) <EOL> etc = locs [ '<STR_LIT>' ] <EOL> confs = { '<STR_LIT>' : '<STR_LIT>' . format ( <EOL> etc , '<STR_LIT>' , name , registry_format ) , <EOL> '<STR_LIT>' : '<STR_LIT>' . format ( <EOL> etc , '<STR_LIT>' , name , registry_format ) , <EOL> '<STR_LIT>' : '<STR_LIT>' . format ( <EOL> etc , '<STR_LIT>' , name , registry_format ) , <EOL> '<STR_LIT>' : '<STR_LIT>' . format ( <EOL> __opts__ [ '<STR_LIT>' ] , name , registry_format ) } <EOL> return confs <EOL> def get_registry_path ( name , <EOL> registry_format = '<STR_LIT>' , <EOL> registryf = None , <EOL> context = None ) : <EOL> confs = get_registry_paths ( <EOL> name , registry_format = registry_format ) <EOL> if registryf and os . path . exists ( registryf ) : <EOL> return registryf <EOL> if context is None or context not in confs : <EOL> if name in NOT_SHARED : <EOL> context = '<STR_LIT>' <EOL> else : <EOL> context = '<STR_LIT>' <EOL> registryf = confs [ context ] <EOL> return registryf <EOL> def yaml_load_local_registry ( name , registryf = None ) : <EOL> registry = __salt__ [ '<STR_LIT>' ] ( <EOL> get_registry_path ( name , <EOL> registryf = registryf , <EOL> registry_format = '<STR_LIT>' ) , <EOL> is_file = True ) <EOL> if not registry : <EOL> registry = { } <EOL> return registry <EOL> def yaml_dump_local_registry ( registry ) : <EOL> content = __salt__ [ '<STR_LIT>' ] ( registry , <EOL> nonewline = False ) <EOL> return content <EOL> def pack_load_local_registry ( name , registryf = None ) : <EOL> value = { } <EOL> regpath = get_registry_path ( name , <EOL> registryf = registryf , <EOL> registry_format = '<STR_LIT>' ) <EOL> try : <EOL> if os . path . exists ( regpath ) : <EOL> with open ( regpath ) as fic : <EOL> rvalue = fic . read ( ) <EOL> value = __salt__ [ '<STR_LIT>' ] ( <EOL> rvalue ) <EOL> except msgpack . exceptions . UnpackValueError : <EOL> log . error ( '<STR_LIT>' . format ( regpath ) ) <EOL> os . unlink ( registryf ) <EOL> value = { } <EOL> return value <EOL> def pack_dump_local_registry ( registry ) : <EOL> '''<STR_LIT>''' <EOL> return __salt__ [ '<STR_LIT>' ] ( registry ) <EOL> def encode_local_registry ( name , registry , registry_format = '<STR_LIT>' ) : <EOL> registryf = get_registry_path ( <EOL> name , registry_format = registry_format ) <EOL> dregistry = os . path . dirname ( registryf ) <EOL> if not os . path . exists ( dregistry ) : <EOL> os . makedirs ( dregistry ) <EOL> content = __salt__ [ <EOL> '<STR_LIT>' . format ( <EOL> registry_format ) ] ( registry ) <EOL> sync = False <EOL> if os . path . exists ( registryf ) : <EOL> with open ( registryf ) as fic : <EOL> old_content = fic . read ( ) <EOL> if old_content != content : <EOL> sync = True <EOL> else : <EOL> sync = True <EOL> if sync : <EOL> with open ( registryf , '<STR_LIT:w>' ) as fic : <EOL> fic . write ( content ) <EOL> os . chmod ( registryf , <NUM_LIT:0> <NUM_LIT> ) <EOL> def _get_local_registry ( name , <EOL> cached = True , <EOL> cachetime = <NUM_LIT> , <EOL> registry_format = '<STR_LIT>' ) : <EOL> '''<STR_LIT>''' <EOL> key = '<STR_LIT>' . format ( '<STR_LIT>' , name ) <EOL> if name not in NOT_SHARED : <EOL> to_load = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> else : <EOL> to_load = [ '<STR_LIT>' ] <EOL> def _do ( name , to_load , registry_format ) : <EOL> registryfs = get_registry_paths ( <EOL> name , registry_format = registry_format ) <EOL> registry = OrderedDict ( ) <EOL> for prefix in to_load : <EOL> registryf = registryfs [ prefix ] <EOL> dregistry = os . path . dirname ( registryf ) <EOL> if not os . path . exists ( dregistry ) : <EOL> os . makedirs ( dregistry ) <EOL> if os . path . exists ( registryf ) : <EOL> data = __salt__ [ <EOL> '<STR_LIT>' . format ( <EOL> registry_format ) ] ( name , registryf ) <EOL> registry = __salt__ [ '<STR_LIT>' ] ( registry , data ) <EOL> _unprefix ( registry , name ) <EOL> return registry <EOL> cache_key = RKEY . format ( key , registry_format ) <EOL> force_run = not cached <EOL> return __salt__ [ '<STR_LIT>' ] ( <EOL> _do , [ name , to_load , registry_format ] , { } , <EOL> cache_key , cachetime , use_memcache = False , <EOL> force_run = force_run ) <EOL> def _unprefix ( registry , name ) : <EOL> loc_k = DEFAULT_LOCAL_REG_NAME . format ( name ) <EOL> for k in [ t for t in registry if t . startswith ( loc_k ) ] : <EOL> spl = loc_k + '<STR_LIT:.>' <EOL> nk = spl . join ( k . split ( spl ) [ <NUM_LIT:1> : ] ) <EOL> registry [ nk ] = registry [ k ] <EOL> registry . pop ( k ) <EOL> return registry <EOL> def get_local_registry ( name , <EOL> cached = True , <EOL> cachetime = <NUM_LIT> , <EOL> registry_format = '<STR_LIT>' ) : <EOL> local_registry = _get_local_registry ( <EOL> name , <EOL> cached = cached , <EOL> cachetime = cachetime , <EOL> registry_format = registry_format ) <EOL> if not local_registry : <EOL> formats = [ <EOL> a <EOL> for a in get_registry_formats ( ) <EOL> if not a == registry_format ] <EOL> for f in formats : <EOL> local_registry = _get_local_registry ( <EOL> name , <EOL> cached = cached , <EOL> cachetime = cachetime , <EOL> registry_format = f ) <EOL> if local_registry : <EOL> break <EOL> _unprefix ( local_registry , name ) <EOL> return local_registry <EOL> def update_registry_params ( registry_name , params , registry_format = '<STR_LIT>' ) : <EOL> '''<STR_LIT>''' <EOL> __salt__ [ '<STR_LIT>' ] ( <EOL> RKEY . format ( registry_name , registry_format ) ) <EOL> registry = get_local_registry ( registry_name , <EOL> cached = False , <EOL> registry_format = registry_format ) <EOL> changes = { } <EOL> topreg_name = '<STR_LIT>' . format ( registry_name ) <EOL> default = True <EOL> if topreg_name in __salt__ : <EOL> registry_obj = __salt__ [ topreg_name ] ( ) <EOL> pref = registry_obj [ '<STR_LIT>' ] <EOL> default = False <EOL> else : <EOL> pref = DEFAULT_LOCAL_REG_NAME . format ( registry_name ) <EOL> for param , value in six . iteritems ( params ) : <EOL> gparam = param <EOL> if ( <EOL> not param . startswith ( pref ) and <EOL> not param . startswith ( '<STR_LIT>' ) <EOL> ) : <EOL> gparam = '<STR_LIT>' . format ( pref , param ) <EOL> reg_value = registry . get ( gparam , _default ) <EOL> if reg_value != value : <EOL> for data in changes , registry : <EOL> data . update ( { gparam : value } ) <EOL> if ( <EOL> default and <EOL> ( not param . startswith ( '<STR_LIT>' ) ) and <EOL> ( param in registry ) <EOL> ) : <EOL> del registry [ param ] <EOL> if changes : <EOL> encode_local_registry ( <EOL> registry_name , registry , registry_format = registry_format ) <EOL> __salt__ [ '<STR_LIT>' ] ( <EOL> RKEY . format ( registry_name , registry_format ) ) <EOL> return changes <EOL> def update_local_registry ( registry_name , params , registry_format = '<STR_LIT>' ) : <EOL> '''<STR_LIT>''' <EOL> return update_registry_params ( registry_name , <EOL> params , <EOL> registry_format = registry_format ) <EOL> def get_registry ( registry_configuration ) : <EOL> '''<STR_LIT>''' <EOL> registry = registry_configuration . copy ( ) <EOL> registry . setdefault ( '<STR_LIT>' , { } ) <EOL> registry [ '<STR_LIT>' ] = '<STR_LIT>' . format ( registry [ '<STR_LIT>' ] ) <EOL> registry [ '<STR_LIT>' ] = '<STR_LIT>' . format ( registry [ '<STR_LIT>' ] ) <EOL> registry . setdefault ( '<STR_LIT>' , { } ) <EOL> registry . setdefault ( '<STR_LIT>' , { } ) <EOL> registry . setdefault ( '<STR_LIT>' , { } ) <EOL> for item , data in registry [ '<STR_LIT>' ] . items ( ) : <EOL> activation_status = _default_activation_status <EOL> if isinstance ( data , dict ) : <EOL> activation_status = __salt__ [ <EOL> '<STR_LIT>' ] ( <EOL> registry [ '<STR_LIT>' ] , <EOL> item , <EOL> default_status = data . get ( '<STR_LIT>' , <EOL> activation_status ) , <EOL> force = data . get ( '<STR_LIT>' , False ) ) <EOL> if activation_status is not _default_activation_status : <EOL> if activation_status : <EOL> registry [ '<STR_LIT>' ] [ item ] = data <EOL> registry [ '<STR_LIT>' ] [ item ] = True <EOL> else : <EOL> registry [ '<STR_LIT>' ] [ item ] = data <EOL> registry [ '<STR_LIT>' ] [ item ] = False <EOL> else : <EOL> registry [ '<STR_LIT>' ] [ item ] = data <EOL> registry [ '<STR_LIT>' ] = registry [ '<STR_LIT>' ] <EOL> return registry <EOL> def construct_registry_configuration ( name , defaults = None ) : <EOL> '''<STR_LIT>''' <EOL> metadata_reg = __salt__ [ '<STR_LIT>' . format ( name ) ] ( ) <EOL> if not defaults : <EOL> defaults = { } <EOL> return __salt__ [ '<STR_LIT>' ] ( { <EOL> '<STR_LIT>' : metadata_reg [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : metadata_reg [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : defaults } ) <EOL> def unregister ( kind , slss , data = None , suf = '<STR_LIT>' ) : <EOL> '''<STR_LIT>''' <EOL> state = '<STR_LIT:\n>' <EOL> if isinstance ( slss , basestring ) : <EOL> slss = [ slss ] <EOL> if slss is None : <EOL> slss = [ ] <EOL> data = locals ( ) <EOL> if slss : <EOL> data [ '<STR_LIT:name>' ] = '<STR_LIT:->' . join ( slss ) <EOL> state += ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) . format ( ** data ) <EOL> state += '<STR_LIT>' <EOL> state += '<STR_LIT>' . format ( ** data ) <EOL> state += '<STR_LIT>' <EOL> for sls in slss : <EOL> state += '<STR_LIT>' . format ( sls ) <EOL> state += '<STR_LIT>' <EOL> state += '<STR_LIT:\n>' <EOL> return state <EOL> def register ( kind , slss , data = None , suf = '<STR_LIT>' ) : <EOL> '''<STR_LIT>''' <EOL> state = '<STR_LIT:\n>' <EOL> if isinstance ( slss , basestring ) : <EOL> slss = [ slss ] <EOL> if slss is None : <EOL> slss = [ ] <EOL> data = locals ( ) <EOL> if slss : <EOL> data [ '<STR_LIT:name>' ] = '<STR_LIT:->' . join ( slss ) <EOL> state += '<STR_LIT>' . format ( ** data ) <EOL> state += '<STR_LIT>' <EOL> state += '<STR_LIT>' . format ( ** data ) <EOL> state += '<STR_LIT>' <EOL> for sls in slss : <EOL> state += '<STR_LIT>' . format ( sls ) <EOL> state += '<STR_LIT>' <EOL> state += '<STR_LIT:\n>' <EOL> return state <EOL> def autoinclude ( reg , additional_includes = None ) : <EOL> '''<STR_LIT>''' <EOL> sls = '<STR_LIT>' <EOL> if not additional_includes : <EOL> additional_includes = [ ] <EOL> bases = reg . get ( '<STR_LIT>' , [ ] ) <EOL> includes = [ ] <EOL> slses = [ ] <EOL> for base in bases : <EOL> includes . append ( '<STR_LIT>' . format ( base = base ) ) <EOL> slses . append ( '<STR_LIT>' . format ( base = base ) ) <EOL> for state , data in reg . get ( '<STR_LIT>' , { } ) . items ( ) : <EOL> includes . append ( '<STR_LIT>' . format ( <EOL> rstatesPref = reg [ '<STR_LIT>' ] , state = state ) ) <EOL> slses . append ( '<STR_LIT>' . format ( <EOL> rstatesPref = reg [ '<STR_LIT>' ] , state = state ) ) <EOL> includes . extend ( [ '<STR_LIT>' . format ( a ) <EOL> for a in additional_includes ] ) <EOL> slses . extend ( [ '<STR_LIT>' . format ( a ) for a in additional_includes ] ) <EOL> if includes : <EOL> includes . insert ( <NUM_LIT:0> , '<STR_LIT>' ) <EOL> sls += '<STR_LIT>' . join ( includes ) <EOL> slss = [ ] <EOL> for state , data in reg . get ( '<STR_LIT>' , { } ) . items ( ) : <EOL> slss . append ( state ) <EOL> sls += '<STR_LIT>' . format ( <EOL> __salt__ [ '<STR_LIT>' ] ( reg [ '<STR_LIT>' ] , slss , suf = '<STR_LIT>' ) ) <EOL> slss = [ ] <EOL> for state , data in reg . get ( '<STR_LIT>' , { } ) . items ( ) : <EOL> slss . append ( state ) <EOL> sls += '<STR_LIT>' . format ( <EOL> __salt__ [ '<STR_LIT>' ] ( reg [ '<STR_LIT>' ] , slss , suf = '<STR_LIT>' ) ) <EOL> return sls <EOL> def get_local_cache_key ( key ) : <EOL> return mc_states . saltapi . get_cache_key ( key , __opts__ ) <EOL> def _cache_entry ( local_reg , key , ttl = <NUM_LIT:1> ) : <EOL> data = local_reg . get ( key , OrderedDict ( ) ) <EOL> if not isinstance ( data , dict ) : <EOL> data = OrderedDict ( ) <EOL> data . setdefault ( '<STR_LIT>' , ttl ) <EOL> data . setdefault ( '<STR_LIT:value>' , _default ) <EOL> data . setdefault ( '<STR_LIT:time>' , time . time ( ) ) <EOL> return data <EOL> def default_cache_value ( ) : <EOL> return _default <EOL> def store_local_cache ( registry , local_reg , ttl = <NUM_LIT:1> ) : <EOL> now = time . time ( ) <EOL> for k in [ a for a in local_reg ] : <EOL> data = _cache_entry ( local_reg , k ) <EOL> if now > data [ '<STR_LIT:time>' ] + data [ '<STR_LIT>' ] : <EOL> local_reg . pop ( k , None ) <EOL> __salt__ [ '<STR_LIT>' ] ( <EOL> registry , local_reg , registry_format = '<STR_LIT>' ) <EOL> local_reg = __salt__ [ '<STR_LIT>' ] ( <EOL> registry , registry_format = '<STR_LIT>' ) <EOL> return local_reg <EOL> def save_local_cached_entry ( value , <EOL> key = None , <EOL> sha1_key = None , <EOL> ttl = <NUM_LIT:1> , <EOL> registry = '<STR_LIT>' ) : <EOL> if not ( key or sha1_key ) : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> if not sha1_key : <EOL> sha1_key = get_local_cache_key ( key ) <EOL> local_reg = __salt__ [ '<STR_LIT>' ] ( <EOL> registry , registry_format = '<STR_LIT>' ) <EOL> data = _cache_entry ( local_reg , sha1_key , ttl = ttl ) <EOL> now = time . time ( ) <EOL> if ( now > data [ '<STR_LIT:time>' ] + ttl ) or ( value is not _default ) : <EOL> data [ '<STR_LIT>' ] = ttl <EOL> data [ '<STR_LIT:time>' ] = now <EOL> data [ '<STR_LIT:value>' ] = value <EOL> local_reg [ sha1_key ] = data <EOL> local_reg = store_local_cache ( registry , <EOL> local_reg , <EOL> ttl = ttl ) <EOL> return local_reg <EOL> def get_local_cached_entry ( key , <EOL> default = _default , <EOL> ttl = <NUM_LIT:1> , <EOL> soft = False , <EOL> registry = '<STR_LIT>' ) : <EOL> local_reg = __salt__ [ '<STR_LIT>' ] ( <EOL> registry , registry_format = '<STR_LIT>' ) <EOL> sha1_key = get_local_cache_key ( key ) <EOL> data = _cache_entry ( local_reg , sha1_key , ttl = ttl ) <EOL> now = time . time ( ) <EOL> value = _default <EOL> if ttl and ( now <= data [ '<STR_LIT:time>' ] + ttl ) : <EOL> value = data [ '<STR_LIT:value>' ] <EOL> data [ '<STR_LIT:value>' ] = value <EOL> if value is _default and not soft : <EOL> raise KeyError ( key ) <EOL> return data <EOL> def filecache_fun ( func , <EOL> args = None , <EOL> kwargs = None , <EOL> registry = '<STR_LIT>' , <EOL> prefix = None , <EOL> ttl = <NUM_LIT:1> ) : <EOL> '''<STR_LIT>''' <EOL> if isinstance ( kwargs , dict ) : <EOL> kwargs = copy . deepcopy ( kwargs ) <EOL> for k in [ a for a in kwargs ] : <EOL> if k . startswith ( '<STR_LIT>' ) : <EOL> kwargs . pop ( k , None ) <EOL> if not prefix : <EOL> prefix = '<STR_LIT>' . format ( func ) <EOL> key = '<STR_LIT>' . format ( prefix ) <EOL> try : <EOL> key += json . dumps ( args ) <EOL> except TypeError : <EOL> try : <EOL> key += '<STR_LIT>' . format ( repr ( args ) ) <EOL> except Exception : <EOL> key += '<STR_LIT>' <EOL> try : <EOL> key += json . dumps ( kwargs ) <EOL> except TypeError : <EOL> try : <EOL> key += '<STR_LIT>' . format ( repr ( kwargs ) ) <EOL> except Exception : <EOL> key += '<STR_LIT>' <EOL> data = get_local_cached_entry ( key , ttl = ttl , soft = True ) <EOL> value = data [ '<STR_LIT:value>' ] <EOL> if value is _default : <EOL> if args is not None and kwargs is not None : <EOL> value = func ( * args , ** kwargs ) <EOL> elif args is not None and ( kwargs is None ) : <EOL> value = func ( * args ) <EOL> elif ( args is None ) and kwargs is not None : <EOL> value = func ( ** kwargs ) <EOL> else : <EOL> value = func ( ) <EOL> try : <EOL> save_local_cached_entry ( value , <EOL> key , <EOL> registry = registry , <EOL> ttl = ttl ) <EOL> except Exception : <EOL> log . error ( traceback . format_exc ( ) ) <EOL> else : <EOL> log . garbage ( '<STR_LIT>' ) <EOL> return value <EOL> def glob_dump ( ) : <EOL> try : <EOL> return copy . deepcopy ( _GLOBAL_KINDS ) <EOL> except ( TypeError , ValueError ) : <EOL> return _GLOBAL_KINDS <EOL> def sub_dump ( ) : <EOL> try : <EOL> return copy . deepcopy ( _SUB_REGISTRIES ) <EOL> except ( TypeError , ValueError ) : <EOL> return _SUB_REGISTRIES <EOL> def dump ( ) : <EOL> try : <EOL> return copy . deepcopy ( _REGISTRY ) <EOL> except ( TypeError , ValueError ) : <EOL> return _REGISTRY </s>
|
<s> '''<STR_LIT>''' <EOL> import logging <EOL> import mc_states . api <EOL> __name = '<STR_LIT>' <EOL> log = logging . getLogger ( __name__ ) <EOL> def settings ( ) : <EOL> '''<STR_LIT>''' <EOL> @ mc_states . api . lazy_subregistry_get ( __salt__ , __name ) <EOL> def _settings ( ) : <EOL> grains = __grains__ <EOL> pillar = __pillar__ <EOL> rabbitmq_reg = __salt__ [ <EOL> '<STR_LIT>' ] ( <EOL> '<STR_LIT>' , registry_format = '<STR_LIT>' ) <EOL> pw = rabbitmq_reg . setdefault ( <EOL> '<STR_LIT:password>' , __salt__ [ '<STR_LIT>' ] ( ) ) <EOL> locs = __salt__ [ '<STR_LIT>' ] ( ) <EOL> data = __salt__ [ '<STR_LIT>' ] ( <EOL> '<STR_LIT>' , { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT:password>' : pw , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : '<STR_LIT>' + __grains__ [ '<STR_LIT:host>' ] , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : "<STR_LIT>" , <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> } , <EOL> '<STR_LIT>' : { <EOL> } , <EOL> '<STR_LIT>' : { <EOL> } , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : [ <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ] , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT:password>' : __salt__ [ '<STR_LIT>' ] ( <EOL> '<STR_LIT>' ) , <EOL> } <EOL> } ) <EOL> __salt__ [ '<STR_LIT>' ] ( <EOL> '<STR_LIT>' , rabbitmq_reg , <EOL> registry_format = '<STR_LIT>' ) <EOL> return data <EOL> return _settings ( ) </s>
|
<s> '''<STR_LIT>''' <EOL> import logging <EOL> import salt . utils <EOL> log = logging . getLogger ( __name__ ) <EOL> def ext_pillar ( id_ , pillar , * args , ** kw ) : <EOL> data = salt . utils . odict . OrderedDict ( ) <EOL> for i in [ <EOL> '<STR_LIT>' , <EOL> ] : <EOL> data = __salt__ [ '<STR_LIT>' ] ( <EOL> data , __salt__ [ i ] ( id_ , pillar , * args , ** kw ) ) <EOL> data [ '<STR_LIT>' ] = True <EOL> return data </s>
|
<s> '''<STR_LIT>''' <EOL> from __future__ import absolute_import <EOL> from __future__ import division <EOL> from __future__ import print_function <EOL> import copy <EOL> import sys <EOL> import os <EOL> import pipes <EOL> import string <EOL> import random <EOL> import subprocess <EOL> import hashlib <EOL> import textwrap <EOL> import six <EOL> try : <EOL> from collections import OrderedDict <EOL> except ImportError : <EOL> try : <EOL> from orderedict import OrderedDict <EOL> except ImportError : <EOL> OrderedDict = dict <EOL> J = os . path . join <EOL> _CWD = os . path . dirname ( os . path . dirname ( <EOL> os . path . abspath ( __file__ ) ) ) <EOL> RED = '<STR_LIT>' <EOL> PURPLE = '<STR_LIT>' <EOL> CYAN = '<STR_LIT>' <EOL> YELLOW = '<STR_LIT>' <EOL> GREEN = '<STR_LIT>' <EOL> NORMAL = '<STR_LIT>' <EOL> COLORS = { '<STR_LIT>' : RED , <EOL> '<STR_LIT>' : PURPLE , <EOL> '<STR_LIT>' : CYAN , <EOL> '<STR_LIT>' : YELLOW , <EOL> '<STR_LIT>' : NORMAL , <EOL> '<STR_LIT>' : GREEN } <EOL> class StageError ( Exception ) : <EOL> '''<STR_LIT:.>''' <EOL> def hashfile ( afile , hasher = None , blocksize = <NUM_LIT> ) : <EOL> if not hasher : <EOL> hasher = hashlib . md5 ( ) <EOL> buf = afile . read ( blocksize ) <EOL> while len ( buf ) > <NUM_LIT:0> : <EOL> hasher . update ( buf ) <EOL> buf = afile . read ( blocksize ) <EOL> return hasher . digest ( ) <EOL> def id_generator ( size = <NUM_LIT:10> , chars = string . ascii_uppercase + string . digits ) : <EOL> return '<STR_LIT>' . join ( random . choice ( chars ) for _ in range ( size ) ) <EOL> def purple ( msg , pipe = sys . stdout ) : <EOL> pipe . write ( PURPLE ) <EOL> pipe . write ( msg ) <EOL> pipe . write ( NORMAL ) <EOL> pipe . write ( '<STR_LIT:\n>' ) <EOL> def red ( msg , pipe = sys . stdout ) : <EOL> pipe . write ( RED ) <EOL> pipe . write ( msg ) <EOL> pipe . write ( NORMAL ) <EOL> pipe . write ( '<STR_LIT:\n>' ) <EOL> def cyan ( msg , pipe = sys . stdout ) : <EOL> pipe . write ( CYAN ) <EOL> pipe . write ( msg ) <EOL> pipe . write ( NORMAL ) <EOL> pipe . write ( '<STR_LIT:\n>' ) <EOL> def yellow ( msg , pipe = sys . stdout ) : <EOL> pipe . write ( YELLOW ) <EOL> pipe . write ( msg ) <EOL> pipe . write ( NORMAL ) <EOL> pipe . write ( '<STR_LIT:\n>' ) <EOL> def green ( msg , pipe = sys . stdout ) : <EOL> pipe . write ( GREEN ) <EOL> pipe . write ( msg ) <EOL> pipe . write ( NORMAL ) <EOL> pipe . write ( '<STR_LIT:\n>' ) <EOL> def die ( reason , pipe = sys . stderr ) : <EOL> red ( reason , pipe = pipe ) <EOL> raise StageError ( reason ) <EOL> def die_in_error ( p , reason , pipe = sys . stderr ) : <EOL> if p . returncode != <NUM_LIT:0> : <EOL> die ( reason , pipe = pipe ) <EOL> def warn_in_error ( p , reason = '<STR_LIT>' , pipe = sys . stderr ) : <EOL> if p . returncode != <NUM_LIT:0> : <EOL> yellow ( reason , pipe = pipe ) <EOL> def run_cmd ( cmd , <EOL> env = None , <EOL> shell = True , <EOL> output = True , <EOL> pipe = sys . stdout , <EOL> errpipe = sys . stderr ) : <EOL> if not env : <EOL> env = copy . deepcopy ( os . environ ) <EOL> if not output : <EOL> pipe = subprocess . PIPE <EOL> errpipe = subprocess . PIPE <EOL> p = subprocess . Popen ( cmd , <EOL> shell = shell , <EOL> env = env , <EOL> stderr = errpipe , <EOL> stdout = pipe ) <EOL> p . wait ( ) <EOL> return p <EOL> def qrun_cmd ( * args , ** kwargs ) : <EOL> kwargs [ '<STR_LIT>' ] = False <EOL> return run_cmd ( * args , ** kwargs ) <EOL> def v_run ( cmd , <EOL> env = None , <EOL> shell = True , <EOL> pipe = sys . stdout , <EOL> errpipe = sys . stderr ) : <EOL> green ( cmd , pipe = pipe ) <EOL> return run_cmd ( cmd , env = env , shell = shell , pipe = pipe , errpipe = errpipe ) <EOL> def v_die_run ( cmd , <EOL> env = None , <EOL> reason = None , <EOL> shell = True , <EOL> pipe = sys . stdout , <EOL> errpipe = sys . stderr ) : <EOL> if not reason : <EOL> reason = '<STR_LIT>' . format ( cmd ) <EOL> p = v_run ( cmd , env = env , shell = shell , pipe = pipe , errpipe = errpipe ) <EOL> die_in_error ( p , reason , pipe = errpipe ) <EOL> return p <EOL> def q_die_run ( cmd , <EOL> env = None , <EOL> reason = None , <EOL> shell = True , <EOL> pipe = sys . stdout , <EOL> errpipe = sys . stderr ) : <EOL> if not reason : <EOL> reason = '<STR_LIT>' . format ( cmd ) <EOL> p = run_cmd ( <EOL> cmd , output = False , env = env , shell = shell , pipe = pipe , errpipe = errpipe ) <EOL> die_in_error ( p , reason , pipe = errpipe ) <EOL> return p <EOL> REPORT = textwrap . dedent ( '''<STR_LIT>''' ) <EOL> def report ( environ , pipe = sys . stdout ) : <EOL> pipe . write ( REPORT . format ( c = COLORS , e = environ ) ) <EOL> def main ( argv = None , <EOL> environ = None , <EOL> pipe = sys . stdout , <EOL> errpipe = sys . stderr ) : <EOL> if not environ : <EOL> environ = copy . deepcopy ( os . environ ) <EOL> if argv is None : <EOL> argv = sys . argv [ : ] <EOL> yellow ( '<STR_LIT>' , pipe = pipe ) <EOL> yellow ( '<STR_LIT>' , pipe = pipe ) <EOL> yellow ( '<STR_LIT>' , pipe = pipe ) <EOL> yellow ( '<STR_LIT>' , pipe = pipe ) <EOL> yellow ( '<STR_LIT>' , pipe = pipe ) <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> environ . setdefault ( <EOL> '<STR_LIT>' , '<STR_LIT>' ) <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> DEFAULT_RELEASE = '<STR_LIT>' <EOL> if environ [ '<STR_LIT>' ] == '<STR_LIT>' : <EOL> DEFAULT_RELEASE = '<STR_LIT>' <EOL> environ . setdefault ( '<STR_LIT>' , DEFAULT_RELEASE ) <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> MS_DATA_DIR = environ . setdefault ( <EOL> '<STR_LIT>' , os . path . join ( _CWD , '<STR_LIT:data>' ) ) <EOL> MS_IMAGE = environ . setdefault ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' . format ( environ ) ) <EOL> MS_IMAGE_DIR = environ . setdefault ( <EOL> '<STR_LIT>' , <EOL> os . path . join ( environ [ '<STR_LIT>' ] , environ [ '<STR_LIT>' ] ) ) <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT:yes>' ) <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT:yes>' ) <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT:yes>' ) <EOL> environ . setdefault ( <EOL> '<STR_LIT>' , '<STR_LIT>' ) <EOL> default_stage_path = os . path . join ( _CWD , '<STR_LIT>' ) <EOL> stage_paths = [ ] <EOL> for p in [ <EOL> J ( MS_IMAGE_DIR , '<STR_LIT>' ) , <EOL> environ . setdefault ( '<STR_LIT>' , default_stage_path ) , <EOL> default_stage_path <EOL> ] : <EOL> if os . path . exists ( p ) and p not in stage_paths : <EOL> stage_paths . append ( p ) <EOL> for env_key , fic in six . iteritems ( { <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> for stage_path in stage_paths : <EOL> pretendant = environ . setdefault ( env_key , J ( stage_path , fic ) ) <EOL> if os . path . exists ( pretendant ) : <EOL> break <EOL> environ . setdefault ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' . format ( environ ) ) <EOL> environ . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> environ . setdefault ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> environ . setdefault ( <EOL> '<STR_LIT>' , <EOL> MS_IMAGE . split ( '<STR_LIT::>' ) [ <NUM_LIT:0> ] + '<STR_LIT>' ) <EOL> environ . setdefault ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' <EOL> . format ( environ ) ) <EOL> id_ = id_generator ( ) <EOL> environ . setdefault ( <EOL> '<STR_LIT>' , <EOL> environ [ '<STR_LIT>' ] . replace ( '<STR_LIT:/>' , '<STR_LIT>' ) + '<STR_LIT>' + id_ ) <EOL> environ . setdefault ( <EOL> '<STR_LIT>' , <EOL> environ [ '<STR_LIT>' ] . replace ( '<STR_LIT:/>' , '<STR_LIT>' ) + '<STR_LIT>' + id_ ) <EOL> MS_INJECTED_DIR = environ [ '<STR_LIT>' ] = os . path . join ( <EOL> environ [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> MS_IMAGE_ROOTFS = environ [ '<STR_LIT>' ] = os . path . join ( <EOL> environ [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> MS_BOOTSTRAP_DIR = environ [ '<STR_LIT>' ] = os . path . join ( <EOL> MS_INJECTED_DIR , '<STR_LIT>' ) <EOL> environ [ '<STR_LIT>' ] = environ [ '<STR_LIT>' ] = _CWD <EOL> report ( environ , pipe = pipe ) <EOL> cpcmd = '<STR_LIT>' <EOL> if qrun_cmd ( '<STR_LIT>' ) . returncode != <NUM_LIT:0> : <EOL> raise StageError ( <EOL> '<STR_LIT>' ) <EOL> breakl = False <EOL> for i in [ <EOL> MS_DATA_DIR , <EOL> MS_INJECTED_DIR , <EOL> MS_BOOTSTRAP_DIR , <EOL> MS_IMAGE_DIR <EOL> ] : <EOL> if not os . path . exists ( i ) : <EOL> try : <EOL> cyan ( '<STR_LIT>' . format ( MS_IMAGE , i ) , pipe = pipe ) <EOL> os . makedirs ( i ) <EOL> except OSError : <EOL> die ( '<STR_LIT>' <EOL> . format ( MS_IMAGE , i ) , pipe = pipe ) <EOL> breakl = True <EOL> if breakl : <EOL> pipe . write ( '<STR_LIT:\n>' ) <EOL> stage_files = OrderedDict ( ) <EOL> stage_files [ <EOL> J ( MS_BOOTSTRAP_DIR , '<STR_LIT>' ) ] = os . path . join ( <EOL> _CWD , '<STR_LIT>' ) <EOL> stage_files [ <EOL> J ( MS_BOOTSTRAP_DIR , '<STR_LIT>' ) ] = os . path . join ( <EOL> _CWD , '<STR_LIT>' ) <EOL> stage_files [ <EOL> J ( MS_BOOTSTRAP_DIR , '<STR_LIT>' ) ] = environ [ <EOL> '<STR_LIT>' ] <EOL> stage_files [ J ( MS_BOOTSTRAP_DIR , '<STR_LIT>' ) ] = environ [ '<STR_LIT>' ] <EOL> stage_files [ J ( MS_BOOTSTRAP_DIR , '<STR_LIT>' ) ] = environ [ '<STR_LIT>' ] <EOL> stage_files [ J ( MS_BOOTSTRAP_DIR , '<STR_LIT>' ) ] = environ [ '<STR_LIT>' ] <EOL> stage_files [ J ( MS_BOOTSTRAP_DIR , '<STR_LIT>' ) ] = environ [ '<STR_LIT>' ] <EOL> for j in stage_files : <EOL> i = os . path . basename ( j ) <EOL> k = stage_files [ j ] <EOL> d = os . path . dirname ( j ) <EOL> if not os . path . exists ( k ) : <EOL> die ( '<STR_LIT>' <EOL> '<STR_LIT>' . format ( MS_IMAGE , i , k ) , pipe = errpipe ) <EOL> if not os . path . exists ( d ) : <EOL> cyan ( '<STR_LIT>' . format ( MS_IMAGE , d ) , pipe = pipe ) <EOL> os . makedirs ( d ) <EOL> docp = True <EOL> if os . path . isfile ( j ) and os . path . exists ( j ) and os . path . exists ( k ) : <EOL> docp = False <EOL> with open ( j ) as jo : <EOL> with open ( k ) as ko : <EOL> if hashfile ( jo ) != hashfile ( ko ) : <EOL> docp = True <EOL> if not docp : <EOL> yellow ( '<STR_LIT>' . format ( MS_IMAGE , i ) , pipe = pipe ) <EOL> else : <EOL> q_die_run ( <EOL> '<STR_LIT>' . format ( cpcmd , pipes . quote ( k ) , pipes . quote ( j ) ) , <EOL> env = environ , <EOL> pipe = pipe , <EOL> errpipe = errpipe , <EOL> reason = ( '<STR_LIT>' <EOL> '<STR_LIT>' . format ( <EOL> MS_IMAGE , i , k , j ) ) ) <EOL> cyan ( '<STR_LIT>' . format ( MS_IMAGE , k , j ) , pipe = pipe ) <EOL> pipe . write ( '<STR_LIT:\n>' ) <EOL> if os . path . exists ( MS_IMAGE_ROOTFS ) : <EOL> q_die_run ( <EOL> '<STR_LIT>' . format ( cpcmd , <EOL> pipes . quote ( MS_IMAGE_ROOTFS ) , <EOL> pipes . quote ( MS_INJECTED_DIR ) ) , <EOL> env = environ , <EOL> pipe = pipe , <EOL> errpipe = errpipe , <EOL> reason = ( '<STR_LIT>' <EOL> '<STR_LIT>' . format ( <EOL> MS_IMAGE , MS_IMAGE_ROOTFS , MS_INJECTED_DIR ) ) ) <EOL> cyan ( '<STR_LIT>' . format ( <EOL> MS_IMAGE , MS_IMAGE_ROOTFS , MS_INJECTED_DIR ) , pipe = pipe ) <EOL> if argv [ <NUM_LIT:1> : ] : <EOL> environ [ '<STR_LIT>' ] += '<STR_LIT>' . format ( '<STR_LIT:U+0020>' . join ( argv [ <NUM_LIT:1> : ] ) ) <EOL> purple ( '<STR_LIT>' , pipe = pipe ) <EOL> purple ( '<STR_LIT>' , pipe = pipe ) <EOL> purple ( '<STR_LIT>' , pipe = pipe ) <EOL> pipe . write ( '<STR_LIT:\n>' ) <EOL> p = v_die_run ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' . format ( MS_IMAGE_DIR , '<STR_LIT:U+0020>' . join ( argv ) ) , <EOL> env = environ , <EOL> reason = '<STR_LIT>' . format ( MS_IMAGE ) ) <EOL> return p , environ , pipe , errpipe <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> main ( ) </s>
|
<s> '''<STR_LIT>''' <EOL> import logging <EOL> import copy <EOL> import mc_states . api <EOL> from salt . utils . odict import OrderedDict <EOL> __name = '<STR_LIT>' <EOL> six = mc_states . api . six <EOL> PREFIX = '<STR_LIT>' . format ( __name ) <EOL> logger = logging . getLogger ( __name__ ) <EOL> prefered_ips = mc_states . api . prefered_ips <EOL> PUBLIC_ZONES = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> INTERNAL_ZONES = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> PUBLIC_SERVICES = [ '<STR_LIT:http>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> DIRECT_RULESETS = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> ZONE_RULESETS = [ '<STR_LIT>' ] <EOL> RULESETS = DIRECT_RULESETS [ : ] + ZONE_RULESETS [ : ] <EOL> FAILOVER_COUNT = <NUM_LIT:16> <EOL> DEFAULT_TARGET = '<STR_LIT>' <EOL> LOCAL_NETS = [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] <EOL> def prefered_ips ( ips , ttl = <NUM_LIT> , * args , ** kw ) : <EOL> def _do ( * a , ** k ) : <EOL> return mc_states . api . prefered_ips ( * a , ** k ) <EOL> cache_key = __name + '<STR_LIT>' . format ( ips ) <EOL> return __salt__ [ '<STR_LIT>' ] ( <EOL> _do , [ ips ] , { } , cache_key , ttl ) <EOL> def is_allow_local ( ) : <EOL> _s = __salt__ <EOL> data_net = _s [ '<STR_LIT>' ] ( ) <EOL> default_route = data_net [ '<STR_LIT>' ] <EOL> local_mode = False <EOL> if __salt__ [ '<STR_LIT>' ] ( ) : <EOL> local_mode = True <EOL> return local_mode <EOL> def is_permissive ( ) : <EOL> _s = __salt__ <EOL> data_net = _s [ '<STR_LIT>' ] ( ) <EOL> default_route = data_net [ '<STR_LIT>' ] <EOL> permissive_mode = False <EOL> if __salt__ [ '<STR_LIT>' ] ( ) : <EOL> rif = default_route . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> if rif == '<STR_LIT>' : <EOL> permissive_mode = True <EOL> return permissive_mode <EOL> def fix_data ( data = None ) : <EOL> if data is None : <EOL> data = { } <EOL> data . setdefault ( '<STR_LIT>' , LOCAL_NETS [ : ] ) <EOL> data . setdefault ( '<STR_LIT>' , { } ) <EOL> data . setdefault ( '<STR_LIT>' , [ ] ) <EOL> data . setdefault ( '<STR_LIT>' , [ ] ) <EOL> data . setdefault ( '<STR_LIT>' , [ ] ) <EOL> data . setdefault ( '<STR_LIT>' , [ ] ) <EOL> data . setdefault ( '<STR_LIT>' , INTERNAL_ZONES [ : ] ) <EOL> data . setdefault ( '<STR_LIT>' , is_permissive ( ) ) <EOL> data . setdefault ( '<STR_LIT>' , is_allow_local ( ) ) <EOL> data . setdefault ( '<STR_LIT>' , PUBLIC_ZONES [ : ] ) <EOL> data . setdefault ( '<STR_LIT>' , [ ] ) <EOL> data . setdefault ( '<STR_LIT>' , True ) <EOL> data . setdefault ( '<STR_LIT>' , OrderedDict ( ) ) <EOL> if data [ '<STR_LIT>' ] is None : <EOL> data [ '<STR_LIT>' ] = is_permissive ( ) <EOL> if data [ '<STR_LIT>' ] is None : <EOL> data [ '<STR_LIT>' ] = True <EOL> return data <EOL> def get_configured_ifs ( data ) : <EOL> configured_ifs = { } <EOL> for i in data [ '<STR_LIT>' ] : <EOL> for f in data [ '<STR_LIT>' ] [ i ] . get ( '<STR_LIT>' , [ ] ) : <EOL> if f not in configured_ifs : <EOL> configured_ifs [ f ] = i <EOL> return configured_ifs <EOL> def is_eth ( ifc ) : <EOL> return ifc . startswith ( '<STR_LIT>' ) or ifc . startswith ( '<STR_LIT>' ) <EOL> def test_container ( data = None ) : <EOL> if not data : <EOL> data = { } <EOL> return data . setdefault ( '<STR_LIT>' , <EOL> __salt__ [ '<STR_LIT>' ] ( ) ) <EOL> def test_rpn ( data , iface , ems = None ) : <EOL> if not ems : <EOL> ems = [ ] <EOL> realrpn = False <EOL> if data . get ( '<STR_LIT>' , False ) and ( <EOL> not test_container ( data ) <EOL> ) and ( <EOL> iface in [ '<STR_LIT>' ] or iface in ems <EOL> ) : <EOL> if iface in ems : <EOL> if iface == ems [ - <NUM_LIT:1> ] : <EOL> realrpn = True <EOL> else : <EOL> realrpn = True <EOL> return realrpn <EOL> def add_real_interfaces ( data = None ) : <EOL> _s = __salt__ <EOL> if data is None : <EOL> data = { } <EOL> fzones = data . setdefault ( '<STR_LIT>' , OrderedDict ( ) ) <EOL> is_container = test_container ( data ) <EOL> data_net = _s [ '<STR_LIT>' ] ( ) <EOL> gifaces = data_net [ '<STR_LIT>' ] <EOL> default_if = data_net [ '<STR_LIT>' ] <EOL> ems = [ i for i , ips in gifaces <EOL> if i . startswith ( '<STR_LIT>' ) and len ( i ) in [ <NUM_LIT:3> , <NUM_LIT:4> ] ] <EOL> configured_ifs = get_configured_ifs ( data ) <EOL> dz = data . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> for iface , ips in gifaces : <EOL> z = None <EOL> if iface in configured_ifs : <EOL> continue <EOL> if ( is_container and is_eth ( iface ) ) or iface == default_if : <EOL> z = dz <EOL> elif '<STR_LIT>' in iface : <EOL> z = '<STR_LIT>' <EOL> elif iface . startswith ( '<STR_LIT>' ) : <EOL> z = '<STR_LIT>' <EOL> elif '<STR_LIT>' in iface : <EOL> z = '<STR_LIT>' <EOL> elif '<STR_LIT>' in iface : <EOL> z = '<STR_LIT>' <EOL> elif test_rpn ( data , iface , ems ) : <EOL> z = '<STR_LIT>' <EOL> elif iface in [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] : <EOL> z = dz <EOL> elif iface . startswith ( '<STR_LIT>' ) or iface . startswith ( '<STR_LIT>' ) : <EOL> z = '<STR_LIT>' <EOL> if z : <EOL> zone = fzones . setdefault ( z , { } ) <EOL> ifs = zone . setdefault ( '<STR_LIT>' , [ ] ) <EOL> if iface not in ifs : <EOL> ifs . append ( iface ) <EOL> return data <EOL> def search_aliased_interfaces ( data = None ) : <EOL> '''<STR_LIT>''' <EOL> data = fix_data ( data ) <EOL> public_ifs = [ ] <EOL> for z in data [ '<STR_LIT>' ] : <EOL> zone = data [ '<STR_LIT>' ] . setdefault ( z , { } ) <EOL> zone . setdefault ( '<STR_LIT>' , [ ] ) <EOL> for i in zone [ '<STR_LIT>' ] : <EOL> public_ifs . append ( i ) <EOL> for i in zone [ '<STR_LIT>' ] : <EOL> if i not in data [ '<STR_LIT>' ] : <EOL> data [ '<STR_LIT>' ] . append ( i ) <EOL> for ifc in data [ '<STR_LIT>' ] : <EOL> if ifc not in public_ifs : <EOL> for z in data [ '<STR_LIT>' ] : <EOL> zdata = data [ '<STR_LIT>' ] . setdefault ( z , { } ) <EOL> ifcs = zdata . setdefault ( '<STR_LIT>' , [ ] ) <EOL> if ifc not in ifcs : <EOL> ifcs . append ( ifc ) <EOL> return data <EOL> def add_aliased_interfaces ( data = None ) : <EOL> '''<STR_LIT>''' <EOL> if data is None : <EOL> data = { } <EOL> zonesn = [ z for z in data [ '<STR_LIT>' ] ] <EOL> data = search_aliased_interfaces ( data ) <EOL> cfgs = get_configured_ifs ( data ) <EOL> count = data . setdefault ( '<STR_LIT>' , FAILOVER_COUNT ) <EOL> for i in data [ '<STR_LIT>' ] : <EOL> for c in range ( count ) : <EOL> j = '<STR_LIT>' . format ( i , c ) <EOL> if j in cfgs : <EOL> continue <EOL> for z in zonesn : <EOL> ifs = data [ '<STR_LIT>' ] [ z ] . get ( '<STR_LIT>' , [ ] ) <EOL> if i in ifs and j not in ifs : <EOL> ifs . append ( j ) <EOL> return data <EOL> def default_settings ( ) : <EOL> _s = __salt__ <EOL> DEFAULTS = { <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : FAILOVER_COUNT , <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT>' : [ ] , <EOL> '<STR_LIT>' : LOCAL_NETS [ : ] , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] , <EOL> '<STR_LIT>' : { '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] } , <EOL> '<STR_LIT>' : OrderedDict ( [ <EOL> ( '<STR_LIT>' , { } ) , <EOL> ( '<STR_LIT>' , { } ) , <EOL> ( '<STR_LIT>' , { '<STR_LIT>' : [ '<STR_LIT>' ] } ) , <EOL> ( '<STR_LIT>' , { } ) , <EOL> ( '<STR_LIT>' , { } ) , <EOL> ( '<STR_LIT>' , { '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' ] } ) , <EOL> ( '<STR_LIT>' , { '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] } ) , <EOL> ( '<STR_LIT>' , { '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' ] } ) , <EOL> ( '<STR_LIT>' , { '<STR_LIT>' : [ ] } ) , <EOL> ( '<STR_LIT>' , { '<STR_LIT>' : [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] } ) , <EOL> ( '<STR_LIT>' , { } ) , <EOL> ( '<STR_LIT>' , { } ) , <EOL> ( '<STR_LIT>' , { } ) ] ) , <EOL> '<STR_LIT>' : INTERNAL_ZONES [ : ] , <EOL> '<STR_LIT>' : PUBLIC_ZONES [ : ] , <EOL> '<STR_LIT>' : PUBLIC_SERVICES [ : ] , <EOL> '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } , <EOL> { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT:http>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } , <EOL> '<STR_LIT>' : { '<STR_LIT:port>' : [ { '<STR_LIT:port>' : '<STR_LIT>' } ] } <EOL> } , <EOL> '<STR_LIT>' : _s [ '<STR_LIT>' ] ( ) , <EOL> '<STR_LIT>' : _s [ '<STR_LIT>' ] ( ) , <EOL> '<STR_LIT>' : _s [ '<STR_LIT>' ] ( ) , <EOL> '<STR_LIT>' : _s [ '<STR_LIT>' ] ( ) , <EOL> '<STR_LIT>' : is_permissive ( ) , <EOL> '<STR_LIT>' : is_allow_local ( ) , <EOL> '<STR_LIT>' : None , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : { } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : { '<STR_LIT>' : '<STR_LIT>' } <EOL> } } <EOL> test_container ( DEFAULTS ) <EOL> data = _s [ '<STR_LIT>' ] ( PREFIX , DEFAULTS ) <EOL> if data [ '<STR_LIT>' ] is None : <EOL> data [ '<STR_LIT>' ] = True <EOL> if data [ '<STR_LIT>' ] is None : <EOL> if data [ '<STR_LIT>' ] : <EOL> data [ '<STR_LIT>' ] = data [ '<STR_LIT>' ] [ <NUM_LIT:0> ] <EOL> else : <EOL> data [ '<STR_LIT>' ] = PUBLIC_ZONES [ <NUM_LIT:0> ] <EOL> data = complete_rules ( data ) <EOL> data = add_real_interfaces ( data ) <EOL> data = add_aliased_interfaces ( data ) <EOL> return data <EOL> def cached_default_settings ( ttl = <NUM_LIT> ) : <EOL> cache_key = __name + '<STR_LIT>' <EOL> return __salt__ [ '<STR_LIT>' ] ( <EOL> default_settings , [ ] , { } , cache_key , ttl ) <EOL> def get_endrule ( audit = None , <EOL> log = None , <EOL> log_level = None , <EOL> log_prefix = None , <EOL> limit = None ) : <EOL> endrule = '<STR_LIT>' <EOL> if log : <EOL> endrule += '<STR_LIT>' <EOL> if log_level : <EOL> endrule += '<STR_LIT>' . format ( log_level ) <EOL> if log_prefix : <EOL> endrule += '<STR_LIT>' . format ( log_prefix ) <EOL> elif audit : <EOL> endrule += '<STR_LIT>' <EOL> if isinstance ( audit , basestring ) : <EOL> endrule += '<STR_LIT>' . format ( audit ) <EOL> if limit and ( log or audit ) : <EOL> endrule += '<STR_LIT>' . format ( limit ) <EOL> return endrule <EOL> def has_action ( rule ) : <EOL> ret = ( <EOL> ( '<STR_LIT>' in rule ) or <EOL> ( '<STR_LIT>' in rule ) or <EOL> ( '<STR_LIT>' in rule ) or <EOL> ( '<STR_LIT>' in rule ) or <EOL> ( '<STR_LIT>' in rule ) or <EOL> ( '<STR_LIT>' in rule ) <EOL> ) <EOL> return ret <EOL> def complete_rules ( data ) : <EOL> for z in [ a for a in data [ '<STR_LIT>' ] ] : <EOL> zdata = data [ '<STR_LIT>' ] [ z ] <EOL> if not isinstance ( zdata , dict ) : <EOL> data [ '<STR_LIT>' ] . pop ( z , None ) <EOL> data . setdefault ( '<STR_LIT>' , DIRECT_RULESETS [ : ] ) <EOL> for ruleset in data [ '<STR_LIT>' ] : <EOL> rules = data . setdefault ( ruleset , [ ] ) <EOL> for i in [ <EOL> a for a in data <EOL> if ( <EOL> ( a . endswith ( "<STR_LIT:->" + ruleset ) or a . startswith ( ruleset + "<STR_LIT:->" ) ) and <EOL> a not in [ ruleset ] ) <EOL> ] : <EOL> val = data [ i ] <EOL> if isinstance ( val , basestring ) : <EOL> val = [ val ] <EOL> if isinstance ( val , list ) : <EOL> for i in val : <EOL> if i not in rules : <EOL> rules . append ( i ) <EOL> for z in [ a for a in data [ '<STR_LIT>' ] ] : <EOL> zdata = data [ '<STR_LIT>' ] [ z ] <EOL> zdata . setdefault ( '<STR_LIT>' , ZONE_RULESETS [ : ] ) <EOL> for ruleset in zdata [ '<STR_LIT>' ] : <EOL> rules = zdata . setdefault ( ruleset , [ ] ) <EOL> for i in [ <EOL> a for a in zdata <EOL> if ( <EOL> ( a . endswith ( "<STR_LIT:->" + ruleset ) or a . startswith ( ruleset + "<STR_LIT:->" ) ) and <EOL> a not in [ ruleset ] ) <EOL> ] : <EOL> val = zdata [ i ] <EOL> if isinstance ( val , basestring ) : <EOL> val = [ val ] <EOL> if isinstance ( val , list ) : <EOL> for i in val : <EOL> if i not in rules : <EOL> rules . append ( i ) <EOL> return data <EOL> def action_allowed ( rule ) : <EOL> ret = not ( <EOL> ( '<STR_LIT>' in rule ) or <EOL> ( '<STR_LIT>' in rule ) or <EOL> ( '<STR_LIT>' in rule ) <EOL> ) <EOL> return ret <EOL> def source_allowed ( rule ) : <EOL> return '<STR_LIT>' not in rule <EOL> def destination_allowed ( rule ) : <EOL> return ( <EOL> ( '<STR_LIT>' not in rule ) <EOL> ) <EOL> def complete_rich_rules ( rules = None , <EOL> rule = None , <EOL> family = None , <EOL> destinations = None , <EOL> icmp_block = None , <EOL> masquerade = None , <EOL> sources = None , <EOL> protocols = None , <EOL> ports = None , <EOL> forward_ports = None , <EOL> services = None , <EOL> endrule = None , <EOL> audit = None , <EOL> log = None , <EOL> log_prefix = None , <EOL> log_level = None , <EOL> limit = None , <EOL> action = None ) : <EOL> '''<STR_LIT>''' <EOL> if not ( <EOL> family and ( <EOL> masquerade or <EOL> has_action ( endrule or '<STR_LIT>' ) or <EOL> ports or <EOL> forward_ports or <EOL> icmp_block or <EOL> ( sources or destinations ) <EOL> ) <EOL> ) : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> else : <EOL> if rules is None : <EOL> rules = [ ] <EOL> if not rule : <EOL> rule = '<STR_LIT>' <EOL> to_add_rules = [ rule ] <EOL> if family : <EOL> buffer_rules = [ ] <EOL> for rule in to_add_rules : <EOL> if '<STR_LIT>' in rule : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> else : <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( family ) <EOL> if prule not in to_add_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if masquerade : <EOL> buffer_rules = [ ] <EOL> for rule in to_add_rules : <EOL> if has_action ( rule ) : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> else : <EOL> prule = rule <EOL> prule += '<STR_LIT>' <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if len ( sources ) == <NUM_LIT:1> and not destinations : <EOL> source = sources [ <NUM_LIT:0> ] <EOL> destination = source <EOL> if not source . startswith ( '<STR_LIT>' ) : <EOL> destination = '<STR_LIT>' . format ( destination ) <EOL> destinations = [ destination ] <EOL> if icmp_block : <EOL> buffer_rules = [ ] <EOL> if isinstance ( icmp_block , six . string_types ) : <EOL> icmp_block = [ icmp_block ] <EOL> elif not isinstance ( icmp_block , list ) : <EOL> icmp_block = [ '<STR_LIT>' ] <EOL> prules = [ ] <EOL> for i in icmp_block : <EOL> rule = '<STR_LIT>' <EOL> if i : <EOL> rule += '<STR_LIT>' . format ( i ) <EOL> if rule not in prules : <EOL> prules . append ( rule ) <EOL> for rule in to_add_rules : <EOL> if has_action ( rule ) : <EOL> continue <EOL> for prule in prules : <EOL> prule = '<STR_LIT>' . format ( rule , prule ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if sources : <EOL> buffer_rules = [ ] <EOL> for rule in to_add_rules : <EOL> if not source_allowed ( rule ) : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> for p in sources : <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( p ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if destinations : <EOL> buffer_rules = [ ] <EOL> for rule in to_add_rules : <EOL> if not destination_allowed ( rule ) : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> for p in destinations : <EOL> prule = rule <EOL> if '<STR_LIT>' in rule and '<STR_LIT::>' in p : <EOL> continue <EOL> if '<STR_LIT>' in rule and '<STR_LIT:.>' in p : <EOL> continue <EOL> prule += '<STR_LIT>' . format ( p ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if ports : <EOL> buffer_rules = [ ] <EOL> pprotocols = protocols <EOL> if not pprotocols : <EOL> pprotocols = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> for rule in to_add_rules : <EOL> if has_action ( rule ) : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> for portid , fromport in six . iteritems ( ports ) : <EOL> fromp = fromport [ '<STR_LIT:port>' ] <EOL> protocols = fromport . get ( '<STR_LIT>' , pprotocols [ : ] ) <EOL> for protocol in protocols : <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( <EOL> fromp , protocol ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if forward_ports : <EOL> buffer_rules = [ ] <EOL> pprotocols = protocols <EOL> if not pprotocols : <EOL> pprotocols = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> for rule in to_add_rules : <EOL> if has_action ( rule ) : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> for portid , portdata in six . iteritems ( forward_ports ) : <EOL> fromp = portdata [ '<STR_LIT:port>' ] <EOL> protocols = portdata . get ( '<STR_LIT>' , pprotocols [ : ] ) <EOL> to_port = portdata . get ( '<STR_LIT>' ) <EOL> to_addr = portdata . get ( '<STR_LIT>' ) <EOL> for protocol in protocols : <EOL> prule = rule <EOL> prule += ( <EOL> '<STR_LIT>' <EOL> ) . format ( fromp , protocol ) <EOL> if to_port : <EOL> prule += '<STR_LIT>' . format ( to_port ) <EOL> if to_addr : <EOL> prule += '<STR_LIT>' . format ( to_addr ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if services : <EOL> buffer_rules = [ ] <EOL> for rule in to_add_rules : <EOL> if has_action ( rule ) : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> for svc in services : <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( svc ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if protocols : <EOL> buffer_rules = [ ] <EOL> for rule in to_add_rules : <EOL> if not ( <EOL> ( '<STR_LIT>' in rule ) or <EOL> ( '<STR_LIT>' in rule ) <EOL> ) or ( <EOL> has_action ( rule ) <EOL> ) : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> for protocol in protocols : <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( protocol ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if endrule : <EOL> buffer_rules = [ ] <EOL> for rule in to_add_rules : <EOL> if has_action ( endrule ) and has_action ( rule ) : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( endrule ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if log : <EOL> buffer_rules = [ ] <EOL> logrule = '<STR_LIT>' <EOL> if log_level : <EOL> logrule += '<STR_LIT>' . format ( log_level ) <EOL> if log_prefix : <EOL> logrule += '<STR_LIT>' . format ( log_prefix ) <EOL> for rule in to_add_rules : <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( logrule ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> elif audit : <EOL> buffer_rules = [ ] <EOL> logrule += '<STR_LIT>' <EOL> if isinstance ( audit , basestring ) : <EOL> logrule += '<STR_LIT>' . format ( audit ) <EOL> for rule in to_add_rules : <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( logrule ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if limit and ( log or audit ) : <EOL> buffer_rules = [ ] <EOL> logrule = '<STR_LIT>' . format ( limit ) <EOL> for rule in to_add_rules : <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( logrule ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> if action : <EOL> buffer_rules = [ ] <EOL> for rule in to_add_rules : <EOL> if not action_allowed ( rule ) : <EOL> if rule not in buffer_rules : <EOL> buffer_rules . append ( rule ) <EOL> continue <EOL> prule = rule <EOL> prule += '<STR_LIT>' . format ( action ) <EOL> if prule not in buffer_rules : <EOL> buffer_rules . append ( prule ) <EOL> to_add_rules = buffer_rules <EOL> for rule in to_add_rules : <EOL> if ( <EOL> rule . strip ( ) and <EOL> rule not in rules and <EOL> rule not in [ '<STR_LIT>' ] <EOL> ) : <EOL> rules . append ( rule ) <EOL> return rules <EOL> def complete_address ( address ) : <EOL> if ( <EOL> isinstance ( address , six . string_types ) and <EOL> address and <EOL> '<STR_LIT>' not in address <EOL> ) : <EOL> address = '<STR_LIT>' . format ( address ) <EOL> return address <EOL> def get_public_ips ( cache = True , data = None , ttl = <NUM_LIT> ) : <EOL> if not cache : <EOL> ttl = <NUM_LIT:0> <EOL> def _do ( data ) : <EOL> if not data : <EOL> data = cached_default_settings ( ) <EOL> running_net = __salt__ [ '<STR_LIT>' ] ( ) <EOL> net = __salt__ [ '<STR_LIT>' ] ( ) <EOL> ifcs = set ( ) <EOL> public_ips = set ( ) <EOL> zones = data . get ( '<STR_LIT>' , { } ) <EOL> for z in data . get ( '<STR_LIT>' , [ ] ) : <EOL> for ifc in zones . get ( z , { } ) . get ( '<STR_LIT>' , [ ] ) : <EOL> ifcs . add ( ifc ) <EOL> for ifc , ips in six . iteritems ( <EOL> __grains__ . get ( '<STR_LIT>' , { } ) <EOL> ) : <EOL> if ifc not in ifcs : <EOL> continue <EOL> for ip in ips : <EOL> public_ips . add ( ip ) <EOL> for iface , ips in running_net . get ( '<STR_LIT>' , [ ] ) : <EOL> if ifc not in ifcs : <EOL> continue <EOL> for addr in ips : <EOL> if addr : <EOL> public_ips . add ( addr ) <EOL> for interfaces in net . get ( '<STR_LIT>' , [ ] ) : <EOL> for ifc , odata in six . iteritems ( interfaces ) : <EOL> ifc = ifc . replace ( '<STR_LIT:_>' , '<STR_LIT::>' ) <EOL> if ifc not in ifcs : <EOL> continue <EOL> addr = odata . get ( '<STR_LIT:address>' , '<STR_LIT>' ) <EOL> if addr : <EOL> public_ips . add ( addr ) <EOL> public_ips = list ( public_ips ) <EOL> def _filter_local ( is_public ) : <EOL> def do ( ip ) : <EOL> if is_public : <EOL> return __salt__ [ '<STR_LIT>' ] ( ip ) <EOL> else : <EOL> return not __salt__ [ '<STR_LIT>' ] ( ip ) <EOL> return do <EOL> is_public = False <EOL> for i in public_ips [ : ] : <EOL> if __salt__ [ '<STR_LIT>' ] ( i ) : <EOL> is_public = True <EOL> break <EOL> if test_container ( data ) : <EOL> is_public = False <EOL> public_ips = filter ( _filter_local ( is_public ) , public_ips ) <EOL> return public_ips <EOL> cache_key = __name + '<STR_LIT>' <EOL> return __salt__ [ '<STR_LIT>' ] ( <EOL> _do , [ data ] , { } , cache_key , ttl ) <EOL> def rich_rules ( family = '<STR_LIT>' , <EOL> sources = None , <EOL> source = None , <EOL> destinations = None , <EOL> destination = None , <EOL> services = None , <EOL> service = None , <EOL> ports = None , <EOL> port = None , <EOL> audit = None , <EOL> log = None , <EOL> log_prefix = None , <EOL> log_level = None , <EOL> forward_ports = None , <EOL> forward_port = None , <EOL> limit = None , <EOL> icmp_block = None , <EOL> masquerade = False , <EOL> action = '<STR_LIT>' , <EOL> public_ips = None , <EOL> protocols = None ) : <EOL> '''<STR_LIT>''' <EOL> rules = [ ] <EOL> if not destinations : <EOL> destinations = [ ] <EOL> destinations = destinations [ : ] <EOL> if destination and destination not in destinations : <EOL> destinations . append ( destination ) <EOL> if public_ips is False : <EOL> public_ips = [ ] <EOL> elif not public_ips : <EOL> public_ips = destinations [ : ] <EOL> if not public_ips : <EOL> public_ips = get_public_ips ( ) <EOL> public_ips = [ complete_address ( d ) for d in public_ips if d ] <EOL> destinations = [ complete_address ( d ) for d in destinations if d ] <EOL> address_protocols = protocols <EOL> if not address_protocols : <EOL> address_protocols = [ ] <EOL> if not protocols : <EOL> protocols = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> if not forward_ports : <EOL> forward_ports = [ ] <EOL> if not ports : <EOL> ports = [ ] <EOL> ports = ports [ : ] <EOL> if port and port not in ports : <EOL> ports . append ( port ) <EOL> nports = { } <EOL> for port in ports : <EOL> if isinstance ( port , ( int , ) ) : <EOL> port = "<STR_LIT>" . format ( port ) <EOL> if isinstance ( port , ( six . string_types ) ) : <EOL> port = { '<STR_LIT:port>' : port , '<STR_LIT>' : protocols [ : ] } <EOL> if isinstance ( port , dict ) : <EOL> protos = port . setdefault ( '<STR_LIT>' , protocols [ : ] ) <EOL> nport = nports . setdefault ( port [ '<STR_LIT:port>' ] , port ) <EOL> nport [ '<STR_LIT:port>' ] = port [ '<STR_LIT:port>' ] <EOL> for p in protos : <EOL> if p not in nport [ '<STR_LIT>' ] : <EOL> nport [ '<STR_LIT>' ] . append ( p ) <EOL> else : <EOL> raise ValueError ( '<STR_LIT>' . format ( port ) ) <EOL> ports = nports <EOL> forward_ports = forward_ports [ : ] <EOL> if forward_port and forward_port not in forward_ports : <EOL> forward_ports . append ( forward_port ) <EOL> forward_ports = [ a for a in forward_ports if isinstance ( a , dict ) ] <EOL> if not services : <EOL> services = [ ] <EOL> services = services [ : ] <EOL> if service and service not in services : <EOL> services . append ( service ) <EOL> services = [ a for a in services if a ] <EOL> if not family : <EOL> family = '<STR_LIT>' <EOL> if not sources : <EOL> sources = [ ] <EOL> sources = sources [ : ] <EOL> if source and source not in sources : <EOL> sources . append ( source ) <EOL> nforward_ports = { } <EOL> for p in forward_ports [ : ] : <EOL> if '<STR_LIT>' not in p and '<STR_LIT:port>' not in p : <EOL> raise ValueError ( '<STR_LIT>' . format ( p ) ) <EOL> port = None <EOL> if '<STR_LIT>' in p and '<STR_LIT:port>' not in p : <EOL> port = p [ '<STR_LIT>' ] <EOL> if port and isinstance ( port , int ) : <EOL> port = "<STR_LIT>" . format ( port ) <EOL> if port is not None : <EOL> p [ '<STR_LIT>' ] = p [ '<STR_LIT:port>' ] = port <EOL> for i in [ '<STR_LIT:port>' , '<STR_LIT>' ] : <EOL> if isinstance ( p . get ( i ) , int ) : <EOL> p [ i ] = "<STR_LIT>" . format ( p [ i ] ) <EOL> p . setdefault ( '<STR_LIT>' , protocols [ : ] ) <EOL> if p [ '<STR_LIT:port>' ] in ports : <EOL> ports . pop ( p [ '<STR_LIT:port>' ] , None ) <EOL> nforward_ports [ p [ '<STR_LIT:port>' ] ] = p <EOL> sources = [ complete_address ( d ) for d in sources ] <EOL> lsources = [ a for a in sources if a ] <EOL> if not family : <EOL> raise ValueError ( <EOL> '<STR_LIT>' ) <EOL> if masquerade : <EOL> rules = complete_rich_rules ( rules , <EOL> family = family , <EOL> masquerade = masquerade , <EOL> sources = lsources , <EOL> destinations = destinations , <EOL> log = log , <EOL> log_level = log_level , <EOL> log_prefix = log_prefix , <EOL> limit = limit ) <EOL> return rules <EOL> if icmp_block : <EOL> rules = complete_rich_rules ( rules , <EOL> family = family , <EOL> icmp_block = icmp_block , <EOL> sources = lsources , <EOL> destinations = destinations , <EOL> log = log , <EOL> log_level = log_level , <EOL> log_prefix = log_prefix , <EOL> limit = limit ) <EOL> return rules <EOL> if ports : <EOL> rules = complete_rich_rules ( rules , <EOL> family = family , <EOL> sources = sources , <EOL> destinations = public_ips , <EOL> audit = audit , <EOL> ports = ports , <EOL> log = log , <EOL> log_level = log_level , <EOL> log_prefix = log_prefix , <EOL> limit = limit , <EOL> action = action ) <EOL> if forward_ports : <EOL> rules = complete_rich_rules ( rules , <EOL> family = family , <EOL> sources = sources , <EOL> destinations = public_ips , <EOL> audit = audit , <EOL> forward_ports = nforward_ports , <EOL> log = log , <EOL> log_level = log_level , <EOL> log_prefix = log_prefix , <EOL> limit = limit , <EOL> action = action ) <EOL> if services : <EOL> rules = complete_rich_rules ( rules , <EOL> family = family , <EOL> sources = sources , <EOL> destinations = public_ips , <EOL> audit = audit , <EOL> services = services , <EOL> log = log , <EOL> log_level = log_level , <EOL> log_prefix = log_prefix , <EOL> limit = limit , <EOL> action = action ) <EOL> if ( <EOL> ( ( sources or destinations ) and protocols ) and <EOL> not ( masquerade or <EOL> ports or <EOL> services or <EOL> forward_ports ) <EOL> ) : <EOL> rules = complete_rich_rules ( rules , <EOL> family = family , <EOL> sources = sources , <EOL> destinations = destinations , <EOL> audit = audit , <EOL> log = log , <EOL> log_level = log_level , <EOL> log_prefix = log_prefix , <EOL> limit = limit , <EOL> protocols = address_protocols , <EOL> action = action ) <EOL> return rules <EOL> def rich_rule ( ** kwargs ) : <EOL> return rich_rules ( ** kwargs ) [ <NUM_LIT:0> ] <EOL> def add_rule ( data , zones = None , rule = None , rules = None , ** kwargs ) : <EOL> rrules = rich_rules ( ** kwargs ) <EOL> if rules is None : <EOL> rules = [ ] <EOL> if isinstance ( rule , six . string_types ) and rule not in rules : <EOL> rules . append ( rule ) <EOL> for i in rules : <EOL> if i not in rrules : <EOL> rrules . append ( rule ) <EOL> if not zones : <EOL> zones = [ z for z in data [ '<STR_LIT>' ] ] <EOL> for z in zones : <EOL> rules = data [ '<STR_LIT>' ] [ z ] . setdefault ( '<STR_LIT>' , [ ] ) <EOL> for rule in rrules : <EOL> if rule not in rules : <EOL> rules . append ( rule ) <EOL> return data <EOL> def add_zones_policies ( data = None ) : <EOL> data = fix_data ( data ) <EOL> zones = data . get ( '<STR_LIT>' , { } ) <EOL> for z in data [ '<STR_LIT>' ] : <EOL> zdata = zones . get ( z , { } ) <EOL> t = zdata . get ( '<STR_LIT:target>' , DEFAULT_TARGET ) <EOL> if data [ '<STR_LIT>' ] : <EOL> t = '<STR_LIT>' <EOL> zone = data [ '<STR_LIT>' ] . setdefault ( z , { } ) <EOL> zone [ '<STR_LIT:target>' ] = t <EOL> for z in data [ '<STR_LIT>' ] : <EOL> zdata = zones . get ( z , { } ) <EOL> t = zdata . get ( '<STR_LIT:target>' , DEFAULT_TARGET ) <EOL> if data [ '<STR_LIT>' ] : <EOL> t = '<STR_LIT>' <EOL> zone = data [ '<STR_LIT>' ] . setdefault ( z , { } ) <EOL> zone [ '<STR_LIT:target>' ] = t <EOL> if not data . get ( '<STR_LIT>' , False ) : <EOL> rule = '<STR_LIT>' <EOL> add_rule ( data , rule = rule ) <EOL> for network in data [ '<STR_LIT>' ] : <EOL> add_rule ( data , source = network , action = '<STR_LIT>' ) <EOL> for network in data [ '<STR_LIT>' ] : <EOL> add_rule ( data , source = network , action = '<STR_LIT>' ) <EOL> return data <EOL> def add_natted_networks ( data = None ) : <EOL> '''<STR_LIT>''' <EOL> data = fix_data ( data ) <EOL> to_nat = set ( ) <EOL> natted = data . get ( '<STR_LIT>' , { } ) <EOL> notinternal = [ ] <EOL> for z in data . get ( '<STR_LIT>' , { } ) : <EOL> if z not in data . get ( '<STR_LIT>' , [ ] ) : <EOL> notinternal . append ( z ) <EOL> continue <EOL> zdata = data [ '<STR_LIT>' ] [ z ] <EOL> for ifc in zdata . get ( '<STR_LIT>' , [ ] ) : <EOL> for network in natted . get ( ifc , [ ] ) : <EOL> to_nat . add ( network ) <EOL> if not notinternal : <EOL> notinternal = None <EOL> if data [ '<STR_LIT>' ] : <EOL> for network in data [ '<STR_LIT>' ] : <EOL> nw = network . split ( '<STR_LIT:/>' ) [ <NUM_LIT:0> ] <EOL> if __salt__ [ '<STR_LIT>' ] ( nw ) : <EOL> continue <EOL> add_rule ( data = data , <EOL> zones = notinternal , <EOL> source = '<STR_LIT>' . format ( network ) , <EOL> action = '<STR_LIT>' ) <EOL> if not test_container ( data ) : <EOL> for network in to_nat : <EOL> add_rule ( data = data , <EOL> zones = notinternal , <EOL> masquerade = True , <EOL> source = '<STR_LIT>' . format ( network ) , <EOL> destination = '<STR_LIT>' . format ( network ) ) <EOL> return data <EOL> def add_services_policies ( data = None ) : <EOL> data = fix_data ( data ) <EOL> _s = __salt__ <EOL> burpsettings = _s [ '<STR_LIT>' ] ( ) <EOL> controllers_registry = _s [ '<STR_LIT>' ] ( ) <EOL> for i in [ '<STR_LIT>' , '<STR_LIT>' ] : <EOL> for s in data [ i ] : <EOL> data [ '<STR_LIT>' ] . setdefault ( s , { } ) <EOL> if not data . get ( '<STR_LIT>' , False ) : <EOL> if controllers_registry [ '<STR_LIT>' ] [ '<STR_LIT>' ] : <EOL> if '<STR_LIT>' not in data [ '<STR_LIT>' ] : <EOL> data [ '<STR_LIT>' ] . append ( '<STR_LIT>' ) <EOL> if controllers_registry [ '<STR_LIT>' ] [ '<STR_LIT>' ] : <EOL> if '<STR_LIT>' not in data [ '<STR_LIT>' ] : <EOL> data [ '<STR_LIT>' ] . append ( '<STR_LIT>' ) <EOL> for z in [ a for a in data [ '<STR_LIT>' ] if a != '<STR_LIT>' ] : <EOL> zdata = data [ '<STR_LIT>' ] [ z ] <EOL> services = zdata . setdefault ( '<STR_LIT>' , { } ) <EOL> pservices = zdata . setdefault ( '<STR_LIT>' , [ ] ) <EOL> rservices = zdata . setdefault ( '<STR_LIT>' , [ ] ) <EOL> if not services : <EOL> services . update ( copy . deepcopy ( data [ '<STR_LIT>' ] ) ) <EOL> if not pservices : <EOL> pservices . extend ( copy . deepcopy ( data [ '<STR_LIT>' ] ) ) <EOL> if not rservices : <EOL> rservices . extend ( copy . deepcopy ( data [ '<STR_LIT>' ] ) ) <EOL> for i in [ rservices , pservices ] : <EOL> for s in i : <EOL> services . setdefault ( s , { } ) <EOL> for s in [ a for a in data [ '<STR_LIT>' ] if a not in services ] : <EOL> services [ s ] = copy . deepcopy ( data [ '<STR_LIT>' ] [ s ] ) <EOL> to_add = [ a for a in services ] <EOL> def order_policies ( apservices , arservices ) : <EOL> def do ( a ) : <EOL> pref = '<STR_LIT:z>' <EOL> if a in apservices : <EOL> pref = '<STR_LIT:m>' <EOL> elif a in arservices : <EOL> pref = '<STR_LIT:a>' <EOL> return '<STR_LIT>' . format ( pref , a ) <EOL> return do <EOL> to_add . sort ( key = order_policies ( pservices , rservices ) ) <EOL> for s in to_add : <EOL> if s not in data [ '<STR_LIT>' ] : <EOL> data [ '<STR_LIT>' ] [ s ] = copy . deepcopy ( services [ s ] ) <EOL> sources = None <EOL> if s in pservices : <EOL> policy = '<STR_LIT>' <EOL> elif s in rservices : <EOL> policy = '<STR_LIT>' <EOL> else : <EOL> policy = None <EOL> if s == '<STR_LIT>' : <EOL> sources = [ a for a in burpsettings [ '<STR_LIT>' ] ] <EOL> if not sources : <EOL> sources = [ '<STR_LIT:127.0.0.1>' ] <EOL> if not sources : <EOL> sources = [ ] <EOL> sources = _s [ '<STR_LIT>' ] ( prefered_ips ( sources ) ) <EOL> if policy and data [ '<STR_LIT>' ] and policy != '<STR_LIT>' : <EOL> policy = '<STR_LIT>' <EOL> if s and sources and not policy : <EOL> policy = '<STR_LIT>' <EOL> if policy : <EOL> policy = policy . lower ( ) <EOL> if not ( sources or policy ) : <EOL> continue <EOL> add_rule ( <EOL> data , zones = [ z ] , sources = sources , service = s , action = policy ) <EOL> return data <EOL> def add_cloud_proxies ( data ) : <EOL> _s = __salt__ <EOL> if _s [ '<STR_LIT>' ] ( ) : <EOL> cloud_reg = _s [ '<STR_LIT>' ] ( ) <EOL> cloud_rules = cloud_reg . get ( <EOL> '<STR_LIT>' , { } ) . get ( '<STR_LIT>' , [ ] ) <EOL> for port , portdata in six . iteritems ( cloud_rules ) : <EOL> add_rule ( data , <EOL> zones = data [ '<STR_LIT>' ] , <EOL> forward_port = { '<STR_LIT:port>' : portdata [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : portdata [ '<STR_LIT:port>' ] , <EOL> '<STR_LIT>' : portdata [ '<STR_LIT>' ] } ) <EOL> return data <EOL> def settings ( ) : <EOL> '''<STR_LIT>''' <EOL> @ mc_states . api . lazy_subregistry_get ( __salt__ , __name ) <EOL> def _settings ( ) : <EOL> data = default_settings ( ) <EOL> data = add_zones_policies ( data ) <EOL> data = add_natted_networks ( data ) <EOL> data = add_services_policies ( data ) <EOL> data = add_cloud_proxies ( data ) <EOL> return data <EOL> return _settings ( ) </s>
|
<s> import unittest <EOL> import copy <EOL> from collections import OrderedDict <EOL> from . . import base <EOL> from mc_states . modules import mc_pillar <EOL> from mc_states . modules import mc_utils <EOL> from mc_states . modules import mc_macros <EOL> from mock import patch , Mock <EOL> import yaml <EOL> import contextlib <EOL> __docformat__ = '<STR_LIT>' <EOL> TESTS = { <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> TEST_NET = '''<STR_LIT>''' <EOL> class TestCase ( base . ModuleCase ) : <EOL> def test_get_whitel ( self ) : <EOL> def _load ( ) : <EOL> return yaml . load ( TEST_NET ) <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load , <EOL> } ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT:a>' ) <EOL> self . assertEqual ( res1 , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> def test_get_burp_conf ( self ) : <EOL> def _load ( ) : <EOL> return yaml . load ( TEST_NET ) <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load , <EOL> } ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( <EOL> '<STR_LIT>' ) [ '<STR_LIT>' ] <EOL> self . assertEqual ( res1 , <EOL> { '<STR_LIT>' : { <EOL> '<STR_LIT>' : [ '<STR_LIT:/>' ] , <EOL> '<STR_LIT>' : [ <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] } } ) <EOL> def test_get_shorewallsettings ( self ) : <EOL> def _load ( ) : <EOL> data = yaml . load ( TEST_NET ) <EOL> data [ '<STR_LIT>' ] [ '<STR_LIT:default>' ] [ '<STR_LIT>' ] = False <EOL> data [ '<STR_LIT>' ] [ '<STR_LIT:default>' ] [ '<STR_LIT>' ] = True <EOL> return data <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load <EOL> } ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( <EOL> '<STR_LIT>' ) <EOL> res2 = self . _ ( '<STR_LIT>' ) ( <EOL> '<STR_LIT>' ) <EOL> self . assertEqual ( <EOL> res1 [ '<STR_LIT>' ] , True ) <EOL> self . assertEqual ( <EOL> res2 [ '<STR_LIT>' ] , True ) <EOL> self . assertEqual ( <EOL> res1 [ '<STR_LIT>' <EOL> '<STR_LIT>' ] , '<STR_LIT:bar>' ) <EOL> self . assertEqual ( <EOL> res1 [ '<STR_LIT>' <EOL> '<STR_LIT>' ] , '<STR_LIT:foo>' ) <EOL> k = ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> res1 = self . _ ( '<STR_LIT>' ) ( <EOL> '<STR_LIT>' ) <EOL> res2 = self . _ ( '<STR_LIT>' ) ( <EOL> '<STR_LIT>' ) <EOL> self . assertEqual ( '<STR_LIT:all>' , res1 [ k ] ) <EOL> self . assertNotEqual ( '<STR_LIT:all>' , res2 [ k ] ) <EOL> def test_get_arr ( self ) : <EOL> def _load ( ) : <EOL> return yaml . load ( TEST_NET ) <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load , <EOL> } ) : <EOL> res = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( <EOL> res . splitlines ( ) , <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> '<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> '<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> '<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> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' . splitlines ( ) ) <EOL> def test_get_mx_rr ( self ) : <EOL> def _load ( ) : <EOL> return yaml . load ( TEST_NET ) <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load , <EOL> } ) : <EOL> res = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res , '<STR_LIT>' ) <EOL> def test_get_raw_rr ( self ) : <EOL> def _load ( ) : <EOL> return yaml . load ( TEST_NET ) <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load , <EOL> } ) : <EOL> res = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res , '<STR_LIT>' ) <EOL> def test_get_cnames_for ( self ) : <EOL> def _load ( ) : <EOL> return yaml . load ( TEST_NET ) <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load , <EOL> } ) : <EOL> res = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res , <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> self . assertEqual ( <EOL> self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) , <EOL> '<STR_LIT>' ) <EOL> def test_get_ns_rr ( self ) : <EOL> def _load ( ) : <EOL> data = yaml . load ( TEST_NET ) <EOL> return data <EOL> with self . patch ( <EOL> filtered = [ '<STR_LIT>' ] , <EOL> kinds = [ '<STR_LIT>' ] , <EOL> funcs = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : _load , <EOL> } <EOL> } <EOL> ) : <EOL> res = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res , '<STR_LIT>' ) <EOL> res = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res , '<STR_LIT>' ) <EOL> ip1 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> ip3 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> ip2 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( ip1 , '<STR_LIT>' ) <EOL> self . assertEqual ( ip2 , '<STR_LIT>' ) <EOL> self . assertEqual ( ip3 , '<STR_LIT>' ) <EOL> def test_get_txts_rr ( self ) : <EOL> def _load ( ) : <EOL> return yaml . load ( TEST_NET ) <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load <EOL> } ) : <EOL> res = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res , <EOL> '''<STR_LIT>''' ) <EOL> def test_get_nss ( self ) : <EOL> def _load ( ) : <EOL> return yaml . load ( TEST_NET ) <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load , <EOL> } ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res1 , <EOL> { '<STR_LIT:all>' : [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] , <EOL> '<STR_LIT:z>' : OrderedDict ( [ ( '<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> '<STR_LIT>' ] ) ] ) } ) <EOL> res1 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res1 , <EOL> { '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> res1 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> res2 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( <EOL> res1 , <EOL> { '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : OrderedDict ( [ ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) ] ) } ) <EOL> self . assertEqual ( <EOL> res2 , <EOL> { '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : OrderedDict ( [ ( '<STR_LIT>' , <EOL> '<STR_LIT>' ) ] ) } ) <EOL> res = self . _ ( '<STR_LIT>' ) ( ) <EOL> self . assertEqual ( <EOL> res , <EOL> { '<STR_LIT:all>' : [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] , <EOL> '<STR_LIT>' : OrderedDict ( [ ( '<STR_LIT>' , <EOL> [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] ) ] ) , <EOL> '<STR_LIT>' : OrderedDict ( [ ( '<STR_LIT>' , <EOL> [ '<STR_LIT>' ] ) , <EOL> ( '<STR_LIT>' , <EOL> [ '<STR_LIT>' ] ) , <EOL> ( '<STR_LIT>' , <EOL> [ '<STR_LIT>' ] ) , <EOL> ( '<STR_LIT>' , <EOL> [ '<STR_LIT>' ] ) ] ) } ) <EOL> def atest_load_networkinfra ( self ) : <EOL> def _load ( ) : <EOL> return yaml . load ( TEST_NET ) <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : _load , <EOL> } ) : <EOL> res = self . _ ( '<STR_LIT>' ) ( ) <EOL> self . assertEqual ( <EOL> res [ '<STR_LIT>' ] , { <EOL> '<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> '<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> '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ <EOL> '<STR_LIT>' ] , <EOL> '<STR_LIT>' : [ <EOL> '<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> def test_get_fqdn_domains ( self ) : <EOL> tests = [ ] <EOL> for i in [ '<STR_LIT:foo>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] : <EOL> tests . append ( self . _ ( '<STR_LIT>' ) ( i ) ) <EOL> self . assertEqual ( tests , <EOL> [ [ ] , [ '<STR_LIT:bar>' ] , [ '<STR_LIT>' , '<STR_LIT>' ] , [ '<STR_LIT>' , '<STR_LIT>' ] ] ) <EOL> def test_get_mail_configuration ( self ) : <EOL> def _query ( t , * a , ** kw ) : <EOL> if t in [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] : <EOL> return { <EOL> '<STR_LIT>' : [ '<STR_LIT>' , <EOL> '<STR_LIT>' ] <EOL> } . get ( t , { } ) <EOL> if t in [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] : <EOL> return yaml . load ( TESTS [ t ] ) [ t ] <EOL> ret1 = { <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : ( <EOL> '<STR_LIT>' ) , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : [ <EOL> { '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT:password>' : '<STR_LIT:bar>' , <EOL> '<STR_LIT:user>' : '<STR_LIT>' } ] , <EOL> '<STR_LIT>' : [ <EOL> { '<STR_LIT>' : '<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> { '<STR_LIT>' : ( <EOL> '<STR_LIT>' ) } , <EOL> { '<STR_LIT>' : ( <EOL> '<STR_LIT>' ) } ] } <EOL> with self . patch ( <EOL> filtered = [ '<STR_LIT>' ] , <EOL> kinds = [ '<STR_LIT>' ] , <EOL> funcs = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : Mock ( return_value = True ) , <EOL> '<STR_LIT>' : Mock ( side_effect = _query ) <EOL> } <EOL> } <EOL> ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> res2 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res1 , ret1 ) <EOL> p = '<STR_LIT>' <EOL> self . assertEqual ( res2 [ p ] , <EOL> [ { '<STR_LIT>' : '<STR_LIT>' } ] ) <EOL> def test_get_configuration ( self ) : <EOL> def _query ( t , * a , ** kw ) : <EOL> if t in [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] : <EOL> return yaml . load ( TESTS [ t ] ) [ t ] <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : Mock ( side_effect = _query ) <EOL> } ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( <EOL> '<STR_LIT>' ) <EOL> res2 = self . _ ( '<STR_LIT>' ) ( <EOL> '<STR_LIT>' ) <EOL> self . assertEqual ( res1 , <EOL> { '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' <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>' : True , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> self . assertEqual ( res2 , { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : True , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : False , <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : '<STR_LIT>' } ) <EOL> def test_get_passwords ( self ) : <EOL> data = { } <EOL> def _update_local_reg ( name , * args , ** kw ) : <EOL> lreg = data . setdefault ( name , { } ) <EOL> lreg . update ( args [ <NUM_LIT:0> ] ) <EOL> return lreg <EOL> def _local_reg ( name , * args , ** kw ) : <EOL> lreg = data . setdefault ( name , { } ) <EOL> return lreg <EOL> def _query ( t , * a , ** kw ) : <EOL> if t in [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] : <EOL> return yaml . load ( TESTS [ t ] ) [ t ] <EOL> with patch . dict ( self . salt , { <EOL> '<STR_LIT>' : Mock ( side_effect = _query ) , <EOL> '<STR_LIT>' : Mock ( <EOL> side_effect = _update_local_reg ) , <EOL> '<STR_LIT>' : Mock ( side_effect = _local_reg ) <EOL> } ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( <EOL> res1 , <EOL> { '<STR_LIT>' : { '<STR_LIT:root>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : { '<STR_LIT:root>' : <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> '<STR_LIT>' } } ) <EOL> res2 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( <EOL> res2 , <EOL> { '<STR_LIT>' : { '<STR_LIT:root>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : { '<STR_LIT:root>' : <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' : <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' } } ) <EOL> self . assertFalse ( '<STR_LIT>' in data [ '<STR_LIT>' ] ) <EOL> self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertTrue ( '<STR_LIT>' in data [ '<STR_LIT>' ] ) <EOL> def test_get_sysadmins_keys ( self ) : <EOL> def _query ( t , * a , ** kw ) : <EOL> if t in [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] : <EOL> return { <EOL> '<STR_LIT>' : { } , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , <EOL> '<STR_LIT>' ] } <EOL> if t in [ <EOL> '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' <EOL> ] : <EOL> return yaml . load ( TESTS [ t ] ) [ t ] <EOL> with self . patch ( <EOL> filtered = [ '<STR_LIT>' ] , <EOL> kinds = [ '<STR_LIT>' ] , <EOL> funcs = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : Mock ( return_value = True ) , <EOL> '<STR_LIT>' : Mock ( side_effect = _query ) <EOL> } <EOL> } <EOL> ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> res2 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res1 , [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> self . assertEqual ( res2 , [ '<STR_LIT>' ] ) <EOL> def test_get_sudoers_map ( self ) : <EOL> def _query ( t , * a , ** kw ) : <EOL> if t in [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] : <EOL> return { <EOL> '<STR_LIT>' : { } , <EOL> '<STR_LIT>' : [ '<STR_LIT>' , <EOL> '<STR_LIT>' ] } <EOL> if t in [ '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ] : <EOL> return yaml . load ( TESTS [ t ] ) [ t ] <EOL> with self . patch ( <EOL> filtered = [ '<STR_LIT>' ] , <EOL> kinds = [ '<STR_LIT>' ] , <EOL> funcs = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : Mock ( return_value = True ) , <EOL> '<STR_LIT>' : Mock ( side_effect = _query ) <EOL> } <EOL> } <EOL> ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( <EOL> '<STR_LIT>' ) <EOL> res2 = self . _ ( '<STR_LIT>' ) ( <EOL> '<STR_LIT>' ) <EOL> self . assertEqual ( res1 , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> self . assertEqual ( res2 , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> def test_get_ssh_groups ( self ) : <EOL> def _query ( t , * a , ** kw ) : <EOL> if t == '<STR_LIT>' : <EOL> return yaml . load ( TESTS [ t ] ) [ t ] <EOL> with self . patch ( <EOL> filtered = [ '<STR_LIT>' ] , <EOL> kinds = [ '<STR_LIT>' ] , <EOL> funcs = { <EOL> '<STR_LIT>' : { <EOL> '<STR_LIT>' : Mock ( return_value = True ) , <EOL> '<STR_LIT>' : Mock ( side_effect = _query ) <EOL> } <EOL> } <EOL> ) : <EOL> res1 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> res2 = self . _ ( '<STR_LIT>' ) ( '<STR_LIT>' ) <EOL> self . assertEqual ( res1 , <EOL> [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT:root>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> self . assertEqual ( res2 , <EOL> [ '<STR_LIT>' , '<STR_LIT:root>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> unittest . main ( ) </s>
|
<s> from django . contrib . admin import site <EOL> from dates import models <EOL> site . register ( [ models . Date , models . DateRange ] ) </s>
|
<s> import os <EOL> PROJ_ROOT = os . path . abspath ( os . path . dirname ( __file__ ) ) <EOL> DEV_MODE = True <EOL> DEBUG = True <EOL> TEMPLATE_DEBUG = DEBUG <EOL> ADMINS = ( ) <EOL> MANAGERS = ADMINS <EOL> CLUSTER_SIZE = <NUM_LIT:3> <EOL> DATABASES = { <EOL> '<STR_LIT:default>' : { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : os . path . join ( PROJ_ROOT , '<STR_LIT>' ) , <EOL> } , <EOL> } <EOL> for db_num in range ( CLUSTER_SIZE ) : <EOL> name = "<STR_LIT>" % ( db_num + <NUM_LIT:1> ) <EOL> DATABASES [ name ] = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : os . path . join ( PROJ_ROOT , '<STR_LIT>' % name ) , <EOL> } <EOL> DATABASE_ROUTERS = [ "<STR_LIT>" ] <EOL> TIME_ZONE = None <EOL> LANGUAGE_CODE = '<STR_LIT>' <EOL> SITE_ID = <NUM_LIT:1> <EOL> USE_I18N = True <EOL> USE_L10N = True <EOL> MEDIA_ROOT = "<STR_LIT>" <EOL> MEDIA_URL = "<STR_LIT>" <EOL> ADMIN_MEDIA_PREFIX = '<STR_LIT>' <EOL> SECRET_KEY = '<STR_LIT>' <EOL> TEMPLATE_LOADERS = ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ) <EOL> MIDDLEWARE_CLASSES = ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> ) <EOL> ROOT_URLCONF = '<STR_LIT>' <EOL> TEMPLATE_DIRS = ( <EOL> os . path . join ( PROJ_ROOT , "<STR_LIT:..>" , "<STR_LIT>" ) , <EOL> ) <EOL> FIXTURE_DIRS = ( <EOL> os . path . join ( PROJ_ROOT , "<STR_LIT:..>" , "<STR_LIT>" ) , <EOL> ) <EOL> INSTALLED_APPS = ( <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> ) </s>
|
<s> config = { <EOL> '<STR_LIT>' : <EOL> { u'<STR_LIT>' : { '<STR_LIT:value>' : '<STR_LIT>' , } , <EOL> u'<STR_LIT:1.0>' : { '<STR_LIT:value>' : '<STR_LIT>' , '<STR_LIT>' : False , <EOL> '<STR_LIT:size>' : <NUM_LIT> } , <EOL> } } </s>
|
<s> import string <EOL> from mammon . server import eventmgr_core , eventmgr_rfc1459 , get_context <EOL> from mammon . capability import Capability <EOL> from mammon . utility import CaseInsensitiveDict , CaseInsensitiveList <EOL> from . import monitor <EOL> cap_metadata_notify = Capability ( '<STR_LIT>' ) <EOL> metadata_key_allowed_chars = string . ascii_letters + string . digits + '<STR_LIT>' <EOL> metadata_key_allowed_chars_tbl = str . maketrans ( '<STR_LIT>' , '<STR_LIT>' , metadata_key_allowed_chars ) <EOL> def validate_metadata_key ( key_name ) : <EOL> badchars = key_name . translate ( metadata_key_allowed_chars_tbl ) <EOL> return badchars == '<STR_LIT>' <EOL> def metadata_GET ( cli , ev_msg , target_name , target ) : <EOL> if len ( ev_msg [ '<STR_LIT>' ] ) > <NUM_LIT:2> : <EOL> keys = ev_msg [ '<STR_LIT>' ] [ <NUM_LIT:2> : ] <EOL> else : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> return <EOL> restricted_keys = cli . ctx . conf . metadata . get ( '<STR_LIT>' , [ ] ) <EOL> for key in keys : <EOL> if key in target . metadata : <EOL> visibility = '<STR_LIT:*>' <EOL> if key in restricted_keys : <EOL> if cli . role and key in cli . role . metakeys_get : <EOL> visibility = '<STR_LIT>' <EOL> else : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ target_name , key , '<STR_LIT>' ] , add_target = False ) <EOL> continue <EOL> args = [ target_name , key , visibility ] <EOL> if isinstance ( target . metadata [ key ] , str ) : <EOL> args . append ( target . metadata [ key ] ) <EOL> cli . dump_numeric ( '<STR_LIT>' , args , add_target = False ) <EOL> elif not validate_metadata_key ( key ) : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ key , '<STR_LIT>' ] , add_target = False ) <EOL> else : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ target_name , key , '<STR_LIT>' ] , add_target = False ) <EOL> def metadata_LIST ( cli , ev_msg , target_name , target ) : <EOL> for key , visibility in get_visible_keys ( cli , target ) : <EOL> args = [ target_name , key , visibility ] <EOL> data = target . metadata [ key ] <EOL> if isinstance ( data , str ) : <EOL> args . append ( data ) <EOL> cli . dump_numeric ( '<STR_LIT>' , args , add_target = False ) <EOL> cli . dump_numeric ( '<STR_LIT>' , [ '<STR_LIT>' ] , add_target = False ) <EOL> def get_visible_keys ( cli , target ) : <EOL> visible_keys = [ ] <EOL> restricted_keys = cli . ctx . conf . metadata . get ( '<STR_LIT>' , [ ] ) <EOL> for key , data in target . metadata . items ( ) : <EOL> visibility = '<STR_LIT:*>' <EOL> if key in restricted_keys : <EOL> if cli . role and key in cli . role . metakeys_get : <EOL> visibility = '<STR_LIT>' <EOL> else : <EOL> continue <EOL> visible_keys . append ( [ key , visibility ] ) <EOL> return visible_keys <EOL> def metadata_SET ( cli , ev_msg , target_name , target ) : <EOL> if len ( ev_msg [ '<STR_LIT>' ] ) > <NUM_LIT:2> : <EOL> key = ev_msg [ '<STR_LIT>' ] [ <NUM_LIT:2> ] <EOL> if len ( ev_msg [ '<STR_LIT>' ] ) > <NUM_LIT:3> : <EOL> value = ev_msg [ '<STR_LIT>' ] [ <NUM_LIT:3> ] <EOL> else : <EOL> value = None <EOL> else : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> return <EOL> if not cli . able_to_edit_metadata ( target ) : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ target_name , '<STR_LIT:*>' , '<STR_LIT>' ] , add_target = False ) <EOL> return <EOL> restricted_keys = cli . ctx . conf . metadata . get ( '<STR_LIT>' , [ ] ) <EOL> whitelist = cli . ctx . conf . metadata . get ( '<STR_LIT>' , [ ] ) <EOL> blacklist = cli . ctx . conf . metadata . get ( '<STR_LIT>' , [ ] ) <EOL> is_valid = False <EOL> if validate_metadata_key ( key ) : <EOL> if key not in blacklist : <EOL> if key in whitelist or not whitelist or key in restricted_keys : <EOL> is_valid = True <EOL> if not is_valid : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ key , '<STR_LIT>' ] , add_target = False ) <EOL> return <EOL> key_restricted = False <EOL> visibility = '<STR_LIT:*>' <EOL> if key in restricted_keys : <EOL> if cli . role and key in cli . role . metakeys_set : <EOL> visibility = '<STR_LIT>' <EOL> else : <EOL> key_restricted = True <EOL> if key_restricted : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ target_name , key , '<STR_LIT>' ] , add_target = False ) <EOL> return <EOL> if value : <EOL> if key not in target . user_set_metadata and key not in restricted_keys : <EOL> limit = cli . ctx . conf . metadata . get ( '<STR_LIT>' , None ) <EOL> if limit is not None : <EOL> if len ( target . user_set_metadata ) + <NUM_LIT:1> > limit : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ target_name , '<STR_LIT>' ] , add_target = False ) <EOL> return <EOL> if not value and key not in target . metadata : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ target_name , key , '<STR_LIT>' ] , add_target = False ) <EOL> return <EOL> info = { <EOL> '<STR_LIT:key>' : key , <EOL> '<STR_LIT:value>' : value , <EOL> '<STR_LIT:source>' : cli , <EOL> '<STR_LIT:target>' : target , <EOL> '<STR_LIT>' : target_name , <EOL> '<STR_LIT>' : visibility , <EOL> } <EOL> eventmgr_core . dispatch ( '<STR_LIT>' , info ) <EOL> def metadata_CLEAR ( cli , ev_msg , target_name , target ) : <EOL> if not cli . able_to_edit_metadata ( target ) : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ target_name , '<STR_LIT:*>' , '<STR_LIT>' ] , add_target = False ) <EOL> return <EOL> restricted_keys = cli . ctx . conf . metadata . get ( '<STR_LIT>' , [ ] ) <EOL> viewable_keys = CaseInsensitiveList ( ) <EOL> if cli . role : <EOL> viewable_keys += restricted_keys + cli . role . metakeys_get + cli . role . metakeys_set <EOL> key_list = { } <EOL> for key , data in dict ( target . metadata ) . items ( ) : <EOL> visibility = '<STR_LIT:*>' <EOL> if key in restricted_keys : <EOL> if key not in viewable_keys : <EOL> continue <EOL> elif cli . role and key in cli . role . metakeys_set : <EOL> visibility = '<STR_LIT>' <EOL> else : <EOL> continue <EOL> key_list [ key ] = { <EOL> '<STR_LIT>' : visibility , <EOL> } <EOL> info = { <EOL> '<STR_LIT:source>' : cli , <EOL> '<STR_LIT:target>' : target , <EOL> '<STR_LIT>' : target_name , <EOL> '<STR_LIT>' : key_list , <EOL> } <EOL> eventmgr_core . dispatch ( '<STR_LIT>' , info ) <EOL> metadata_cmds = { <EOL> '<STR_LIT>' : metadata_GET , <EOL> '<STR_LIT:list>' : metadata_LIST , <EOL> '<STR_LIT>' : metadata_SET , <EOL> '<STR_LIT>' : metadata_CLEAR , <EOL> } <EOL> metadata_cmds = CaseInsensitiveDict ( ** metadata_cmds ) <EOL> @ eventmgr_rfc1459 . message ( '<STR_LIT>' , min_params = <NUM_LIT:2> ) <EOL> def m_METADATA ( cli , ev_msg ) : <EOL> target_name , subcmd = ev_msg [ '<STR_LIT>' ] [ : <NUM_LIT:2> ] <EOL> if subcmd not in metadata_cmds : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ '<STR_LIT>' , subcmd , '<STR_LIT>' ] ) <EOL> return <EOL> if target_name == '<STR_LIT:*>' : <EOL> target = cli <EOL> else : <EOL> target = cli . ctx . channels . get ( target_name , None ) <EOL> if target is None : <EOL> target = cli . ctx . clients . get ( target_name , None ) <EOL> if target is None : <EOL> cli . dump_numeric ( '<STR_LIT>' , [ target_name , '<STR_LIT>' ] , add_target = False ) <EOL> return <EOL> metadata_cmds [ subcmd ] ( cli , ev_msg , target_name , target ) <EOL> def set_key ( target , key , value = None ) : <EOL> ctx = get_context ( ) <EOL> if value is None : <EOL> try : <EOL> del target . metadata [ key ] <EOL> target . user_set_metadata . remove ( key ) <EOL> except ( KeyError , ValueError ) : <EOL> pass <EOL> else : <EOL> target . metadata [ key ] = value <EOL> restricted_keys = ctx . conf . metadata . get ( '<STR_LIT>' , [ ] ) <EOL> if key not in target . user_set_metadata and key not in restricted_keys : <EOL> target . user_set_metadata . append ( key ) <EOL> target . metadata [ key ] = value <EOL> def get_monitor_list ( source , target ) : <EOL> monitor_list = monitor . monitored . get ( target . nickname , [ ] ) <EOL> monitor_list += target . get_common_peers ( exclude = monitor_list + [ source ] , cap = '<STR_LIT>' ) <EOL> return monitor_list <EOL> def dump_metadata_notify ( source , target , key , args , monitor_list = None , restricted_keys = None ) : <EOL> if monitor_list is None : <EOL> monitor_list = get_monitor_list ( source , target ) <EOL> if restricted_keys is None : <EOL> ctx = get_context ( ) <EOL> restricted_keys = ctx . conf . metadata . get ( '<STR_LIT>' , [ ] ) <EOL> for cli in monitor_list : <EOL> if key in restricted_keys and ( not cli . role or key not in cli . role . metakeys_get ) : <EOL> continue <EOL> if cli == source or cli == target : <EOL> continue <EOL> if cli . servername == ctx . conf . name : <EOL> cli . dump_verb ( '<STR_LIT>' , args ) <EOL> @ eventmgr_core . handler ( '<STR_LIT>' , priority = <NUM_LIT:1> , local_client = '<STR_LIT:source>' ) <EOL> def m_metadata_clear ( info ) : <EOL> ctx = get_context ( ) <EOL> restricted_keys = ctx . conf . metadata . get ( '<STR_LIT>' , [ ] ) <EOL> source = info [ '<STR_LIT:source>' ] <EOL> target = info [ '<STR_LIT:target>' ] <EOL> target_name = info [ '<STR_LIT>' ] <EOL> keys = info [ '<STR_LIT>' ] <EOL> monitor_list = get_monitor_list ( source , target ) <EOL> for key , kinfo in keys . items ( ) : <EOL> visibility = kinfo [ '<STR_LIT>' ] <EOL> args = [ target_name , key , visibility ] <EOL> source . dump_numeric ( '<STR_LIT>' , args , add_target = False ) <EOL> info = { <EOL> '<STR_LIT:key>' : key , <EOL> '<STR_LIT:source>' : source , <EOL> '<STR_LIT:target>' : target , <EOL> '<STR_LIT>' : target_name , <EOL> '<STR_LIT>' : visibility , <EOL> } <EOL> eventmgr_core . dispatch ( '<STR_LIT>' , info ) <EOL> source . dump_numeric ( '<STR_LIT>' , [ '<STR_LIT>' ] , add_target = False ) <EOL> @ eventmgr_core . handler ( '<STR_LIT>' , priority = <NUM_LIT:1> ) <EOL> def m_metadata_delete ( info ) : <EOL> key = info [ '<STR_LIT:key>' ] <EOL> source = info [ '<STR_LIT:source>' ] <EOL> target = info [ '<STR_LIT:target>' ] <EOL> target_name = info [ '<STR_LIT>' ] <EOL> visibility = info [ '<STR_LIT>' ] <EOL> set_key ( target , key ) <EOL> args = [ target_name , key , visibility ] <EOL> dump_metadata_notify ( source , target , key , args ) <EOL> @ eventmgr_core . handler ( '<STR_LIT>' , priority = <NUM_LIT:1> ) <EOL> def m_metadata_set ( info ) : <EOL> ctx = get_context ( ) <EOL> source = info [ '<STR_LIT:source>' ] <EOL> target = info [ '<STR_LIT:target>' ] <EOL> key = info [ '<STR_LIT:key>' ] <EOL> value = info [ '<STR_LIT:value>' ] <EOL> args = [ info [ '<STR_LIT>' ] , key , info [ '<STR_LIT>' ] ] <EOL> if value : <EOL> args . append ( value ) <EOL> set_key ( target , key , value ) <EOL> if source . servername == ctx . conf . name : <EOL> source . dump_numeric ( '<STR_LIT>' , args , add_target = False ) <EOL> source . dump_numeric ( '<STR_LIT>' , [ '<STR_LIT>' ] , add_target = False ) <EOL> dump_metadata_notify ( source , target , key , args ) <EOL> @ eventmgr_core . handler ( '<STR_LIT>' , priority = <NUM_LIT:1> , local_client = '<STR_LIT>' ) <EOL> def m_metadata_cap_notify ( info ) : <EOL> if '<STR_LIT>' not in info [ '<STR_LIT>' ] : <EOL> return <EOL> cli = info [ '<STR_LIT>' ] <EOL> for key , visibility in get_visible_keys ( cli , cli ) : <EOL> cli . dump_verb ( '<STR_LIT>' , [ cli . nickname , key , visibility ] ) <EOL> for nickname in cli . monitoring : <EOL> target = cli . ctx . clients . get ( nickname , None ) <EOL> if target : <EOL> for key , visibility in get_visible_keys ( cli , target ) : <EOL> cli . dump_verb ( '<STR_LIT>' , [ target . nickname , key , visibility ] ) <EOL> @ eventmgr_core . handler ( '<STR_LIT>' , priority = <NUM_LIT:1> , local_client = '<STR_LIT>' ) <EOL> def m_metadata_monitor_target ( info ) : <EOL> cli = info [ '<STR_LIT>' ] <EOL> if '<STR_LIT>' not in cli . caps : <EOL> return <EOL> for nickname in info [ '<STR_LIT>' ] : <EOL> target = cli . ctx . clients . get ( nickname , None ) <EOL> if target : <EOL> for key , visibility in get_visible_keys ( cli , target ) : <EOL> cli . dump_verb ( '<STR_LIT>' , [ target . nickname , key , visibility ] ) <EOL> @ eventmgr_core . handler ( '<STR_LIT>' , priority = <NUM_LIT:2> ) <EOL> def m_metadata_monitor_chanjoin ( info ) : <EOL> cli = info [ '<STR_LIT>' ] <EOL> ch = info [ '<STR_LIT>' ] <EOL> cli . monitoring . add ( ch . name ) <EOL> for key , visibility in get_visible_keys ( cli , ch ) : <EOL> cli . dump_verb ( '<STR_LIT>' , [ ch . name , key , visibility ] ) <EOL> @ eventmgr_core . handler ( '<STR_LIT>' , priority = <NUM_LIT:2> ) <EOL> def m_metadata_monitor_chanpart ( info ) : <EOL> cli = info [ '<STR_LIT>' ] <EOL> ch = info [ '<STR_LIT>' ] <EOL> cli . monitoring . discard ( ch . name ) </s>
|
<s> """<STR_LIT>""" <EOL> class Result ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> self . _result = { } <EOL> self . _act = None <EOL> self . _scene = None <EOL> self . _actor_gen = None <EOL> self . _good = <NUM_LIT:0> <EOL> self . _bad = <NUM_LIT:0> <EOL> def add ( self , act , scene , good , bad ) : <EOL> if act not in self . _result : <EOL> self . _result [ act ] = { } <EOL> self . _result [ act ] [ scene ] = ( good , bad ) <EOL> def set_act_scene ( self , act_object , scene_object ) : <EOL> self . _act = act_object . act_num <EOL> self . _scene = scene_object . scene_num <EOL> self . _actor_gen = scene_object . gen_actors ( ) <EOL> self . _good = <NUM_LIT:0> <EOL> self . _bad = <NUM_LIT:0> <EOL> def guess ( self , guessed_actor ) : <EOL> try : <EOL> actual_actor = next ( self . _actor_gen ) <EOL> if actual_actor == guessed_actor : <EOL> self . _good += <NUM_LIT:1> <EOL> else : <EOL> self . _bad += <NUM_LIT:1> <EOL> return actual_actor <EOL> except StopIteration : <EOL> self . add ( self . _act , self . _scene , self . _good , self . _bad ) <EOL> def __str__ ( self ) : <EOL> lines = [ ] <EOL> lines . append ( '<STR_LIT>' <EOL> % ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) ) <EOL> tot_good = tot_bad = <NUM_LIT:0> <EOL> for act in sorted ( self . _result . keys ( ) ) : <EOL> for scene in sorted ( self . _result [ act ] . keys ( ) ) : <EOL> good = self . _result [ act ] [ scene ] [ <NUM_LIT:0> ] <EOL> bad = self . _result [ act ] [ scene ] [ <NUM_LIT:1> ] <EOL> lines . append ( '<STR_LIT>' <EOL> % ( act , scene , good , bad , <NUM_LIT> * good / ( good + bad ) ) ) <EOL> tot_good += good <EOL> tot_bad += bad <EOL> lines . append ( '<STR_LIT>' <EOL> % ( '<STR_LIT>' , '<STR_LIT>' , tot_good , tot_bad , <EOL> <NUM_LIT> * tot_good / ( tot_good + tot_bad ) ) ) <EOL> return '<STR_LIT:\n>' . join ( lines ) </s>
|
<s> """<STR_LIT>""" <EOL> import csv <EOL> import pytest <EOL> def read_csv ( file_name = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def test_read_csv ( ) : <EOL> expected = [ <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:Name>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT:1>' } , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:Name>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT:2>' } , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:Name>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT:3>' } , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:Name>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT:4>' } , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:Name>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT:5>' } , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:Name>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' } , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:Name>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' } , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:Name>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' } , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT:Name>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' } <EOL> ] <EOL> assert expected == read_csv ( ) <EOL> def main ( ) : <EOL> return pytest . main ( __file__ ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> main ( ) </s>
|
<s> """<STR_LIT>""" <EOL> import numpy as np <EOL> import pandas as pa <EOL> from . . nodes import MDFNode , MDFEvalNode <EOL> from collections import deque , defaultdict <EOL> import datetime <EOL> import operator <EOL> import csv <EOL> import matplotlib . pyplot as pp <EOL> import sys <EOL> import types <EOL> if sys . version_info [ <NUM_LIT:0> ] > <NUM_LIT:2> : <EOL> basestring = str <EOL> def _get_labels ( node , label = None , value = None ) : <EOL> """<STR_LIT>""" <EOL> if value is not None : <EOL> if label is None : <EOL> label = _get_labels ( node ) [ <NUM_LIT:0> ] <EOL> if isinstance ( value , ( tuple , list , np . ndarray , pa . core . generic . NDFrame , pa . Index ) ) : <EOL> if isinstance ( label , ( tuple , list , np . ndarray , pa . core . generic . NDFrame , pa . Index ) ) : <EOL> label = list ( label ) <EOL> if len ( label ) < len ( value ) : <EOL> label += [ "<STR_LIT>" % ( label , i ) for i in xrange ( len ( label ) , len ( value ) ) ] <EOL> return label [ : len ( value ) ] <EOL> if isinstance ( value , pa . Series ) : <EOL> return [ "<STR_LIT>" % ( label , c ) for c in value . index ] <EOL> return [ "<STR_LIT>" % ( label , i ) for i in xrange ( len ( value ) ) ] <EOL> if isinstance ( label , ( tuple , list , np . ndarray , pa . core . generic . NDFrame ) ) : <EOL> return list ( label [ : <NUM_LIT:1> ] ) <EOL> return [ label ] <EOL> if label is not None : <EOL> if isinstance ( label , ( tuple , list , np . ndarray , pa . core . generic . NDFrame ) ) : <EOL> return list ( label [ : <NUM_LIT:1> ] ) <EOL> return [ label ] <EOL> if isinstance ( node , MDFNode ) : <EOL> return [ node . name . split ( "<STR_LIT:.>" ) . pop ( ) ] <EOL> return [ str ( node ) ] <EOL> def _relabel ( columns , node_names , short_names , ctx_ids ) : <EOL> """<STR_LIT>""" <EOL> assert len ( columns ) == len ( node_names ) == len ( short_names ) == len ( ctx_ids ) <EOL> def _get_overlapping ( columns ) : <EOL> col_count = { } <EOL> overlapping = set ( ) <EOL> for cols in columns : <EOL> for col in cols : <EOL> col_count . setdefault ( col , <NUM_LIT:0> ) <EOL> col_count [ col ] += <NUM_LIT:1> <EOL> if col_count [ col ] > <NUM_LIT:1> : <EOL> overlapping . add ( col ) <EOL> return overlapping <EOL> overlap = _get_overlapping ( columns ) <EOL> if not overlap : <EOL> return columns <EOL> columns = [ list ( cols ) for cols in columns ] <EOL> overlap_node_names = { } <EOL> for i , ( cols , node_name , short_name , ctx_id ) in enumerate ( zip ( columns , node_names , short_names , ctx_ids ) ) : <EOL> for j , col in enumerate ( cols ) : <EOL> if col in overlap : <EOL> overlap_node_names . setdefault ( col , [ ] ) . append ( ( i , j , node_name , short_name , ctx_id ) ) <EOL> for col , details in overlap_node_names . iteritems ( ) : <EOL> is_ , js_ , node_names , short_names , ctx_ids = zip ( * details ) <EOL> unique_short_names = np . unique ( short_names ) <EOL> if unique_short_names . size == len ( short_names ) : <EOL> for i , j , node_name , short_name , ctx_id in details : <EOL> columns [ i ] [ j ] = "<STR_LIT>" % ( col , short_name ) <EOL> continue <EOL> unique_node_names = np . unique ( node_names ) <EOL> if unique_node_names . size == len ( node_names ) : <EOL> if unique_short_names . size == <NUM_LIT:1> and col . startswith ( unique_short_names [ <NUM_LIT:0> ] ) : <EOL> for i , j , node_name , short_name , ctx_id in details : <EOL> columns [ i ] [ j ] = col . replace ( short_name , node_name ) <EOL> else : <EOL> for i , j , node_name , short_name , ctx_id in details : <EOL> columns [ i ] [ j ] = "<STR_LIT>" % ( col , node_name ) <EOL> continue <EOL> unique_ctx_ids = np . unique ( ctx_ids ) <EOL> if unique_ctx_ids . size == len ( ctx_ids ) : <EOL> for i , j , node_name , short_name , ctx_id in details : <EOL> columns [ i ] [ j ] = "<STR_LIT>" % ( col , ctx_id ) <EOL> continue <EOL> for x in xrange ( len ( details ) ) : <EOL> columns [ i ] [ j ] = "<STR_LIT>" % ( col , x ) <EOL> return columns <EOL> def _pairs_to_node_label_lists ( node_label_pairs ) : <EOL> results = [ ] <EOL> for node_or_node_label_pair in node_label_pairs : <EOL> if isinstance ( node_or_node_label_pair , ( tuple , list ) ) : <EOL> results . append ( node_or_node_label_pair ) <EOL> else : <EOL> results . append ( ( node_or_node_label_pair , None ) ) <EOL> return map ( list , zip ( * results ) ) <EOL> class CSVWriter ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , fh , nodes , columns = None ) : <EOL> """<STR_LIT>""" <EOL> self . fh = fh <EOL> self . open_fhs = [ ] <EOL> self . writers = { } <EOL> if not isinstance ( fh , MDFNode ) : <EOL> if isinstance ( fh , basestring ) : <EOL> fh = open ( fh , "<STR_LIT:wb>" ) <EOL> self . open_fhs . append ( fh ) <EOL> writer = csv . writer ( fh ) <EOL> self . writers = defaultdict ( lambda : writer ) <EOL> self . handlers = None <EOL> if isinstance ( nodes , MDFNode ) : <EOL> nodes = [ nodes ] <EOL> if len ( nodes ) > <NUM_LIT:1> and columns is None : <EOL> self . nodes , self . columns = _pairs_to_node_label_lists ( nodes ) <EOL> else : <EOL> self . nodes = nodes <EOL> self . columns = list ( columns or [ ] ) [ : len ( nodes ) ] <EOL> self . columns += [ None ] * ( len ( nodes ) - len ( self . columns ) ) <EOL> def __del__ ( self ) : <EOL> self . close ( ) <EOL> def close ( self ) : <EOL> """<STR_LIT>""" <EOL> while self . open_fhs : <EOL> fh = self . open_fhs . pop ( ) <EOL> fh . close ( ) <EOL> self . writers . clear ( ) <EOL> def __call__ ( self , date , ctx ) : <EOL> values = [ ctx . get_value ( node ) for node in self . nodes ] <EOL> ctx_id = ctx . get_id ( ) <EOL> try : <EOL> writer = self . writers [ ctx_id ] <EOL> except KeyError : <EOL> fh = self . fh <EOL> if isinstance ( fh , MDFNode ) : <EOL> fh = ctx . get_value ( fh ) <EOL> if isinstance ( fh , basestring ) : <EOL> fh = open ( fh , "<STR_LIT:wb>" ) <EOL> self . open_fhs . append ( fh ) <EOL> writer = self . writers [ ctx_id ] = csv . writer ( fh ) <EOL> if self . handlers is None : <EOL> header = [ "<STR_LIT:date>" ] <EOL> self . handlers = [ ] <EOL> for node , value , column in zip ( self . nodes , values , self . columns ) : <EOL> if isinstance ( column , MDFNode ) : <EOL> column = ctx . get_value ( column ) <EOL> header . extend ( _get_labels ( node , column , value ) ) <EOL> if isinstance ( value , ( basestring , int , float , bool , datetime . date ) ) : <EOL> self . handlers . append ( self . _write_basetype ) <EOL> elif isinstance ( value , ( list , tuple , np . ndarray , pa . Index , pa . core . generic . NDFrame ) ) : <EOL> self . handlers . append ( self . _write_list ) <EOL> elif isinstance ( value , pa . Series ) : <EOL> self . handlers . append ( self . _write_series ) <EOL> else : <EOL> raise Exception ( "<STR_LIT>" % ( type ( value ) , node ) ) <EOL> writer . writerow ( header ) <EOL> row = [ date ] <EOL> for handler , value in zip ( self . handlers , values ) : <EOL> handler ( value , row ) <EOL> writer . writerow ( row ) <EOL> def _write_basetype ( self , value , row ) : <EOL> row . append ( value ) <EOL> def _write_list ( self , value , row ) : <EOL> row . extend ( value ) <EOL> def _write_series ( self , value , row ) : <EOL> row . extend ( value ) <EOL> class NodeTypeHandler ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , node , filter = False ) : <EOL> self . _name = node . short_name <EOL> self . _filter = node . get_filter ( ) if filter and isinstance ( node , MDFEvalNode ) else None <EOL> self . _index = [ ] <EOL> self . _labels = set ( ) <EOL> self . _data = dict ( ) <EOL> def handle ( self , date , ctx , value ) : <EOL> """<STR_LIT>""" <EOL> if self . _filter is None or ctx [ self . _filter ] : <EOL> self . _index . append ( date ) <EOL> self . _handle ( date , value ) <EOL> def _handle ( self , date , value ) : <EOL> raise NotImplementedError ( "<STR_LIT>" ) <EOL> def get_dataframe ( self , dtype = object ) : <EOL> """<STR_LIT>""" <EOL> columns = self . get_columns ( ) <EOL> df = pa . DataFrame ( data = { } , index = self . _index , columns = columns , dtype = dtype ) <EOL> for ( d , l ) , value in self . _data . items ( ) : <EOL> df [ l ] [ d ] = value <EOL> return df <EOL> def get_columns ( self ) : <EOL> """<STR_LIT>""" <EOL> return sorted ( self . _labels ) <EOL> class NodeListTypeHandler ( NodeTypeHandler ) : <EOL> def __init__ ( self , node , filter = False ) : <EOL> super ( NodeListTypeHandler , self ) . __init__ ( node , filter = filter ) <EOL> def _handle ( self , date , value ) : <EOL> self . _labels = self . _labels or [ self . _name + "<STR_LIT:.>" + str ( i ) for i in range ( len ( value ) ) ] <EOL> assert len ( self . _labels ) == len ( value ) <EOL> for l , v in zip ( self . _labels , value ) : <EOL> self . _data [ ( date , l ) ] = v <EOL> class NodeDictTypeHandler ( NodeTypeHandler ) : <EOL> def __init__ ( self , node , filter = False ) : <EOL> super ( NodeDictTypeHandler , self ) . __init__ ( node , filter = filter ) <EOL> def _handle ( self , date , value ) : <EOL> self . _labels = self . _labels . union ( map ( str , value . keys ( ) ) ) <EOL> for k , v in value . items ( ) : <EOL> self . _data [ ( date , str ( k ) ) ] = v <EOL> class NodeSeriesTypeHandler ( NodeTypeHandler ) : <EOL> def __init__ ( self , node , filter = False ) : <EOL> super ( NodeSeriesTypeHandler , self ) . __init__ ( node , filter = filter ) <EOL> def _handle ( self , date , value ) : <EOL> self . _labels = self . _labels . union ( map ( str , value . index ) ) <EOL> for l in value . index : <EOL> self . _data [ ( date , str ( l ) ) ] = value [ l ] <EOL> class NodeBaseTypeHandler ( NodeTypeHandler ) : <EOL> def __init__ ( self , node , filter = False ) : <EOL> super ( NodeBaseTypeHandler , self ) . __init__ ( node , filter = filter ) <EOL> self . _labels . add ( self . _name ) <EOL> def _handle ( self , date , value ) : <EOL> self . _data [ ( date , self . _name ) ] = value <EOL> class DataFrameBuilder ( object ) : <EOL> __version__ = <NUM_LIT:2> <EOL> def __init__ ( self , nodes , contexts = None , dtype = object , sparse_fill_value = None , filter = False , <EOL> start_date = None ) : <EOL> """<STR_LIT>""" <EOL> self . context_handler_dict = { } <EOL> self . filter = filter <EOL> self . dtype = object <EOL> self . sparse_fill_value = None <EOL> self . start_date = start_date <EOL> self . _finalized = False <EOL> self . _cached_dataframes = { } <EOL> self . _cached_columns = { } <EOL> if isinstance ( nodes , MDFNode ) : <EOL> nodes = [ nodes ] <EOL> self . nodes = nodes <EOL> if contexts : <EOL> assert len ( contexts ) == len ( nodes ) <EOL> else : <EOL> contexts = [ ] <EOL> self . contexts = contexts <EOL> self . _last_ctx = None <EOL> def __call__ ( self , date , ctx ) : <EOL> self . _version_ = self . __version__ <EOL> self . _last_ctx = ctx . get_id ( ) <EOL> ctx_list = self . contexts or ( [ ctx ] * len ( self . nodes ) ) <EOL> for ctx_ , node in zip ( ctx_list , self . nodes ) : <EOL> node_value = ctx_ . get_value ( node ) <EOL> handler_dict = self . context_handler_dict . setdefault ( ctx . get_id ( ) , { } ) <EOL> key = ( node . name , node . short_name , ctx_ . get_id ( ) ) <EOL> handler = handler_dict . get ( key ) <EOL> if not handler : <EOL> if isinstance ( node_value , ( basestring , int , float , bool , datetime . date ) ) or isinstance ( node_value , tuple ( np . typeDict . values ( ) ) ) : <EOL> handler = NodeBaseTypeHandler ( node , filter = self . filter ) <EOL> elif isinstance ( node_value , dict ) : <EOL> handler = NodeDictTypeHandler ( node , filter = self . filter ) <EOL> elif isinstance ( node_value , pa . Series ) : <EOL> handler = NodeSeriesTypeHandler ( node , filter = self . filter ) <EOL> elif isinstance ( node_value , ( list , tuple , deque , np . ndarray , pa . Index , pa . core . generic . NDFrame ) ) : <EOL> handler = NodeListTypeHandler ( node , filter = self . filter ) <EOL> else : <EOL> raise Exception ( "<STR_LIT>" % ( type ( node_value ) , node ) ) <EOL> handler_dict [ key ] = handler <EOL> if ( self . start_date is None ) or ( date >= self . start_date ) : <EOL> handler . handle ( date , ctx_ , node_value ) <EOL> def clear ( self ) : <EOL> self . context_handler_dict . clear ( ) <EOL> self . _cached_columns . clear ( ) <EOL> self . _cached_dataframes . clear ( ) <EOL> def get_dataframe ( self , ctx , dtype = None , sparse_fill_value = None ) : <EOL> ctx_id = ctx if isinstance ( ctx , int ) else ctx . get_id ( ) <EOL> try : <EOL> return self . _cached_dataframes [ ctx_id ] <EOL> except KeyError : <EOL> pass <EOL> if dtype is None : <EOL> dtype = self . dtype <EOL> result_df = self . _build_dataframe ( ctx_id , dtype ) <EOL> if sparse_fill_value is None : <EOL> sparse_fill_value = self . sparse_fill_value <EOL> if sparse_fill_value is not None : <EOL> try : <EOL> result_df = result_df . to_sparse ( fill_value = sparse_fill_value ) <EOL> except TypeError : <EOL> pass <EOL> return result_df . convert_objects ( ) <EOL> def _build_dataframe ( self , ctx , dtype ) : <EOL> """<STR_LIT>""" <EOL> ctx_id = ctx if isinstance ( ctx , int ) else ctx . get_id ( ) <EOL> handler_dict = self . context_handler_dict [ ctx_id ] <EOL> if len ( handler_dict ) == <NUM_LIT:1> : <EOL> handler = next ( iter ( handler_dict . values ( ) ) ) <EOL> result_df = handler . get_dataframe ( dtype = dtype ) <EOL> else : <EOL> result_df = pa . DataFrame ( dtype = dtype ) <EOL> handler_keys , handlers = zip ( * handler_dict . items ( ) ) <EOL> dataframes = [ h . get_dataframe ( dtype = dtype ) for h in handlers ] <EOL> all_columns = [ df . columns for df in dataframes ] <EOL> node_names , short_names , ctx_ids = zip ( * handler_keys ) <EOL> new_columns = _relabel ( all_columns , node_names , short_names , ctx_ids ) <EOL> for df , cols in zip ( dataframes , new_columns ) : <EOL> df . columns = cols <EOL> for df in dataframes : <EOL> result_df = result_df . join ( df , how = "<STR_LIT>" ) <EOL> result_df = result_df . reindex ( columns = sorted ( result_df . columns ) ) <EOL> return result_df <EOL> def get_columns ( self , node , ctx ) : <EOL> """<STR_LIT>""" <EOL> ctx_id = ctx if isinstance ( ctx , int ) else ctx . get_id ( ) <EOL> try : <EOL> return self . _cached_columns [ ( ctx_id , node ) ] <EOL> except KeyError : <EOL> pass <EOL> handler_dict = self . context_handler_dict [ ctx_id ] <EOL> columns = [ ] <EOL> ctx_ids = [ ] <EOL> for ( node_name , short_name , sub_ctx_id ) , handler in handler_dict . items ( ) : <EOL> if node_name == node . name and short_name == node . short_name : <EOL> columns . append ( handler . get_columns ( ) ) <EOL> ctx_ids . append ( sub_ctx_id ) <EOL> columns = _relabel ( columns , <EOL> [ node . name ] * len ( columns ) , <EOL> [ node . short_name ] * len ( columns ) , <EOL> ctx_ids ) <EOL> return reduce ( operator . add , columns , [ ] ) <EOL> @ property <EOL> def dataframes ( self ) : <EOL> """<STR_LIT>""" <EOL> return [ self . get_dataframe ( ctx ) for ctx in self . context_handler_dict . keys ( ) ] <EOL> @ property <EOL> def dataframe ( self ) : <EOL> return self . get_dataframe ( self . _last_ctx ) if self . _last_ctx is not None else None <EOL> def plot ( self , show = True , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> for df in self . dataframes : <EOL> df . plot ( ** kwargs ) <EOL> legend = sorted ( df . columns ) <EOL> pp . legend ( legend , loc = '<STR_LIT>' , bbox_to_anchor = ( <NUM_LIT:0.5> , - <NUM_LIT> ) , fancybox = True , shadow = True ) <EOL> if show : <EOL> pp . show ( ) <EOL> def finalize ( self ) : <EOL> """<STR_LIT>""" <EOL> assert not self . _finalized <EOL> for ctx_id in list ( self . context_handler_dict . keys ( ) ) : <EOL> for node in self . nodes : <EOL> self . _cached_columns [ ( ctx_id , node ) ] = self . get_columns ( node , ctx_id ) <EOL> self . _cached_dataframes [ ctx_id ] = self . get_dataframe ( ctx_id ) <EOL> del self . context_handler_dict [ ctx_id ] <EOL> assert len ( self . context_handler_dict ) == <NUM_LIT:0> <EOL> if not hasattr ( self , "<STR_LIT>" ) : <EOL> self . _version_ = self . __version__ <EOL> self . _finalized = True <EOL> def combine_result ( self , other , other_ctx , ctx ) : <EOL> """<STR_LIT>""" <EOL> ctx_id = ctx . get_id ( ) <EOL> other_ctx_id = other_ctx . get_id ( ) <EOL> if not self . _finalized : <EOL> self . finalize ( ) <EOL> nodes = set ( self . nodes ) <EOL> other_nodes = set ( other . nodes ) <EOL> additional_nodes = other_nodes . difference ( nodes ) <EOL> self . nodes += list ( additional_nodes ) <EOL> for node in other . nodes : <EOL> self . _cached_columns [ ( ctx_id , node ) ] = other . get_columns ( node , other_ctx_id ) <EOL> self . _cached_dataframes [ ctx_id ] = other . get_dataframe ( other_ctx_id ) <EOL> class FinalValueCollector ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , nodes ) : <EOL> if isinstance ( nodes , MDFNode ) : <EOL> nodes = [ nodes ] <EOL> self . __nodes = nodes <EOL> self . __values = { } <EOL> self . __contexts = [ ] <EOL> def __call__ ( self , date , ctx ) : <EOL> ctx_id = ctx . get_id ( ) <EOL> self . __values [ ctx_id ] = [ ctx . get_value ( node ) for node in self . __nodes ] <EOL> if ctx_id not in self . __contexts : <EOL> self . __contexts . append ( ctx_id ) <EOL> def clear ( self ) : <EOL> """<STR_LIT>""" <EOL> self . __values . clear ( ) <EOL> self . __contexts = [ ] <EOL> def get_values ( self , ctx = None ) : <EOL> """<STR_LIT>""" <EOL> if not self . __values : <EOL> return None <EOL> if ctx is None : <EOL> ctx = self . __contexts [ - <NUM_LIT:1> ] <EOL> ctx_id = ctx if isinstance ( ctx , int ) else ctx . get_id ( ) <EOL> return self . __values . get ( ctx_id , None ) <EOL> def get_dict ( self , ctx = None ) : <EOL> """<STR_LIT>""" <EOL> values = self . get_values ( ctx ) <EOL> if values is None : <EOL> return None <EOL> return dict ( zip ( self . __nodes , values ) ) <EOL> @ property <EOL> def values ( self ) : <EOL> """<STR_LIT>""" <EOL> if not self . __contexts : <EOL> return None <EOL> ctx_id = self . __contexts [ - <NUM_LIT:1> ] <EOL> return self . get_values ( ctx_id ) <EOL> class NodeLogger ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , nodes , fh = sys . stdout ) : <EOL> """<STR_LIT>""" <EOL> self . nodes = nodes <EOL> self . fh = fh <EOL> def __call__ ( self , date , ctx ) : <EOL> max_len = max ( ( len ( node . name ) for node in self . nodes ) ) <EOL> fmt = "<STR_LIT>" % max_len <EOL> root_ctx = ctx <EOL> values = [ None ] * len ( self . nodes ) <EOL> for i , node in enumerate ( self . nodes ) : <EOL> values [ i ] = ctx [ node ] <EOL> self . fh . write ( "<STR_LIT>" % ctx ) <EOL> for node , value in zip ( self . nodes , values ) : <EOL> self . fh . write ( fmt % ( node . name , value ) ) <EOL> self . fh . write ( "<STR_LIT:\n>" ) <EOL> while True : <EOL> prev_values = list ( values ) <EOL> yield <EOL> for i , node in enumerate ( self . nodes ) : <EOL> if node . has_value ( ctx ) : <EOL> values [ i ] = ctx [ node ] <EOL> if values != prev_values : <EOL> self . fh . write ( "<STR_LIT>" % ctx ) <EOL> for node , value , prev_value in zip ( self . nodes , values , prev_values ) : <EOL> if value != prev_value : <EOL> self . fh . write ( fmt % ( node . name , value ) ) <EOL> self . fh . write ( "<STR_LIT:\n>" ) </s>
|
<s> """<STR_LIT>""" <EOL> import unittest <EOL> from mdf . parser import tokenize <EOL> class PylabParserTest ( unittest . TestCase ) : <EOL> def test_simple_parse ( self ) : <EOL> test = "<STR_LIT>" <EOL> expected = [ "<STR_LIT>" , "<STR_LIT:T>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> actual = tokenize ( test ) <EOL> self . assertEqual ( actual , expected ) <EOL> def test_func ( self ) : <EOL> test = "<STR_LIT>" <EOL> expected = [ "<STR_LIT>" , "<STR_LIT:T>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> actual = tokenize ( test ) <EOL> self . assertEqual ( actual , expected ) <EOL> def test_index ( self ) : <EOL> test = "<STR_LIT>" <EOL> expected = [ "<STR_LIT>" , "<STR_LIT:T>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> actual = tokenize ( test ) <EOL> self . assertEqual ( actual , expected ) <EOL> def test_index_func ( self ) : <EOL> test = "<STR_LIT>" <EOL> expected = [ "<STR_LIT>" , "<STR_LIT:T>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> actual = tokenize ( test ) <EOL> self . assertEqual ( actual , expected ) <EOL> def test_func_index ( self ) : <EOL> test = "<STR_LIT>" <EOL> expected = [ "<STR_LIT>" , "<STR_LIT:T>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> actual = tokenize ( test ) <EOL> self . assertEqual ( actual , expected ) <EOL> def test_dict ( self ) : <EOL> test = "<STR_LIT>" <EOL> expected = [ "<STR_LIT>" , "<STR_LIT:T>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> actual = tokenize ( test ) <EOL> self . assertEqual ( actual , expected ) <EOL> def test_list ( self ) : <EOL> test = "<STR_LIT>" <EOL> expected = [ "<STR_LIT>" , "<STR_LIT:T>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> actual = tokenize ( test ) <EOL> self . assertEqual ( actual , expected ) <EOL> def test_multiproc ( self ) : <EOL> test = "<STR_LIT>" <EOL> expected = [ "<STR_LIT>" , "<STR_LIT:T>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> actual = tokenize ( test ) <EOL> self . assertEqual ( actual , expected ) </s>
|
<s> from distutils . core import setup <EOL> setup ( name = "<STR_LIT>" , <EOL> version = "<STR_LIT>" , <EOL> description = "<STR_LIT>" , <EOL> author = "<STR_LIT>" , <EOL> author_email = "<STR_LIT>" , <EOL> license = "<STR_LIT>" , <EOL> url = "<STR_LIT>" , <EOL> packages = [ "<STR_LIT>" ] , <EOL> long_description = "<STR_LIT>" , <EOL> ) </s>
|
<s> """<STR_LIT>""" <EOL> __license__ = """<STR_LIT>""" <EOL> __author__ = "<STR_LIT>" <EOL> try : <EOL> from version import gitver_version <EOL> __version__ = gitver_version <EOL> except ImportError : <EOL> __version__ = '<STR_LIT>' </s>
|
<s> import json <EOL> import click <EOL> import cligj <EOL> import mapbox <EOL> from mapboxcli . errors import MapboxCLIException <EOL> @ click . command ( short_help = "<STR_LIT>" ) <EOL> @ click . argument ( '<STR_LIT>' , required = True ) <EOL> @ click . argument ( '<STR_LIT>' , required = True ) <EOL> @ click . argument ( '<STR_LIT>' , required = True ) <EOL> @ cligj . features_in_arg <EOL> @ click . option ( '<STR_LIT>' , '<STR_LIT>' , type = int , default = <NUM_LIT> , <EOL> help = "<STR_LIT>" ) <EOL> @ click . option ( '<STR_LIT>' , default = True , <EOL> help = "<STR_LIT>" ) <EOL> @ click . option ( '<STR_LIT>' , default = True , <EOL> help = "<STR_LIT>" ) <EOL> @ click . option ( '<STR_LIT>' , '<STR_LIT>' , default = '<STR_LIT:->' , <EOL> help = "<STR_LIT>" ) <EOL> @ click . pass_context <EOL> def surface ( ctx , mapid , layer , fields , features , <EOL> zoom , interpolate , geojson , output ) : <EOL> """<STR_LIT>""" <EOL> stdout = click . open_file ( output , '<STR_LIT:w>' ) <EOL> access_token = ( ctx . obj and ctx . obj . get ( '<STR_LIT>' ) ) or None <EOL> fields = fields . split ( "<STR_LIT:U+002C>" ) <EOL> service = mapbox . Surface ( access_token = access_token ) <EOL> try : <EOL> res = service . surface ( <EOL> features , <EOL> mapid = mapid , <EOL> layer = layer , <EOL> fields = fields , <EOL> geojson = geojson , <EOL> interpolate = interpolate , <EOL> zoom = zoom ) <EOL> except mapbox . errors . ValidationError as exc : <EOL> raise click . BadParameter ( str ( exc ) ) <EOL> if res . status_code == <NUM_LIT:200> : <EOL> if geojson : <EOL> click . echo ( json . dumps ( res . geojson ( ) ) , file = stdout ) <EOL> else : <EOL> click . echo ( res . text , file = stdout ) <EOL> else : <EOL> raise MapboxCLIException ( res . text . strip ( ) ) </s>
|
<s> """<STR_LIT>""" <EOL> import concurrent . futures <EOL> import multiprocessing <EOL> import time <EOL> import numpy <EOL> import rasterio <EOL> from rasterio . _example import compute <EOL> def main ( infile , outfile , num_workers = <NUM_LIT:4> ) : <EOL> with rasterio . drivers ( ) : <EOL> with rasterio . open ( infile ) as src : <EOL> meta = src . meta <EOL> del meta [ '<STR_LIT>' ] <EOL> meta . update ( affine = src . affine ) <EOL> meta . update ( blockxsize = <NUM_LIT> , blockysize = <NUM_LIT> , tiled = '<STR_LIT:yes>' ) <EOL> with rasterio . open ( outfile , '<STR_LIT:w>' , ** meta ) as dst : <EOL> def jobs ( ) : <EOL> for ij , window in dst . block_windows ( ) : <EOL> data = src . read ( window = window ) <EOL> result = numpy . zeros ( data . shape , dtype = data . dtype ) <EOL> yield data , result , window <EOL> with concurrent . futures . ThreadPoolExecutor ( <EOL> max_workers = num_workers ) as executor : <EOL> future_to_window = { <EOL> executor . submit ( compute , data , res ) : ( res , window ) <EOL> for data , res , window in jobs ( ) } <EOL> for future in concurrent . futures . as_completed ( <EOL> future_to_window ) : <EOL> result , window = future_to_window [ future ] <EOL> dst . write ( result , window = window ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> import argparse <EOL> parser = argparse . ArgumentParser ( <EOL> description = "<STR_LIT>" ) <EOL> parser . add_argument ( <EOL> '<STR_LIT:input>' , <EOL> metavar = '<STR_LIT>' , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_argument ( <EOL> '<STR_LIT>' , <EOL> metavar = '<STR_LIT>' , <EOL> help = "<STR_LIT>" ) <EOL> parser . add_argument ( <EOL> '<STR_LIT>' , <EOL> metavar = '<STR_LIT>' , <EOL> type = int , <EOL> default = multiprocessing . cpu_count ( ) , <EOL> help = "<STR_LIT>" ) <EOL> args = parser . parse_args ( ) <EOL> main ( args . input , args . output , args . j ) </s>
|
<s> """<STR_LIT>""" <EOL> import logging <EOL> import click <EOL> import rasterio <EOL> import rasterio . crs <EOL> from rasterio . env import Env <EOL> @ click . command ( short_help = "<STR_LIT>" ) <EOL> @ click . option ( '<STR_LIT>' , '<STR_LIT:key>' , flag_value = '<STR_LIT>' , default = True , <EOL> help = "<STR_LIT>" ) <EOL> @ click . pass_context <EOL> def env ( ctx , key ) : <EOL> """<STR_LIT>""" <EOL> verbosity = ( ctx . obj and ctx . obj . get ( '<STR_LIT>' ) ) or <NUM_LIT:1> <EOL> stdout = click . get_text_stream ( '<STR_LIT>' ) <EOL> with Env ( CPL_DEBUG = ( verbosity > <NUM_LIT:2> ) ) as env : <EOL> if key == '<STR_LIT>' : <EOL> for k , v in sorted ( env . drivers ( ) . items ( ) ) : <EOL> stdout . write ( "<STR_LIT>" % ( k , v ) ) <EOL> stdout . write ( '<STR_LIT:\n>' ) </s>
|
<s> import rasterio <EOL> def test_checksum_band ( ) : <EOL> with rasterio . open ( '<STR_LIT>' ) as src : <EOL> checksums = [ src . checksum ( i ) for i in src . indexes ] <EOL> assert checksums == [ <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> def test_checksum_band_window ( ) : <EOL> with rasterio . open ( '<STR_LIT>' ) as src : <EOL> window = ( ( <NUM_LIT:0> , src . height ) , ( <NUM_LIT:0> , src . width ) ) <EOL> checksums = [ src . checksum ( i , window = window ) for i in src . indexes ] <EOL> assert checksums == [ <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> def test_checksum_band_window_min ( ) : <EOL> with rasterio . open ( '<STR_LIT>' ) as src : <EOL> window = ( ( <NUM_LIT:0> , <NUM_LIT:1> ) , ( <NUM_LIT:0> , <NUM_LIT:1> ) ) <EOL> checksums = [ src . checksum ( i , window = window ) for i in src . indexes ] <EOL> assert checksums == [ <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ] <EOL> def test_checksum_band_window_quarter ( ) : <EOL> """<STR_LIT>""" <EOL> with rasterio . open ( '<STR_LIT>' ) as src : <EOL> window = ( ( <NUM_LIT:0> , src . height // <NUM_LIT:2> ) , ( <NUM_LIT:0> , src . width // <NUM_LIT:2> ) ) <EOL> checksums = [ src . checksum ( i , window = window ) for i in src . indexes ] <EOL> assert checksums != [ <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> def test_checksum_band_window_too_tall ( ) : <EOL> """<STR_LIT>""" <EOL> with rasterio . open ( '<STR_LIT>' ) as src : <EOL> window = ( ( <NUM_LIT:0> , <NUM_LIT> ) , ( <NUM_LIT:0> , src . width ) ) <EOL> checksums = [ src . checksum ( i , window = window ) for i in src . indexes ] <EOL> assert checksums == [ <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] <EOL> def test_checksum_band_window_too_short ( ) : <EOL> """<STR_LIT>""" <EOL> with rasterio . open ( '<STR_LIT>' ) as src : <EOL> window = ( ( <NUM_LIT:0> , - <NUM_LIT:1> ) , ( <NUM_LIT:0> , src . width ) ) <EOL> checksums = [ src . checksum ( i , window = window ) for i in src . indexes ] <EOL> assert checksums == [ <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] </s>
|
<s> import numpy <EOL> import rasterio <EOL> def test_read_out_shape_resample_down ( ) : <EOL> with rasterio . open ( '<STR_LIT>' ) as s : <EOL> out = numpy . zeros ( ( <NUM_LIT:8> , <NUM_LIT:8> ) , dtype = rasterio . ubyte ) <EOL> data = s . read ( <NUM_LIT:1> , out = out ) <EOL> expected = numpy . array ( [ <EOL> [ <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:20> , <NUM_LIT:15> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ] , <EOL> [ <NUM_LIT:0> , <NUM_LIT:6> , <NUM_LIT> , <NUM_LIT:9> , <NUM_LIT:255> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] , <EOL> [ <NUM_LIT:0> , <NUM_LIT:7> , <NUM_LIT> , <NUM_LIT:255> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ] , <EOL> [ <NUM_LIT:0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:0> ] , <EOL> [ <NUM_LIT:0> , <NUM_LIT:9> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:255> , <NUM_LIT:0> ] , <EOL> [ <NUM_LIT:11> , <NUM_LIT:7> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:0> ] , <EOL> [ <NUM_LIT:8> , <NUM_LIT:10> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:20> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:0> ] , <EOL> [ <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:0> , <NUM_LIT:0> ] ] , dtype = numpy . uint8 ) <EOL> assert ( data == expected ) . all ( ) <EOL> def test_read_out_shape_resample_up ( ) : <EOL> with rasterio . open ( '<STR_LIT>' ) as s : <EOL> out = numpy . zeros ( ( <NUM_LIT> , <NUM_LIT> ) , dtype = rasterio . ubyte ) <EOL> data = s . read ( <NUM_LIT:1> , out = out , masked = True ) <EOL> assert data . shape == ( <NUM_LIT> , <NUM_LIT> ) <EOL> assert data . mean ( ) == s . read ( <NUM_LIT:1> , masked = True ) . mean ( ) </s>
|